diff --git a/.changeset/repo-owned-content.md b/.changeset/repo-owned-content.md new file mode 100644 index 0000000..ebde286 --- /dev/null +++ b/.changeset/repo-owned-content.md @@ -0,0 +1,5 @@ +--- +"web": patch +--- + +Move website copy and chart references into the web repository so edits can be previewed and released with the site. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 772ba54..fb1fe17 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,8 +25,6 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - with: - path: web - uses: actions/setup-node@v4 with: node-version: 24.10.0 @@ -34,29 +32,13 @@ jobs: with: bun-version: 1.3.14 - run: bun install --frozen-lockfile - working-directory: web - - name: Read pinned CMS revision - id: cms - working-directory: web - run: node scripts/cms-revision.mjs >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v4 - with: - repository: AstrologyEngine/cms - ref: ${{ steps.cms.outputs.revision }} - path: cms - persist-credentials: false - - run: bun install --frozen-lockfile && bun run contract:build - working-directory: cms - run: bun run sync && bun test verification - working-directory: web - run: bunx playwright install --with-deps chromium - working-directory: web - run: bun run test:browser - working-directory: web - uses: actions/upload-artifact@v4 if: failure() with: name: local-browser-results path: | - web/playwright-report/ - web/test-results/ + playwright-report/ + test-results/ diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 24f51bd..ef80a88 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -12,26 +12,9 @@ jobs: checks: if: github.event_name == 'release' && github.event.release.prerelease uses: ./.github/workflows/ci.yml - gate: - if: github.event_name == 'push' || (github.event_name == 'release' && github.event.release.prerelease) - runs-on: ubuntu-24.04 - env: - CMS_DEPLOY_ENABLED: ${{ vars.CMS_DEPLOY_ENABLED }} - steps: - - name: Report CMS provisioning gate - run: | - if [ "$CMS_DEPLOY_ENABLED" != true ]; then - echo "CMS deployment is disabled pending [hosted setup #39](https://github.com/AstrologyEngine/web-issues/issues/39)." >> "$GITHUB_STEP_SUMMARY" - if [ "$GITHUB_EVENT_NAME" = release ]; then - echo "::error::Alpha release blocked: complete CMS setup #39 and enable CMS_DEPLOY_ENABLED." - exit 1 - fi - else - echo "CMS deployment is enabled." >> "$GITHUB_STEP_SUMMARY" - fi deploy: - if: vars.CMS_DEPLOY_ENABLED == 'true' && always() && needs.gate.result == 'success' && (github.event_name == 'push' || needs.checks.result == 'success') - needs: [checks, gate] + if: always() && (github.event_name == 'push' || (github.event.release.prerelease && needs.checks.result == 'success')) + needs: checks runs-on: ubuntu-24.04 environment: ${{ github.event_name == 'push' && 'staging' || 'alpha' }} env: @@ -54,13 +37,7 @@ jobs: with: bun-version: 1.3.14 - run: bun install --frozen-lockfile - - name: Verify the target CMS deployment - run: node scripts/verify-cms-deployment.mjs "$TARGET" - env: - GH_TOKEN: ${{ github.token }} - run: bun run sync && bun run build - env: - CMS_SNAPSHOT_ORIGIN: https://cms-${{ env.TARGET }}.astrologyengine.dev - run: bunx wrangler deploy --env "$TARGET" --dry-run - name: Recheck current staging head if: github.event_name == 'push' diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 6e294ee..ad0e322 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -11,7 +11,7 @@ concurrency: cancel-in-progress: false jobs: preview: - if: github.event.pull_request.head.repo.full_name == github.repository && (github.event.action == 'closed' || vars.CMS_DEPLOY_ENABLED == 'true') + if: github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-24.04 timeout-minutes: 25 env: @@ -54,9 +54,8 @@ jobs: id=$(jq -n --arg ref "$HEAD_SHA" --arg environment "pr-$PR" '{ref:$ref,environment:$environment,auto_merge:false,required_contexts:[],transient_environment:true,production_environment:false}' | gh api -X POST "repos/$REPO/deployments" --input - --jq .id) echo "id=$id" >> "$GITHUB_OUTPUT" gh api -X POST "repos/$REPO/deployments/$id/statuses" -f state=in_progress - node scripts/verify-cms-deployment.mjs staging bun run sync - CMS_SNAPSHOT_ORIGIN=https://cms-staging.astrologyengine.dev bun run build + bun run build - name: Upload preview id: upload if: steps.deploy.outputs.id != '' diff --git a/.gitignore b/.gitignore index 8ec3a05..6627a23 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ build/ .wrangler/ static/release.json static/calculation-worker.js -static/content/ # Caches and generated test output .cache/ diff --git a/AGENTS.md b/AGENTS.md index 89ab3b8..fd500a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,3 +15,8 @@ See `docs/agents/triage-labels.md`. Single-context layout: root `GLOSSARY.md` and `docs/adr/`. See `docs/agents/domain.md`. + +### Website copy + +For UI text, translations, accessibility labels, or chart reference copy, +see [the copy editing guide](docs/agents/content.md). diff --git a/README.md b/README.md index 3621697..b7badb5 100644 --- a/README.md +++ b/README.md @@ -12,45 +12,14 @@ bun run sync bun run dev ``` -Web can install, check and build independently. Without a running CMS, local -requests use baseline copy bundled from the pinned contract package. +Run `bun run dev` to start the website. -For both services, clone [AstrologyEngine/cms](https://github.com/AstrologyEngine/cms) -as sibling `../cms` and run: +Checks include `bun run check`, `bun run check:ts`, `bun run lint`, +`bun run format:check`, `bun test verification`, `bun run build`, +both Worker dry runs, and `bun run test:browser` (install Chromium with +`bunx playwright install chromium`). -```sh -bun run dev:stack -# Other checkout/ports: -CMS_REPO_PATH=/path/to/cms WEB_PORT=5174 CMS_PORT=8789 bun run dev:stack -``` - -The launcher installs frozen dependencies, migrates/seeds persistent local D1, -watches and temporarily links the local contract, and starts CMS then web. -Ctrl+C stops its processes and restores the pinned package. Each service can -also run separately: start CMS there, then set `CMS_ORIGIN` when starting web -(default `http://127.0.0.1:8787`). - -Before committing: `bun run sync`, `bun run check`, `bun run check:ts`, -`bun run lint`, `bun run format:check`, `node --test scripts/*.test.mjs`, -`bun test verification`, `bun run build`, both environment dry runs and -`bun run test:browser` (install Chromium with `bunx playwright install chromium`). - -## CMS copy - -[CMS](https://github.com/AstrologyEngine/cms) owns website copy, the typed -catalog, locale helpers and baseline English seed. Web pins -`@astrologyengine/cms-contract` to an exact public GitHub release asset. - -New keys: update and release CMS, deploy/seed it, then update web's dependency -URL and lockfile before using those keys. Ordinary content edits use the CMS -admin API and need no web release. See the -[CMS runbook](https://github.com/AstrologyEngine/cms/blob/main/docs/runbooks/cms.md). - -Builds bundle outage snapshots from the package's baseline seed by default. -`CMS_SNAPSHOT_ORIGIN` fetches all enabled locales from a live CMS; fetch errors -fail the build. Deployed builds always use their target CMS origin. +## Website copy -Browser tests require a CMS checkout and use isolated databases for English, -a partial pseudo-locale and CMS outages. `CMS_REPO_PATH` overrides the sibling -path; `PLAYWRIGHT_PORT` changes test ports. `E2E_BASE_URL` tests an existing site -without a local CMS checkout. See [extraction details](docs/cms-extraction.md). +Edit the tracked content files and preview your changes with the web app. +See the [copy editing guide](docs/agents/content.md). diff --git a/bun.lock b/bun.lock index 7dfbd89..0138fa7 100644 --- a/bun.lock +++ b/bun.lock @@ -5,7 +5,6 @@ "": { "name": "web", "dependencies": { - "@astrologyengine/cms-contract": "https://github.com/AstrologyEngine/cms/releases/download/v0.1.0/cms-contract-0.1.0.tgz", "@js-temporal/polyfill": "0.5.1", "chrono-node": "2.10.3", "zod": "4.6.7", @@ -31,8 +30,6 @@ }, }, "packages": { - "@astrologyengine/cms-contract": ["@astrologyengine/cms-contract@https://github.com/AstrologyEngine/cms/releases/download/v0.1.0/cms-contract-0.1.0.tgz", {}, "sha512-7fRq0KR0DnhOFcYM4lr2Imf1v8kjhiTev97Cghy329wW8vJExjMzurzsWn7PIdVPqoLXA/CbJJaQ7JrWAa2u3A=="], - "@changesets/apply-release-plan": ["@changesets/apply-release-plan@8.1.1", "", { "dependencies": { "@changesets/config": "^4.0.1", "@changesets/format": "^0.1.2", "@changesets/git": "^4.0.1", "@changesets/should-skip-package": "^1.0.0", "@changesets/types": "^7.0.0", "import-meta-resolve": "^4.2.0", "jsonc-parser": "^3.3.1", "semver": "^7.8.1" } }, "sha512-nk2Hbq3M9NeHMdaIRBDvawKrQJzXB9sGyBUE5yWnIKtvdcNCPj75zBekJYr0gTT2ecJH3eFeTrc8eisPImcv0Q=="], "@changesets/assemble-release-plan": ["@changesets/assemble-release-plan@7.0.0", "", { "dependencies": { "@changesets/errors": "^1.0.0", "@changesets/get-dependents-graph": "^3.0.0", "@changesets/should-skip-package": "^1.0.0", "@changesets/types": "^7.0.0", "semver": "^7.8.1" } }, "sha512-oEW8BxdA604kGGtDSCiHr5w9Tv4UWe9I2k61IBNZzCOE1kbYaJj4v+lFQNgcEZFkUc2pV/+hASErGDvpJOZCTg=="], diff --git a/docs/README.md b/docs/README.md index e448cdb..37db269 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,9 +30,6 @@ without starting Vite. New tests in `tests/` are included automatically. Staging and alpha run the suite after deployment. Preview E2E failures fail the preview check; reports and failure traces are uploaded as workflow artifacts. -## CMS extraction gate +## Website copy -CMS is maintained in AstrologyEngine/cms. Deployment and preview creation are -disabled unless repository variable `CMS_DEPLOY_ENABLED=true`; enable only -after hosted provisioning/acceptance in web-issues#39. CMS must deploy and seed -before web. Contract release assets are independent of hosted deployment. +See the [copy editing guide](agents/content.md). diff --git a/docs/agents/content.md b/docs/agents/content.md new file mode 100644 index 0000000..999a1f3 --- /dev/null +++ b/docs/agents/content.md @@ -0,0 +1,17 @@ +# Edit website copy + +1. Search the visible text or its key with `rg -n -F 'text' src/lib/copy/content/en`. + UI files under `ui/` follow the first part of the key, such as `landing` or + `settings`. Chart descriptions, names, and keywords are in `reference/`. +2. Edit the value in JSON. Keep its existing key, placeholders such as `{date}`, + and intentional line breaks (`\n`). For new UI text, add a key to the + relevant feature file and use `t()` where it appears. Add placeholder + names to the signature in `src/lib/copy/content/placeholders.ts` when a + new key takes values. +3. Run `bun run check:content`. Run `bun run dev` and open the affected view. + For a homepage edit use `/`. For chart reference copy open `/app`, + enter birth details, and select the chart item. Include the affected view + in the PR so reviewers can verify the copy on the deployed preview. + +English provides the default copy. A translation supplies complete entries +for the keys it translates. Missing entries display in English. diff --git a/docs/runbooks/cms.md b/docs/runbooks/cms.md index 3b00361..358979f 100644 --- a/docs/runbooks/cms.md +++ b/docs/runbooks/cms.md @@ -1,7 +1,5 @@ -# CMS runbooks +# Superseded CMS runbook -The CMS is now maintained in [AstrologyEngine/cms](https://github.com/AstrologyEngine/cms). -See the [CMS runbooks document](https://github.com/AstrologyEngine/cms/blob/main/docs/runbooks/cms.md). +The web project owns site copy. See the [copy editing guide](../agents/content.md). -Original history remains in this repository. The extraction and web integration -are described in [the extraction record](../cms-extraction.md). +The [CMS extraction record](../cms-extraction.md) documents the former service. diff --git a/package.json b/package.json index b819dba..26b2ba1 100644 --- a/package.json +++ b/package.json @@ -5,24 +5,23 @@ "license": "MIT", "type": "module", "scripts": { - "dev": "bun run worker:build && node scripts/cms-snapshot.mjs && vite dev", + "dev": "bun run worker:build && vite dev", "sync": "svelte-kit sync", "check": "svelte-check --tsconfig ./tsconfig.json", "check:ts": "node node_modules/@typescript/native/bin/tsc --noEmit", "lint": "oxlint --disable-nested-config . && node scripts/check-copy.mjs", "format": "oxfmt --disable-nested-config . && prettier --plugin prettier-plugin-svelte --write \"**/*.svelte\"", "format:check": "oxfmt --disable-nested-config --check . && prettier --plugin prettier-plugin-svelte --check \"**/*.svelte\"", - "build": "bun run worker:build && node scripts/build-info.mjs && node scripts/cms-snapshot.mjs && vite build", + "build": "bun run worker:build && node scripts/build-info.mjs && vite build", "dry-run": "wrangler deploy --dry-run", "test:browser": "playwright test", "changeset": "changeset", "version:release": "changeset version && bun install --lockfile-only && bun run format", "release:publish": "node scripts/publish-release.mjs", "worker:build": "bun build src/lib/calculation/worker.ts --target browser --outfile static/calculation-worker.js", - "dev:stack": "node scripts/dev-stack.mjs" + "check:content": "bun test verification/content.test.ts" }, "dependencies": { - "@astrologyengine/cms-contract": "https://github.com/AstrologyEngine/cms/releases/download/v0.1.0/cms-contract-0.1.0.tgz", "@js-temporal/polyfill": "0.5.1", "chrono-node": "2.10.3", "zod": "4.6.7" diff --git a/playwright.config.ts b/playwright.config.ts index b84f858..edc5e1f 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,37 +1,13 @@ -import { resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { cmsRepoPath } from "./scripts/cms-repo.mjs"; import { defineConfig } from "@playwright/test"; -// Projects (docs/plans/cms.md, Phase 7): -// default – the site against a seeded local CMS -// i18n – a second CMS seeded with a partially translated pseudo-locale -// cms-down – the site with an unreachable CMS (bundled snapshot copy) const remote = process.env.E2E_BASE_URL; const port = Number(process.env.PLAYWRIGHT_PORT ?? "4173"); -const ports = { - web: port, - webDown: port + 1, - webI18n: port + 2, - cms: port + 4614, // 8787 by default - cmsI18n: port + 4615, -}; const url = (p: number) => `http://127.0.0.1:${p}`; -// Optional: use a locally installed Chromium when Playwright's download is unavailable. const chromium = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE; -const cms = (p: number, fixture?: string) => ({ - command: `bun run dev:e2e --port ${p}`, - ...(fixture ? { env: { CMS_E2E_FIXTURE: fixture } } : {}), - cwd: cmsRepoPath(), - url: `${url(p)}/health`, - reuseExistingServer: false, - timeout: 120_000, -}); -const web = (p: number, cmsOrigin: string) => ({ - command: `bun run dev --host 127.0.0.1 --port ${p} --strictPort`, +const web = (p: number, mode = "") => ({ + command: `bun run dev --host 127.0.0.1 --port ${p} --strictPort ${mode}`, url: url(p), - env: { CMS_ORIGIN: cmsOrigin }, reuseExistingServer: false, timeout: 120_000, }); @@ -56,40 +32,20 @@ export default defineConfig({ { name: "remote", use: { baseURL: remote }, - testIgnore: /i18n|cms-down/, + testIgnore: /i18n/, }, ] : [ { name: "default", - use: { baseURL: url(ports.web) }, - testIgnore: /i18n|cms-down/, + use: { baseURL: url(port) }, + testIgnore: /i18n/, }, { name: "i18n", - use: { baseURL: url(ports.webI18n) }, + use: { baseURL: url(port + 1) }, testMatch: /i18n\.spec\.ts/, }, - { - name: "cms-down", - use: { baseURL: url(ports.webDown) }, - testMatch: /cms-down\.spec\.ts/, - }, - ], - webServer: remote - ? undefined - : [ - cms(ports.cms), - cms( - ports.cmsI18n, - resolve( - fileURLToPath(new URL(".", import.meta.url)), - "tests/fixtures/cms-pseudo-locale.json", - ), - ), - web(ports.web, url(ports.cms)), - web(ports.webI18n, url(ports.cmsI18n)), - // Port 9 (discard) refuses connections: the CMS is down. - web(ports.webDown, url(9)), ], + webServer: remote ? undefined : [web(port), web(port + 1, "--mode e2e-i18n")], }); diff --git a/scripts/check-copy.mjs b/scripts/check-copy.mjs index 0f7027f..7294e64 100644 --- a/scripts/check-copy.mjs +++ b/scripts/check-copy.mjs @@ -1,6 +1,6 @@ // Fails when Svelte markup contains hardcoded copy: text nodes with letters or // literal aria-label/placeholder/title/alt/label attributes. All user-facing -// copy comes from the CMS (docs/designs/cms.md). Symbols and numbers are fine. +// copy comes from the web content files. Symbols and numbers are fine. import { readdir, readFile } from "node:fs/promises"; import { join, relative } from "node:path"; import { fileURLToPath } from "node:url"; @@ -79,7 +79,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { console.error(`${relative(".", file)}:${line}: hardcoded copy: ${text}`); if (findings.length) { console.error( - `${findings.length} hardcoded string(s). Add them to the CMS catalog and use t().`, + `${findings.length} hardcoded string(s). Add them to the web content files and use t().`, ); process.exit(1); } diff --git a/scripts/check-copy.test.mjs b/scripts/check-copy.test.mjs index a31e066..330f243 100644 --- a/scripts/check-copy.test.mjs +++ b/scripts/check-copy.test.mjs @@ -29,7 +29,7 @@ test("flags literal accessible and hint attributes", () => { ); }); -test("allows CMS expressions, symbols, numbers and non-copy attributes", () => { +test("allows copy expressions, symbols, numbers and non-copy attributes", () => { assert.deepEqual( find(`

{t("brand.name")} ✳ × ° ↗ · 12

diff --git a/scripts/cms-repo.mjs b/scripts/cms-repo.mjs deleted file mode 100644 index c09a683..0000000 --- a/scripts/cms-repo.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { existsSync } from "node:fs"; -import { resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -export const cmsRepoPath = (env = process.env) => { - const root = fileURLToPath(new URL("..", import.meta.url)); - const cms = resolve(root, env.CMS_REPO_PATH || "../cms"); - if (!existsSync(resolve(cms, "packages/contract/package.json"))) - throw new Error( - `CMS checkout missing at ${cms}. Clone AstrologyEngine/cms beside web or set CMS_REPO_PATH.`, - ); - return cms; -}; diff --git a/scripts/cms-revision.mjs b/scripts/cms-revision.mjs deleted file mode 100644 index 4e2d3f9..0000000 --- a/scripts/cms-revision.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { createRequire } from "node:module"; -const pkg = createRequire(import.meta.url)( - "@astrologyengine/cms-contract/package.json", -); -if (!/^[a-f0-9]{40}$/.test(pkg.cmsRevision)) - throw new Error("Installed CMS contract has no valid source revision"); -console.log(`revision=${pkg.cmsRevision}`); diff --git a/scripts/cms-snapshot.mjs b/scripts/cms-snapshot.mjs deleted file mode 100644 index f94e503..0000000 --- a/scripts/cms-snapshot.mjs +++ /dev/null @@ -1,89 +0,0 @@ -// Bundled outage copy (docs/designs/cms.md §9.5): one JSON file per enabled -// locale plus index.json in static/content/. -// -// CMS_SNAPSHOT_ORIGIN=https://cms-staging.astrologyengine.dev node scripts/cms-snapshot.mjs -// fetches every enabled locale; any failure fails the build. -// node scripts/cms-snapshot.mjs -// without an origin (local dev, tests): English from the CMS seed. -import { createRequire } from "node:module"; -import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; - -const getJson = async (fetch, url) => { - const response = await fetch(url); - if (!response.ok) - throw new Error(`CMS snapshot: ${url} answered ${response.status}`); - return response.json(); -}; - -const fromOrigin = async (origin, fetch) => { - const locales = await getJson(fetch, new URL("/v1/locales", origin)); - const bundles = []; - for (const { code } of locales.locales) - bundles.push(await getJson(fetch, new URL(`/v1/content/${code}`, origin))); - return { - index: { - default: locales.default, - version: Math.max(...bundles.map((bundle) => bundle.version)), - locales: locales.locales, - }, - bundles, - }; -}; - -const fromSeed = async (seedPath) => { - const seed = JSON.parse(await readFile(seedPath, "utf8")); - const chain = [seed.locale]; - return { - index: { - default: seed.locale, - version: 0, - locales: [{ code: seed.locale, name: "English", chain }], - }, - bundles: [ - { - locale: seed.locale, - default: seed.locale, - chain, - version: 0, - entries: seed.entries, - fallbacks: {}, - }, - ], - }; -}; - -export const writeSnapshot = async ({ - origin, - seedPath, - outDir, - fetch = globalThis.fetch, -}) => { - const { index, bundles } = origin - ? await fromOrigin(origin, fetch) - : await fromSeed(seedPath); - await rm(outDir, { recursive: true, force: true }); - await mkdir(outDir, { recursive: true }); - await writeFile(join(outDir, "index.json"), JSON.stringify(index)); - for (const bundle of bundles) - await writeFile( - join(outDir, `${bundle.locale}.json`), - JSON.stringify(bundle), - ); - return { source: origin ?? seedPath, locales: bundles.map((b) => b.locale) }; -}; - -if (process.argv[1] === fileURLToPath(import.meta.url)) { - const root = fileURLToPath(new URL("..", import.meta.url)); - const result = await writeSnapshot({ - origin: process.env.CMS_SNAPSHOT_ORIGIN || undefined, - seedPath: createRequire(import.meta.url).resolve( - "@astrologyengine/cms-contract/seed/en.json", - ), - outDir: join(root, "static/content"), - }); - console.log( - `CMS snapshot: ${result.locales.join(", ")} from ${result.source}`, - ); -} diff --git a/scripts/cms-snapshot.test.mjs b/scripts/cms-snapshot.test.mjs deleted file mode 100644 index 480d6a3..0000000 --- a/scripts/cms-snapshot.test.mjs +++ /dev/null @@ -1,108 +0,0 @@ -import assert from "node:assert/strict"; -import { mkdtemp, readFile, readdir, writeFile, mkdir } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { test } from "node:test"; -import { writeSnapshot } from "./cms-snapshot.mjs"; - -const read = async (dir, file) => - JSON.parse(await readFile(join(dir, file), "utf8")); -const temp = () => mkdtemp(join(tmpdir(), "cms-snapshot-")); - -const seed = { - locale: "en", - entries: { ui: { "brand.name": { text: "Astrology Engine" } }, body: {} }, -}; - -test("builds an English snapshot from the CMS seed without an origin", async () => { - const dir = await temp(); - const seedPath = join(dir, "seed.json"); - await writeFile(seedPath, JSON.stringify(seed)); - const out = join(dir, "content"); - await writeSnapshot({ seedPath, outDir: out }); - assert.deepEqual(await read(out, "index.json"), { - default: "en", - version: 0, - locales: [{ code: "en", name: "English", chain: ["en"] }], - }); - assert.deepEqual(await read(out, "en.json"), { - locale: "en", - default: "en", - chain: ["en"], - version: 0, - entries: seed.entries, - fallbacks: {}, - }); -}); - -const bundle = (locale, version) => ({ - locale, - default: "en", - chain: [locale], - version, - entries: {}, - fallbacks: {}, -}); - -test("fetches every enabled locale from the origin and replaces stale files", async () => { - const out = join(await temp(), "content"); - await mkdir(out); - await writeFile(join(out, "fr.json"), "{}"); - const requested = []; - const fetch = async (url) => { - requested.push(String(url)); - const path = new URL(url).pathname; - const body = - path === "/v1/locales" - ? { - default: "en", - locales: [ - { code: "en", name: "English", chain: ["en"] }, - { code: "es", name: "Español", chain: ["es", "en"] }, - ], - } - : bundle(path.split("/").at(-1), path.endsWith("/es") ? 9 : 8); - return new Response(JSON.stringify(body), { status: 200 }); - }; - await writeSnapshot({ origin: "https://cms.test", outDir: out, fetch }); - assert.deepEqual(requested, [ - "https://cms.test/v1/locales", - "https://cms.test/v1/content/en", - "https://cms.test/v1/content/es", - ]); - assert.deepEqual((await readdir(out)).sort(), [ - "en.json", - "es.json", - "index.json", - ]); - assert.equal((await read(out, "index.json")).version, 9); - assert.equal((await read(out, "es.json")).locale, "es"); -}); - -test("fails when the origin cannot provide a locale", async () => { - const out = join(await temp(), "content"); - const fetch = async (url) => - new URL(url).pathname === "/v1/locales" - ? new Response( - JSON.stringify({ - default: "en", - locales: [{ code: "en", name: "English", chain: ["en"] }], - }), - ) - : new Response("down", { status: 503 }); - await assert.rejects( - writeSnapshot({ origin: "https://cms.test", outDir: out, fetch }), - /503/, - ); -}); - -test("fails when the origin is unreachable", async () => { - const out = join(await temp(), "content"); - const fetch = async () => { - throw new Error("getaddrinfo ENOTFOUND"); - }; - await assert.rejects( - writeSnapshot({ origin: "https://cms.test", outDir: out, fetch }), - /ENOTFOUND/, - ); -}); diff --git a/scripts/dev-stack.mjs b/scripts/dev-stack.mjs deleted file mode 100644 index c247b38..0000000 --- a/scripts/dev-stack.mjs +++ /dev/null @@ -1,137 +0,0 @@ -import { watch } from "node:fs"; -import { resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { cmsRepoPath } from "./cms-repo.mjs"; -import { acquireStackLock, linkLocalContract } from "./local-contract.mjs"; -import { availablePort, createSupervisor, waitForReady } from "./processes.mjs"; -import { writeSnapshot } from "./cms-snapshot.mjs"; - -const port = (value, fallback) => { - const number = Number(value ?? fallback); - if (!Number.isInteger(number) || number < 1024 || number > 65535) - throw new Error(`Invalid port: ${value}`); - return number; -}; - -const runStack = async () => { - const root = fileURLToPath(new URL("..", import.meta.url)); - const cms = cmsRepoPath(); - const wp = port(process.env.WEB_PORT, 5173); - const cp = port(process.env.CMS_PORT, 8787); - const ports = [wp, cp, cp + 10000]; - if (new Set(ports).size !== ports.length || ports.some((p) => p > 65535)) - throw new Error("Stack ports must be distinct and at most 65535"); - for (const p of ports) await availablePort(p); - const releaseLock = await acquireStackLock(root); - const supervisor = createSupervisor(); - let linkSetup, seedWatcher, stopping; - const stop = () => - (stopping ??= (async () => { - seedWatcher?.close(); - await supervisor.cleanup(); - const restore = await linkSetup?.catch(() => undefined); - await restore?.(); - await releaseLock(); - })()); - const handlers = [ - ["SIGINT", 130], - ["SIGTERM", 143], - ].map(([signal, code]) => { - const handler = () => { - void stop().then(() => process.exit(code)); - }; - process.once(signal, handler); - return [signal, handler]; - }); - const env = { ...process.env, CMS_REPO_PATH: cms }; - const assertRunning = () => { - if (stopping) throw new Error("Stack is stopping"); - }; - const start = (...args) => { - assertRunning(); - return supervisor.start(...args); - }; - const run = async (args, cwd = root) => { - assertRunning(); - await supervisor.run("bun", args, cwd, env); - assertRunning(); - }; - try { - console.log(`Web: ${root}\nCMS: ${cms}`); - await run(["install", "--frozen-lockfile"]); - await run(["install", "--frozen-lockfile"], cms); - await run(["run", "contract:build"], cms); - linkSetup = linkLocalContract({ root, cms }); - await linkSetup; - assertRunning(); - await run(["run", "migrate:local"], cms); - await run(["run", "seed:local"], cms); - const contract = start("bun", ["run", "contract:watch"], cms, env); - const cu = `http://127.0.0.1:${cp}`, - wu = `http://127.0.0.1:${wp}`; - const cs = start( - "bun", - [ - "x", - "wrangler", - "dev", - "--ip", - "127.0.0.1", - "--port", - String(cp), - "--inspector-port", - String(cp + 10000), - "--show-interactive-dev-session=false", - ], - cms, - env, - ); - await waitForReady(`${cu}/health`, cs); - const ws = start( - "bun", - [ - "run", - "dev", - "--host", - "127.0.0.1", - "--port", - String(wp), - "--strictPort", - ], - root, - { ...env, CMS_ORIGIN: cu }, - ); - await waitForReady(wu, ws); - let snapshotWrite = Promise.resolve(); - seedWatcher = watch(resolve(cms, "packages/contract/seed"), () => { - snapshotWrite = snapshotWrite - .then(() => - writeSnapshot({ - seedPath: resolve(cms, "packages/contract/seed/en.json"), - outDir: resolve(root, "static/content"), - }), - ) - .catch((error) => console.error(`Snapshot update: ${error.message}`)); - }); - console.log( - `\nWeb: ${wu}\nCMS: ${cu}\nLocal data persists in the CMS checkout. Ctrl+C stops this stack.`, - ); - const name = await Promise.race( - [ - ["CMS", cs], - ["web", ws], - ["contract watcher", contract], - ].map(([name, service]) => service.done.then(() => name)), - ); - throw new Error(`${name} stopped; shutting down the stack`); - } finally { - await stop(); - for (const [signal, handler] of handlers) - process.removeListener(signal, handler); - } -}; - -runStack().catch((error) => { - console.error(error.message); - process.exitCode = 1; -}); diff --git a/scripts/local-contract.mjs b/scripts/local-contract.mjs deleted file mode 100644 index a701b25..0000000 --- a/scripts/local-contract.mjs +++ /dev/null @@ -1,88 +0,0 @@ -import { - lstat, - mkdir, - open, - readFile, - rename, - rm, - symlink, -} from "node:fs/promises"; -import { resolve } from "node:path"; - -const exists = async (path) => { - try { - await lstat(path); - return true; - } catch (error) { - if (error.code === "ENOENT") return false; - throw error; - } -}; - -// Acquire before installing dependencies so competing launchers cannot alter an active link. -export const acquireStackLock = async (root) => { - const directory = resolve(root, ".cache"); - const lockPath = resolve(directory, "cms-stack-lock"); - await mkdir(directory, { recursive: true }); - let lock; - try { - lock = await open(lockPath, "wx"); - } catch (error) { - if (error.code === "EEXIST") - throw new Error( - `Another stack owns this checkout, or a previous run was killed. Inspect ${lockPath} before recovering its contract link.`, - ); - throw error; - } - await lock.writeFile( - JSON.stringify({ - pid: process.pid, - target: resolve(root, "node_modules/@astrologyengine/cms-contract"), - backup: resolve( - root, - "node_modules/@astrologyengine/cms-contract.stack-backup", - ), - }) + "\n", - ); - await lock.close(); - return () => rm(lockPath, { force: true }); -}; - -export const linkLocalContract = async ({ root, cms }) => { - const target = resolve(root, "node_modules/@astrologyengine/cms-contract"); - const backup = `${target}.stack-backup`; - await mkdir(resolve(root, "node_modules/@astrologyengine"), { - recursive: true, - }); - let moved = false, - linked = false; - const restore = async () => { - if (linked) { - await rm(target, { recursive: true, force: true }); - linked = false; - } - if (moved) { - await rename(backup, target); - moved = false; - } - }; - try { - if (await exists(backup)) - throw new Error(`Contract backup already exists: ${backup}`); - const pkg = JSON.parse( - await readFile(resolve(cms, "packages/contract/package.json"), "utf8"), - ); - if (pkg.name !== "@astrologyengine/cms-contract") - throw new Error("Unexpected local contract package"); - if (await exists(target)) { - await rename(target, backup); - moved = true; - } - await symlink(resolve(cms, "packages/contract"), target, "dir"); - linked = true; - return restore; - } catch (error) { - await restore(); - throw error; - } -}; diff --git a/scripts/local-contract.test.mjs b/scripts/local-contract.test.mjs deleted file mode 100644 index cb4b004..0000000 --- a/scripts/local-contract.test.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import assert from "node:assert/strict"; -import { - mkdtemp, - mkdir, - readFile, - readlink, - rm, - writeFile, -} from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { resolve } from "node:path"; -import { test } from "node:test"; -import { acquireStackLock, linkLocalContract } from "./local-contract.mjs"; - -test("local contract link restores the installed package and rejects competing launchers", async () => { - const root = await mkdtemp(resolve(tmpdir(), "cms-link-")); - const cms = resolve(root, "cms"); - const target = resolve(root, "node_modules/@astrologyengine/cms-contract"); - try { - await mkdir(target, { recursive: true }); - await writeFile(resolve(target, "installed"), "pinned release"); - await mkdir(resolve(cms, "packages/contract"), { recursive: true }); - await writeFile( - resolve(cms, "packages/contract/package.json"), - '{"name":"@astrologyengine/cms-contract"}', - ); - const unlock = await acquireStackLock(root); - await assert.rejects(acquireStackLock(root), /Another stack/); - const restore = await linkLocalContract({ root, cms }); - assert.equal(await readlink(target), resolve(cms, "packages/contract")); - await restore(); - assert.equal( - await readFile(resolve(target, "installed"), "utf8"), - "pinned release", - ); - const again = await linkLocalContract({ root, cms }); - await again(); - await unlock(); - } finally { - await rm(root, { recursive: true, force: true }); - } -}); diff --git a/scripts/processes.mjs b/scripts/processes.mjs deleted file mode 100644 index 6dfe678..0000000 --- a/scripts/processes.mjs +++ /dev/null @@ -1,97 +0,0 @@ -import { spawn } from "node:child_process"; -import { createServer } from "node:net"; -import { setTimeout as delay } from "node:timers/promises"; - -export const createSupervisor = () => { - const children = new Set(); - const start = (command, args, cwd, env = process.env) => { - const child = spawn(command, args, { - cwd, - env, - detached: true, - stdio: "inherit", - }); - const done = new Promise((resolve, reject) => { - child.once("error", reject); - child.once("exit", (code, signal) => - code === 0 - ? resolve() - : reject(new Error(`${command} exited (${signal ?? code})`)), - ); - }); - void done.catch(() => {}); - const item = { child, done }; - children.add(item); - return item; - }; - const signalGroup = (pid, signal) => { - if (!pid) return false; - try { - process.kill(-pid, signal); - return true; - } catch (error) { - if (error.code !== "ESRCH") throw error; - return false; - } - }; - const stop = async (item) => { - if (signalGroup(item.child.pid, "SIGTERM")) { - await delay(250); - signalGroup(item.child.pid, "SIGKILL"); - } - children.delete(item); - }; - const run = async (...args) => { - const item = start(...args); - try { - await item.done; - } finally { - await stop(item); - } - }; - const cleanup = async () => { - await Promise.all([...children].map(stop)); - }; - return { start, run, cleanup }; -}; - -export const availablePort = (port) => - new Promise((resolve, reject) => { - const server = createServer(); - server.once("error", () => - reject( - new Error(`Port ${port} is unavailable; set WEB_PORT or CMS_PORT.`), - ), - ); - server.listen(port, "127.0.0.1", () => server.close(resolve)); - }); - -export const waitForReady = async (url, service) => { - const controller = new AbortController(); - try { - await Promise.race([ - service.done.then(() => { - throw new Error(`Service stopped before readiness: ${url}`); - }), - (async () => { - for ( - let attempt = 0; - attempt < 120 && !controller.signal.aborted; - attempt++ - ) { - try { - const response = await fetch(url, { - signal: AbortSignal.timeout(1000), - }); - await response.body?.cancel(); - if (response.ok) return; - } catch {} - await delay(1000, undefined, { signal: controller.signal }); - } - throw new Error(`Readiness timeout: ${url}`); - })(), - ]); - } finally { - controller.abort(); - } -}; diff --git a/scripts/processes.test.mjs b/scripts/processes.test.mjs deleted file mode 100644 index 4f1bcb6..0000000 --- a/scripts/processes.test.mjs +++ /dev/null @@ -1,32 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { createSupervisor, waitForReady } from "./processes.mjs"; - -test("supervisor detects early failure and only shuts down its owned processes", async () => { - const owned = createSupervisor(), - unrelated = createSupervisor(); - const other = unrelated.start( - process.execPath, - ["-e", "setInterval(()=>{},1000)"], - process.cwd(), - ); - try { - const dead = owned.start( - process.execPath, - ["-e", "process.exit(7)"], - process.cwd(), - ); - await assert.rejects(waitForReady("http://127.0.0.1:9", dead), /exited/); - const running = owned.start( - process.execPath, - ["-e", "setInterval(()=>{},1000)"], - process.cwd(), - ); - await owned.cleanup(); - await assert.rejects(running.done); - assert.doesNotThrow(() => process.kill(other.child.pid, 0)); - await owned.cleanup(); - } finally { - await unrelated.cleanup(); - } -}); diff --git a/scripts/verify-cms-deployment.mjs b/scripts/verify-cms-deployment.mjs deleted file mode 100644 index 78c80dd..0000000 --- a/scripts/verify-cms-deployment.mjs +++ /dev/null @@ -1,75 +0,0 @@ -import { createRequire } from "node:module"; -import { fileURLToPath } from "node:url"; - -const repository = "https://api.github.com/repos/AstrologyEngine/cms"; -const isRevision = (value) => /^[a-f0-9]{40}$/.test(value ?? ""); - -export const verifyCmsDeployment = async ({ - target, - revision, - token, - fetch = globalThis.fetch, -}) => { - if (!["staging", "alpha"].includes(target) || !isRevision(revision)) - throw new Error("Expected a CMS deployment target and pinned revision"); - - const read = async (path) => { - const request = (authorization) => - fetch(repository + path, { - headers: { - Accept: "application/vnd.github+json", - ...(authorization - ? { Authorization: `Bearer ${authorization}` } - : {}), - }, - signal: AbortSignal.timeout(15_000), - }); - // A repository-scoped runner token can be denied on another repository. - // The CMS deployment metadata is also public. - const first = await request(token); - const response = - token && [401, 403, 404].includes(first.status) ? await request() : first; - if (!response.ok) - throw new Error( - `Could not verify CMS ${target}: GitHub HTTP ${response.status}`, - ); - return response.json(); - }; - const [deployment] = await read( - `/deployments?environment=${target}&task=deploy&per_page=1`, - ); - if (!Number.isSafeInteger(deployment?.id) || !isRevision(deployment?.sha)) - throw new Error(`No CMS ${target} deployment recorded in GitHub`); - - const [status] = await read( - `/deployments/${deployment.id}/statuses?per_page=1`, - ); - if (status?.state !== "success") - throw new Error( - `Latest CMS ${target} deployment ${deployment.id} is ${status?.state ?? "pending"}; wait for CMS migration, seed, and smoke checks to pass.`, - ); - - if (deployment.sha !== revision) { - const comparison = await read(`/compare/${revision}...${deployment.sha}`); - if (comparison.status !== "ahead") - throw new Error( - `CMS ${target} deployment ${deployment.sha} does not include the pinned contract revision ${revision}`, - ); - } - return { revision: deployment.sha, logUrl: status.log_url }; -}; - -if (process.argv[1] === fileURLToPath(import.meta.url)) { - const target = process.argv[2]; - const contract = createRequire(import.meta.url)( - "@astrologyengine/cms-contract/package.json", - ); - const deployment = await verifyCmsDeployment({ - target, - revision: contract.cmsRevision, - token: process.env.GH_TOKEN, - }); - console.log( - `CMS ${target} verified at ${deployment.revision} (${deployment.logUrl ?? "no workflow link"})`, - ); -} diff --git a/scripts/verify-cms-deployment.test.mjs b/scripts/verify-cms-deployment.test.mjs deleted file mode 100644 index 91df98e..0000000 --- a/scripts/verify-cms-deployment.test.mjs +++ /dev/null @@ -1,87 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { verifyCmsDeployment } from "./verify-cms-deployment.mjs"; - -const revision = "a".repeat(40); -const newer = "b".repeat(40); -const assess = (answers, target = "staging") => { - const paths = []; - const result = verifyCmsDeployment({ - target, - revision, - fetch: async (url) => { - paths.push(new URL(url).pathname + new URL(url).search); - assert.ok(answers.length, "Unexpected GitHub API request"); - return Response.json(answers.shift()); - }, - }); - return { paths, result }; -}; - -test("checks the matching CMS environment and accepts a deployed descendant", async () => { - const { paths, result } = assess( - [ - [{ id: 42, sha: newer }], - [{ state: "success", log_url: "https://github.com/example" }], - { status: "ahead" }, - ], - "alpha", - ); - assert.deepEqual(await result, { - revision: newer, - logUrl: "https://github.com/example", - }); - assert.deepEqual(paths, [ - "/repos/AstrologyEngine/cms/deployments?environment=alpha&task=deploy&per_page=1", - "/repos/AstrologyEngine/cms/deployments/42/statuses?per_page=1", - `/repos/AstrologyEngine/cms/compare/${revision}...${newer}`, - ]); -}); - -test("accepts the exact pinned revision", async () => { - const { result } = assess([ - [{ id: 42, sha: revision }], - [{ state: "success" }], - ]); - assert.equal((await result).revision, revision); -}); - -test("fails when CMS has never been deployed by GitHub", async () => { - await assert.rejects(assess([[]]).result, /No CMS staging deployment/); -}); - -test("fails on the latest failed or pending deploy even if an earlier deploy succeeded", async () => { - for (const state of ["failure", "in_progress"]) - await assert.rejects( - assess([[{ id: 42, sha: revision }], [{ state }, { state: "success" }]]) - .result, - /wait for CMS migration, seed, and smoke checks/, - ); -}); - -test("rejects an older or divergent CMS deployment", async () => { - for (const status of ["behind", "diverged"]) - await assert.rejects( - assess([[{ id: 42, sha: newer }], [{ state: "success" }], { status }]) - .result, - /does not include the pinned contract revision/, - ); -}); - -test("uses the Actions token and can read public metadata if cross-repo access is denied", async () => { - const auth = []; - const result = await verifyCmsDeployment({ - target: "staging", - revision, - token: "test-token", - fetch: async (url, { headers }) => { - assert.equal(new URL(url).origin, "https://api.github.com"); - auth.push(headers.Authorization); - if (auth.length === 1) return Response.json({}, { status: 403 }); - if (auth.length === 2) return Response.json([{ id: 42, sha: revision }]); - return Response.json([{ state: "success" }]); - }, - }); - assert.equal(result.revision, revision); - assert.deepEqual(auth, ["Bearer test-token", undefined, "Bearer test-token"]); -}); diff --git a/src/app.d.ts b/src/app.d.ts index c865f06..6d7297e 100644 --- a/src/app.d.ts +++ b/src/app.d.ts @@ -13,12 +13,6 @@ declare global { interface Platform { env: { ASSETS: { fetch(input: Request | URL | string): Promise }; - CMS: { - fetch( - input: Request | URL | string, - init?: RequestInit, - ): Promise; - }; }; } } diff --git a/src/error.html b/src/error.html index c13c643..bb3e04d 100644 --- a/src/error.html +++ b/src/error.html @@ -15,7 +15,7 @@ padding: 0 1.5rem; " > - +

{ if (event.url.pathname.startsWith("/api/")) return resolve(event); - const locales = await contentSource({ - platform: event.platform, - origin: event.url.origin, - }).locales(); const { locale, persist } = chooseLocale({ query: event.url.searchParams.get("lang"), cookie: event.cookies.get("lang"), acceptLanguage: event.request.headers.get("accept-language"), - enabled: locales.locales.map((entry) => entry.code), - defaultCode: locales.default, + enabled: locales.map((entry) => entry.code), + defaultCode, }); if (persist) event.cookies.set("lang", locale, { diff --git a/src/lib/calculation/worker.ts b/src/lib/calculation/worker.ts index 2488fde..0a1696e 100644 --- a/src/lib/calculation/worker.ts +++ b/src/lib/calculation/worker.ts @@ -88,7 +88,7 @@ const dataset = async (utc: string) => { return { data, sha256: s.sha256 }; }; let queue = Promise.resolve(); -/** Stable outcome code; the page words it with CMS copy. */ +/** Stable outcome code; the page words it with site copy. */ const calculationCode = (error: unknown) => { const message = error instanceof Error ? error.message : ""; if (message === "Could not download calculation data.") diff --git a/src/lib/copy/content/en/reference/angle.json b/src/lib/copy/content/en/reference/angle.json new file mode 100644 index 0000000..be52643 --- /dev/null +++ b/src/lib/copy/content/en/reference/angle.json @@ -0,0 +1,22 @@ +{ + "ASCENDANT_SYMBOL": { + "name": "Ascendant", + "insight": "The Ascendant is where the zodiac meets the eastern horizon, symbolizing how you first meet the world.", + "keywords": ["eastern horizon", "approach"] + }, + "MIDHEAVEN": { + "name": "Midheaven", + "insight": "The Midheaven marks the zodiac’s upper meridian crossing and symbolizes vocation and public visibility.", + "keywords": ["meridian", "public life"] + }, + "DESCENDANT": { + "name": "Descendant", + "insight": "The Descendant is where the zodiac meets the western horizon, symbolizing encounters and partnerships.", + "keywords": ["western horizon", "partnership"] + }, + "IMUM_COELI": { + "name": "Imum Coeli", + "insight": "The Imum Coeli is the point opposite the Midheaven, symbolizing home, roots and private foundations.", + "keywords": ["roots", "foundation"] + } +} diff --git a/src/lib/copy/content/en/reference/aspect.json b/src/lib/copy/content/en/reference/aspect.json new file mode 100644 index 0000000..8cc740c --- /dev/null +++ b/src/lib/copy/content/en/reference/aspect.json @@ -0,0 +1,37 @@ +{ + "Conjunction": { + "name": "Conjunction", + "insight": "A conjunction places two chart factors near the same zodiac position, symbolically combining their themes.", + "keywords": ["union", "focus"] + }, + "Semisextile": { + "name": "Semisextile", + "insight": "A semisextile places two chart factors about 30° apart, interpreted here as a subtle need to accommodate differences.", + "keywords": ["adjustment", "awareness"] + }, + "Sextile": { + "name": "Sextile", + "insight": "A sextile places two chart factors about 60° apart, symbolizing opportunities for cooperation.", + "keywords": ["opportunity", "cooperation"] + }, + "Square": { + "name": "Square", + "insight": "A square places two chart factors about 90° apart, symbolizing friction between themes that call for attention.", + "keywords": ["tension", "action"] + }, + "Trine": { + "name": "Trine", + "insight": "A trine places two chart factors about 120° apart, symbolizing ease and mutual support.", + "keywords": ["flow", "ease"] + }, + "Quincunx": { + "name": "Quincunx", + "insight": "A quincunx places two chart factors about 150° apart, symbolizing themes that can be difficult to reconcile.", + "keywords": ["adjustment", "adaptation"] + }, + "Opposition": { + "name": "Opposition", + "insight": "An opposition places two chart factors about 180° apart, symbolizing contrasting needs held in relationship.", + "keywords": ["contrast", "balance"] + } +} diff --git a/src/lib/copy/content/en/reference/body.json b/src/lib/copy/content/en/reference/body.json new file mode 100644 index 0000000..84a1561 --- /dev/null +++ b/src/lib/copy/content/en/reference/body.json @@ -0,0 +1,77 @@ +{ + "SUN": { + "name": "Sun", + "insight": "The Sun symbolizes identity, purpose and the wish to express yourself.", + "keywords": ["identity", "purpose"] + }, + "MOON": { + "name": "Moon", + "insight": "The Moon symbolizes emotional needs, familiar habits and what feels comforting.", + "keywords": ["emotions", "comfort"] + }, + "MERCURY": { + "name": "Mercury", + "insight": "Mercury symbolizes learning, reasoning and the exchange of ideas.", + "keywords": ["thought", "communication"] + }, + "VENUS": { + "name": "Venus", + "insight": "Venus symbolizes affection, attraction and what you value or enjoy.", + "keywords": ["connection", "values"] + }, + "MARS": { + "name": "Mars", + "insight": "Mars symbolizes initiative, desire and the way you assert yourself.", + "keywords": ["action", "drive"] + }, + "JUPITER": { + "name": "Jupiter", + "insight": "Jupiter symbolizes growth through exploration, belief and a search for meaning.", + "keywords": ["growth", "meaning"] + }, + "SATURN": { + "name": "Saturn", + "insight": "Saturn symbolizes boundaries, responsibility and what takes time to build.", + "keywords": ["discipline", "structure"] + }, + "URANUS": { + "name": "Uranus", + "insight": "Uranus symbolizes independence, experimentation and breaks with familiar patterns.", + "keywords": ["change", "freedom"] + }, + "NEPTUNE": { + "name": "Neptune", + "insight": "Neptune symbolizes imagination, longing and the blurred line between ideals and illusion.", + "keywords": ["imagination", "ideals"] + }, + "PLUTO": { + "name": "Pluto", + "insight": "Pluto symbolizes power, control and profound processes of change.", + "keywords": ["power", "transformation"] + }, + "CHIRON": { + "name": "Chiron", + "insight": "Chiron symbolizes vulnerability and the understanding that can grow from difficult experiences.", + "keywords": ["vulnerability", "understanding"] + }, + "CERES": { + "name": "Ceres", + "insight": "Ceres symbolizes nurturing, nourishment and the experience of giving or receiving care.", + "keywords": ["care", "nourishment"] + }, + "NORTH_NODE": { + "name": "North Node", + "insight": "The North Node marks the point where the Moon crosses the Sun’s apparent path northward, interpreted here as a symbol of development.", + "keywords": ["lunar node", "development"] + }, + "SOUTH_NODE": { + "name": "South Node", + "insight": "The South Node marks the point where the Moon crosses the Sun’s apparent path southward, interpreted here as a symbol of familiar patterns.", + "keywords": ["lunar node", "familiarity"] + }, + "EARTH": { + "name": "Earth", + "insight": "Earth is shown here as a symbolic point opposite the Sun, rather than a planet observed from Earth.", + "keywords": ["Earth point", "opposite Sun"] + } +} diff --git a/src/lib/copy/content/en/reference/house.json b/src/lib/copy/content/en/reference/house.json new file mode 100644 index 0000000..580cc88 --- /dev/null +++ b/src/lib/copy/content/en/reference/house.json @@ -0,0 +1,50 @@ +{ + "1": { + "insight": "The first house represents self-presentation, physical presence and how you enter new situations.", + "keywords": ["presence", "self-presentation"] + }, + "2": { + "insight": "The second house represents personal resources, possessions and what you rely on for security.", + "keywords": ["resources", "security"] + }, + "3": { + "insight": "The third house represents everyday learning, communication, siblings and nearby surroundings.", + "keywords": ["learning", "communication"] + }, + "4": { + "insight": "The fourth house represents home, family roots and the foundations of private life.", + "keywords": ["home", "roots"] + }, + "5": { + "insight": "The fifth house represents creativity, play, romance and relationships with children.", + "keywords": ["creativity", "play"] + }, + "6": { + "insight": "The sixth house represents daily work, practical responsibilities and routines of care.", + "keywords": ["routine", "care"] + }, + "7": { + "insight": "The seventh house represents one-to-one commitments, including partnerships and agreements.", + "keywords": ["partnership", "relationship"] + }, + "8": { + "insight": "The eighth house represents shared resources, obligations and experiences of loss or change.", + "keywords": ["shared resources", "change"] + }, + "9": { + "insight": "The ninth house represents higher learning, travel and the beliefs that shape a wider worldview.", + "keywords": ["exploration", "belief"] + }, + "10": { + "insight": "The tenth house represents vocation, reputation and responsibilities in public life.", + "keywords": ["vocation", "reputation"] + }, + "11": { + "insight": "The eleventh house represents friendships, groups and hopes pursued with others.", + "keywords": ["community", "aspiration"] + }, + "12": { + "insight": "The twelfth house represents solitude, retreat and parts of life kept out of public view.", + "keywords": ["solitude", "retreat"] + } +} diff --git a/src/lib/copy/content/en/reference/sign.json b/src/lib/copy/content/en/reference/sign.json new file mode 100644 index 0000000..7939198 --- /dev/null +++ b/src/lib/copy/content/en/reference/sign.json @@ -0,0 +1,67 @@ +{ + "aries": { + "name": "Aries", + "insight": "Aries symbolizes the impulse to begin, take a risk and act directly.", + "keywords": ["initiative", "courage"] + }, + "taurus": { + "name": "Taurus", + "insight": "Taurus symbolizes steadiness, physical comfort and the patient cultivation of what matters.", + "keywords": ["steadiness", "comfort"] + }, + "gemini": { + "name": "Gemini", + "insight": "Gemini symbolizes curiosity, conversation and the exploration of different perspectives.", + "keywords": ["curiosity", "communication"] + }, + "cancer": { + "name": "Cancer", + "insight": "Cancer symbolizes emotional attachment, protection and the need for belonging.", + "keywords": ["care", "belonging"] + }, + "leo": { + "name": "Leo", + "insight": "Leo symbolizes creative expression, generosity and the wish to be seen.", + "keywords": ["creativity", "expression"] + }, + "virgo": { + "name": "Virgo", + "insight": "Virgo symbolizes careful observation, practical service and the refinement of skills.", + "keywords": ["discernment", "service"] + }, + "libra": { + "name": "Libra", + "insight": "Libra symbolizes cooperation, fairness and the weighing of different needs.", + "keywords": ["balance", "relationship"] + }, + "scorpio": { + "name": "Scorpio", + "insight": "Scorpio symbolizes emotional depth, questions of trust and the process of letting go.", + "keywords": ["depth", "transformation"] + }, + "ophiuchus": { + "name": "Ophiuchus", + "insight": "Ophiuchus is a constellation crossed by the Sun’s apparent path and included in this app’s True Sky preset.", + "keywords": ["constellation", "Sun’s path"] + }, + "sagittarius": { + "name": "Sagittarius", + "insight": "Sagittarius symbolizes exploration, the search for meaning and the testing of beliefs.", + "keywords": ["exploration", "meaning"] + }, + "capricorn": { + "name": "Capricorn", + "insight": "Capricorn symbolizes responsibility, patient ambition and work toward lasting goals.", + "keywords": ["commitment", "structure"] + }, + "aquarius": { + "name": "Aquarius", + "insight": "Aquarius symbolizes independent thought, collective ideals and alternatives to established ways.", + "keywords": ["innovation", "community"] + }, + "pisces": { + "name": "Pisces", + "insight": "Pisces symbolizes imagination, compassion and openness to experiences beyond clear boundaries.", + "keywords": ["imagination", "empathy"] + } +} diff --git a/src/lib/copy/content/en/ui/app.json b/src/lib/copy/content/en/ui/app.json new file mode 100644 index 0000000..8c7a628 --- /dev/null +++ b/src/lib/copy/content/en/ui/app.json @@ -0,0 +1,18 @@ +{ + "app.birth.dateTime": "{date} at {time}", + "app.birth.empty": "Enter birth details", + "app.empty.caption": "Add a date, time and place of birth", + "app.empty.label": "Empty chart awaiting birth details", + "app.empty.title": "Your sky begins here", + "app.entry.edit": "Edit birth details", + "app.entry.headingEmpty": "Start with your birth details", + "app.entry.headingWithBirth": "Your birth chart", + "app.error.retry": "Retry calculation", + "app.error.retryLink": "Retry", + "app.meta.title": "Your chart | Astrology Engine", + "app.rail.hint": "Select a planet, sign, house or angle on the wheel to read about it here.", + "app.status.calculating": "Calculating your chart…", + "app.status.housesAdjusted": "House system adjusted to {houseSystem}.", + "app.status.notApplied": "Showing {shown} chart; requested settings have not been applied.", + "app.status.updating": "Showing {shown} chart while updating to {requested}." +} diff --git a/src/lib/copy/content/en/ui/birth.json b/src/lib/copy/content/en/ui/birth.json new file mode 100644 index 0000000..55d5076 --- /dev/null +++ b/src/lib/copy/content/en/ui/birth.json @@ -0,0 +1,17 @@ +{ + "birth.action.done": "Done", + "birth.action.retry": "Retry", + "birth.chip.dateNeeded": "Date needed", + "birth.chip.placeFound": "Place found", + "birth.chip.placeNeeded": "Birthplace needed", + "birth.chip.timeNeeded": "Birth time needed", + "birth.chip.timeProvided": "Time provided", + "birth.choice.date": "Choose a date", + "birth.choice.offset": "Choose the recorded offset", + "birth.choice.place": "Choose a birthplace", + "birth.choice.placeOption": "{city}, {region}, {country}", + "birth.input.label": "Birth details", + "birth.input.placeholder": "June 21, 2000 at 1pm in London", + "birth.modal.intro": "A date, time and birthplace locate your chart in the sky.", + "birth.status.resolving": "Resolving birth details…" +} diff --git a/src/lib/copy/content/en/ui/brand.json b/src/lib/copy/content/en/ui/brand.json new file mode 100644 index 0000000..54c94f1 --- /dev/null +++ b/src/lib/copy/content/en/ui/brand.json @@ -0,0 +1,4 @@ +{ + "brand.beta": "BETA", + "brand.name": "Astrology Engine" +} diff --git a/src/lib/copy/content/en/ui/chart.json b/src/lib/copy/content/en/ui/chart.json new file mode 100644 index 0000000..f84e577 --- /dev/null +++ b/src/lib/copy/content/en/ui/chart.json @@ -0,0 +1,6 @@ +{ + "chart.house.name": "House {number}", + "chart.reference.faganBradley": "Vedic", + "chart.reference.tropical": "Tropical", + "chart.reference.trueSky": "True Sky" +} diff --git a/src/lib/copy/content/en/ui/details.json b/src/lib/copy/content/en/ui/details.json new file mode 100644 index 0000000..54dba78 --- /dev/null +++ b/src/lib/copy/content/en/ui/details.json @@ -0,0 +1,28 @@ +{ + "details.aspect.title": "{first} {aspect} {second}", + "details.body.degree": "Degree", + "details.body.house": "House", + "details.body.no": "No", + "details.body.retrograde": "Retrograde", + "details.body.sign": "Sign", + "details.body.yes": "Yes", + "details.bridging": "This placement is in the final degree of its sign, offered here as a symbolic prompt to reflect on transition within that sign.", + "details.context": "{reference} · {houseSystem} houses", + "details.contextRequested": "{reference} · {houseSystem} houses (requested {requested})", + "details.house.cuspSign": "Sign at cusp", + "details.house.empty": "No bodies in this house", + "details.house.modernRuler": "Modern ruler", + "details.house.noRuler": "No established ruler", + "details.house.occupants": "Occupants", + "details.house.ruler": "Ruler", + "details.house.traditionalRuler": "Traditional ruler", + "details.house.unavailable": "Unavailable", + "details.label.angle": "Angle details", + "details.label.aspect": "Aspect details", + "details.label.body": "Body details", + "details.label.house": "House details", + "details.label.sign": "Sign details", + "details.shell.close": "Close details", + "details.shell.resize": "Resize details", + "details.unavailable": "Details are unavailable right now." +} diff --git a/src/lib/copy/content/en/ui/error.json b/src/lib/copy/content/en/ui/error.json new file mode 100644 index 0000000..94c8b54 --- /dev/null +++ b/src/lib/copy/content/en/ui/error.json @@ -0,0 +1,26 @@ +{ + "error.chart.dataIntegrity": "Whoops, chart data couldn’t be verified.", + "error.chart.dataUnavailable": "Whoops, chart data couldn’t be downloaded.", + "error.chart.failed": "Whoops, chart calculation failed.", + "error.chart.invalidInput": "Whoops, these birth details couldn’t be used.", + "error.chart.noVerifiedData": "Whoops, there’s no verified data for this birth date.", + "error.chart.notStarted": "Whoops, chart calculation couldn’t start.", + "error.chart.outOfRange": "Whoops, this birth date is outside the supported range.", + "error.chart.timeout": "Whoops, chart calculation took too long.", + "error.resolver.chooseDate": "Choose a valid date interpretation.", + "error.resolver.choosePlace": "Choose your birthplace.", + "error.resolver.dateIncomplete": "Enter a complete birth date, including the year.", + "error.resolver.emptyInput": "Enter your birth details.", + "error.resolver.explicitTimezone": "An explicit timezone or offset was supplied. Please provide the local birth date and time at the birthplace without a timezone, or clarify the intended local time.", + "error.resolver.inputTooLong": "Birth details are too long.", + "error.resolver.invalidBirth": "The birth details could not be validated. Check the date, time and birthplace.", + "error.resolver.invalidInput": "Please check your birth details.", + "error.resolver.outOfCoverage": "Birth time is outside sky data coverage.", + "error.resolver.placeNotFound": "No place found. Add a city and state or country.", + "error.resolver.range": "The birth details contain a range. Supply one exact date and time.", + "error.resolver.temporaryFailure": "Unable to resolve birth details. Please try again.", + "error.resolver.timeAmbiguous": "That local time occurred twice. Choose the recorded UTC offset.", + "error.resolver.timeInFuture": "Birth time must be in the past.", + "error.resolver.timeMissing": "Add your birth time to calculate a chart.", + "error.resolver.timeSkipped": "That local time was skipped when the clocks changed. Correct the birth time." +} diff --git a/src/lib/copy/content/en/ui/explorer.json b/src/lib/copy/content/en/ui/explorer.json new file mode 100644 index 0000000..bd228ff --- /dev/null +++ b/src/lib/copy/content/en/ui/explorer.json @@ -0,0 +1,17 @@ +{ + "explorer.announce.cleared": "Selection cleared", + "explorer.announce.opened": "Selection opened", + "explorer.announce.pickerReset": "Connections updated; open the picker again.", + "explorer.announce.unavailable": "Selection no longer available", + "explorer.aspects.explore": "Explore aspects", + "explorer.aspects.exploreOf": "Explore aspects of {body}", + "explorer.list.angles": "Choose an angle by name", + "explorer.list.bodies": "Choose a body by name", + "explorer.list.houses": "Choose a house by number", + "explorer.list.signs": "Choose a sign by name", + "explorer.picker.back": "Back", + "explorer.picker.close": "Close", + "explorer.picker.first": "Choose the first body", + "explorer.picker.label": "Choose an aspect", + "explorer.picker.second": "Choose a connection to {body}" +} diff --git a/src/lib/copy/content/en/ui/landing.json b/src/lib/copy/content/en/ui/landing.json new file mode 100644 index 0000000..8cf2d34 --- /dev/null +++ b/src/lib/copy/content/en/ui/landing.json @@ -0,0 +1,15 @@ +{ + "landing.footer.brand": "ASTROLOGY ENGINE", + "landing.footer.tagline": "MADE FOR THE CURIOUS", + "landing.hero.cta": "Start exploring", + "landing.hero.description": "There’s more to your chart than your Sun sign. Discover the planets, signs and houses that make up your unique sky, one piece at a time.", + "landing.hero.eyebrow": "A LITTLE CURIOSITY GOES A LONG WAY", + "landing.hero.note": "Your chart begins with your birth details.", + "landing.hero.title": "Explore your\nbirth chart.", + "landing.meta.description": "Explore the elements of your birth chart, one discovery at a time.", + "landing.meta.title": "Natal Chart Explorer | Astrology Engine", + "landing.sample.alt": "Sample chart showing Aries, Taurus and Gemini, planets, and houses 1 through 3", + "landing.sample.caption": "A small glimpse of the bigger picture. This sample isn’t your personal chart.", + "landing.sample.index": "01 / THE WHEEL", + "landing.sample.label": "SAMPLE CHART" +} diff --git a/src/lib/copy/content/en/ui/language.json b/src/lib/copy/content/en/ui/language.json new file mode 100644 index 0000000..f1eef81 --- /dev/null +++ b/src/lib/copy/content/en/ui/language.json @@ -0,0 +1,3 @@ +{ + "language.switcher": "Language" +} diff --git a/src/lib/copy/content/en/ui/settings.json b/src/lib/copy/content/en/ui/settings.json new file mode 100644 index 0000000..bc34d19 --- /dev/null +++ b/src/lib/copy/content/en/ui/settings.json @@ -0,0 +1,23 @@ +{ + "settings.advanced.houses": "Advanced settings: {houses} houses", + "settings.help.divisionsConstellation": "constellation", + "settings.help.divisionsEqual": "equal", + "settings.help.faganBradley": "The preset labeled Vedic uses twelve equal signs with the Fagan–Bradley sidereal reference, a Western sidereal convention distinct from those commonly used in Vedic astrology.", + "settings.help.label": "System help", + "settings.help.summary": "Signs: {divisions}. Actual houses: {houses}.", + "settings.help.summaryOphiuchusIncluded": "Signs: {divisions} · Ophiuchus included. Actual houses: {houses}.", + "settings.help.toggle": "About this system", + "settings.help.tropical": "Tropical astrology divides the zodiac into twelve equal signs, beginning at the March equinox point.", + "settings.help.trueSkyConstellations": "True Sky uses unequal, constellation-based divisions following the Chimenti convention, including Ophiuchus as a thirteenth sign.", + "settings.houses.equal": "Equal", + "settings.houses.equalHint": "Twelve 30° houses measured from the Ascendant.", + "settings.houses.label": "House system", + "settings.houses.placidus": "Placidus", + "settings.houses.placidusHint": "Houses sized by the time it takes each part of the sky to rise.", + "settings.houses.wholeSign": "Whole Sign", + "settings.houses.wholeSignHint": "Each house is one whole sign.", + "settings.preset.tropical": "Tropical", + "settings.preset.trueSky": "True Sky", + "settings.preset.vedic": "Vedic", + "settings.presets.label": "Zodiac presets" +} diff --git a/src/lib/copy/content/en/ui/wheel.json b/src/lib/copy/content/en/ui/wheel.json new file mode 100644 index 0000000..5c1d365 --- /dev/null +++ b/src/lib/copy/content/en/ui/wheel.json @@ -0,0 +1,18 @@ +{ + "wheel.angle.asc": "ASC", + "wheel.angle.dsc": "DSC", + "wheel.angle.ic": "IC", + "wheel.angle.mc": "MC", + "wheel.group.label": "Grouped bodies: {bodies}", + "wheel.group.labelSelected": "Grouped bodies: {bodies}. Selected {body}", + "wheel.groupPicker.close": "Close body picker", + "wheel.groupPicker.title": "Choose a body", + "wheel.label": "Interactive natal chart", + "wheel.mobile.dragHint": "Drag sideways to pan", + "wheel.mobile.panLeft": "Pan wheel left", + "wheel.mobile.panRight": "Pan wheel right", + "wheel.mobile.viewport": "Chart viewport", + "wheel.mobile.zoomIn": "Zoom half wheel", + "wheel.mobile.zoomOut": "Show whole wheel", + "wheel.sign.region": "{sign} sign region" +} diff --git a/src/lib/copy/content/english.ts b/src/lib/copy/content/english.ts new file mode 100644 index 0000000..53149c5 --- /dev/null +++ b/src/lib/copy/content/english.ts @@ -0,0 +1,37 @@ +import app from "./en/ui/app.json"; +import birth from "./en/ui/birth.json"; +import brand from "./en/ui/brand.json"; +import chart from "./en/ui/chart.json"; +import details from "./en/ui/details.json"; +import error from "./en/ui/error.json"; +import explorer from "./en/ui/explorer.json"; +import landing from "./en/ui/landing.json"; +import language from "./en/ui/language.json"; +import settings from "./en/ui/settings.json"; +import wheel from "./en/ui/wheel.json"; +import body from "./en/reference/body.json"; +import angle from "./en/reference/angle.json"; +import sign from "./en/reference/sign.json"; +import aspect from "./en/reference/aspect.json"; +import house from "./en/reference/house.json"; + +export const english = { + ui: { + ...app, + ...birth, + ...brand, + ...chart, + ...details, + ...error, + ...explorer, + ...landing, + ...language, + ...settings, + ...wheel, + }, + body, + angle, + sign, + aspect, + house, +}; diff --git a/src/lib/copy/content/placeholders.ts b/src/lib/copy/content/placeholders.ts new file mode 100644 index 0000000..09c73ea --- /dev/null +++ b/src/lib/copy/content/placeholders.ts @@ -0,0 +1,23 @@ +import type { english } from "./english"; + +export type UiKey = keyof typeof english.ui; + +export const placeholders = { + "app.birth.dateTime": ["date", "time"], + "app.status.housesAdjusted": ["houseSystem"], + "app.status.notApplied": ["shown"], + "app.status.updating": ["requested", "shown"], + "birth.choice.placeOption": ["city", "country", "region"], + "chart.house.name": ["number"], + "details.aspect.title": ["aspect", "first", "second"], + "details.context": ["houseSystem", "reference"], + "details.contextRequested": ["houseSystem", "reference", "requested"], + "explorer.aspects.exploreOf": ["body"], + "explorer.picker.second": ["body"], + "settings.advanced.houses": ["houses"], + "settings.help.summary": ["divisions", "houses"], + "settings.help.summaryOphiuchusIncluded": ["divisions", "houses"], + "wheel.group.label": ["bodies"], + "wheel.group.labelSelected": ["bodies", "body"], + "wheel.sign.region": ["sign"], +} as const satisfies Partial>; diff --git a/src/lib/copy/copy.ts b/src/lib/copy/copy.ts index 55939fc..1e5f89d 100644 --- a/src/lib/copy/copy.ts +++ b/src/lib/copy/copy.ts @@ -1,25 +1,31 @@ -/** - * Typed access to CMS copy (docs/designs/cms.md §9.3). Keys and placeholder - * names come from the CMS catalog, so unknown keys fail type checks. - */ -import type { AppCatalog } from "@astrologyengine/cms-contract/catalog"; +import type { placeholders, UiKey } from "./content/placeholders"; -type UiKeys = AppCatalog["ui"]["keys"]; -export type UiKey = keyof UiKeys & string; +export type { UiKey } from "./content/placeholders"; + +type UiKeys = { + [K in UiKey]: K extends keyof typeof placeholders + ? (typeof placeholders)[K] + : readonly []; +}; type ParamsOf = UiKeys[K] extends readonly [] ? [] : [params: Record]; -/** Keys whose text takes no placeholders. */ export type PlainKey = { [K in UiKey]: UiKeys[K] extends readonly [] ? K : never; }[UiKey]; export type Reference = { insight: string; keywords: string[] }; export type NamedReference = Reference & { name: string }; - -import type { Bundle } from "@astrologyengine/cms-contract/types"; -export type { Bundle } from "@astrologyengine/cms-contract/types"; +export type ContentEntries = { + ui?: Partial>; + body?: Record; + angle?: Record; + sign?: Record; + aspect?: Record; + house?: Record; +}; +export type Bundle = { locale: string; entries: ContentEntries }; type Options = { warn?: (message: string) => void }; @@ -33,26 +39,28 @@ export const createCopy = ( const missing = (id: string) => { if (warned.has(id)) return; warned.add(id); - warn(`Missing CMS copy: ${id} (${bundle.locale})`); + warn(`Missing copy: ${id} (${bundle.locale})`); }; - const lookup = (collection: string, key: string) => - bundle.entries[collection]?.[key] as T | undefined; + const lookup = (collection: keyof ContentEntries, key: string) => + (bundle.entries[collection] as Record | undefined)?.[ + key + ] as T | undefined; const t = (key: K, ...[params]: ParamsOf): string => { - const entry = lookup<{ text: string }>("ui", key); + const entry = lookup("ui", key); if (!entry) { missing(`ui:${key}`); return key; } - if (!params) return entry.text; + if (!params) return entry; const values = params as Record; - return entry.text.replace(PLACEHOLDER, (match, name: string) => + return entry.replace(PLACEHOLDER, (match, name: string) => Object.hasOwn(values, name) ? String(values[name]) : match, ); }; const named = - (collection: string) => + (collection: keyof ContentEntries) => (key: string): NamedReference | undefined => lookup(collection, key); const body = named("body"); diff --git a/src/lib/labels.ts b/src/lib/labels.ts index 8d2bfd4..3b5705e 100644 --- a/src/lib/labels.ts +++ b/src/lib/labels.ts @@ -1,4 +1,4 @@ -/** CMS keys for settings identifiers that the UI displays. */ +/** Copy keys for settings identifiers that the UI displays. */ import type { PlainKey } from "./copy/copy"; import type { Preset, Settings } from "./settings"; diff --git a/src/lib/messages.ts b/src/lib/messages.ts index 4b96287..17a53e6 100644 --- a/src/lib/messages.ts +++ b/src/lib/messages.ts @@ -1,6 +1,6 @@ /** - * Server and worker outcomes are stable codes; the client words them with CMS - * copy (docs/designs/cms.md §9.3). + * Server and worker outcomes are stable codes; the client words them with site + * copy. */ import type { PlainKey } from "./copy/copy"; diff --git a/src/lib/rulers.ts b/src/lib/rulers.ts index 7e23c34..c53271b 100644 --- a/src/lib/rulers.ts +++ b/src/lib/rulers.ts @@ -5,7 +5,7 @@ type BodyId = (typeof bodyIds)[number]; /** * Traditional and modern ruler of each sign, as body IDs; their names come - * from the CMS. Ophiuchus is a modern sign: Pluto rules it, with no + * from the web content files. Ophiuchus is a modern sign: Pluto rules it, with no * traditional ruler. */ export const rulers: Record< diff --git a/src/lib/server/cms/index.ts b/src/lib/server/cms/index.ts deleted file mode 100644 index ac8170f..0000000 --- a/src/lib/server/cms/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { dev } from "$app/environment"; -import { env } from "$env/dynamic/private"; -import { createContentSource, type ContentSource } from "./source"; - -let source: ContentSource | undefined; - -/** - * One content source per isolate, so its cache outlives requests. Production - * reads the CMS through the `CMS` service binding and the snapshot through - * `ASSETS`; `vite dev` uses CMS_ORIGIN over HTTP (like the ASSETS dev path). - */ -export const contentSource = ({ - platform, - origin, -}: { - platform: App.Platform | undefined; - origin: string; -}) => { - source ??= createContentSource({ - fetchCms: (path, init) => - dev || !platform - ? fetch(`${env.CMS_ORIGIN || "http://127.0.0.1:8787"}${path}`, init) - : platform.env.CMS.fetch(`https://cms.internal${path}`, init), - readSnapshot: async (file) => { - const path = `/content/${file}`; - const response = - dev || !platform - ? await fetch(`${origin}${path}`) - : await platform.env.ASSETS.fetch(new URL(path, origin)); - return response.ok ? response.json() : null; - }, - }); - return source; -}; diff --git a/src/lib/server/cms/locale.ts b/src/lib/server/cms/locale.ts deleted file mode 100644 index e41d187..0000000 --- a/src/lib/server/cms/locale.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { - negotiate, - parseAcceptLanguage, -} from "@astrologyengine/cms-contract/locales"; - -const NO_MATCH = ""; - -/** The enabled locale matching `tag` (exact, base, sibling), or null. */ -const match = (tag: string | null | undefined, enabled: string[]) => { - if (!tag) return null; - const found = negotiate([tag], enabled, NO_MATCH); - return found === NO_MATCH ? null : found; -}; - -/** - * Locale for a request (docs/designs/cms.md §9.2): `?lang` (persisted in a - * cookie) → cookie → Accept-Language → default. - */ -export const chooseLocale = ({ - query, - cookie, - acceptLanguage, - enabled, - defaultCode, -}: { - query: string | null; - cookie?: string; - acceptLanguage: string | null; - enabled: string[]; - defaultCode: string; -}) => { - const fromQuery = match(query, enabled); - if (fromQuery) return { locale: fromQuery, persist: true }; - const fromCookie = match(cookie, enabled); - if (fromCookie) return { locale: fromCookie, persist: false }; - return { - locale: negotiate( - parseAcceptLanguage(acceptLanguage ?? ""), - enabled, - defaultCode, - ), - persist: false, - }; -}; diff --git a/src/lib/server/cms/source.ts b/src/lib/server/cms/source.ts deleted file mode 100644 index 952e5f5..0000000 --- a/src/lib/server/cms/source.ts +++ /dev/null @@ -1,125 +0,0 @@ -import type { Bundle } from "../../copy/copy"; - -import type { LocalesIndex } from "@astrologyengine/cms-contract/types"; -export type { - LocaleSummary, - LocalesIndex, -} from "@astrologyengine/cms-contract/types"; - -type Entry = { value: T; etag: string | null; checkedAt: number }; - -const notFound = (path: string) => - Object.assign(new Error(path), { name: "CmsNotFound" }); -const isNotFound = (error: unknown) => - error instanceof Error && error.name === "CmsNotFound"; - -/** - * Copy source for the website (docs/designs/cms.md §9.4–9.5). Per key, in - * order: fresh isolate cache → live CMS (revalidated with If-None-Match) → - * stale cache → bundled snapshot. After a failure the fallback is reused for - * `freshMs` before the CMS is tried again, so an outage does not make every - * request wait for the timeout. - */ -export const createContentSource = ({ - fetchCms, - readSnapshot, - now = Date.now, - log = (event) => console.warn(event), - freshMs = 60_000, - timeoutMs = 2_000, -}: { - fetchCms: (path: string, init?: RequestInit) => Promise; - readSnapshot: (file: string) => Promise; - now?: () => number; - log?: (event: Record) => void; - freshMs?: number; - timeoutMs?: number; -}) => { - const cache = new Map>(); - - const live = async (path: string, cached?: Entry) => { - const response = await fetchCms(path, { - headers: cached?.etag ? { "if-none-match": cached.etag } : {}, - signal: AbortSignal.timeout(timeoutMs), - }); - if (response.status === 304 && cached) { - cached.checkedAt = now(); - return cached.value; - } - if (response.status === 404) throw notFound(path); - if (!response.ok) throw new Error(`CMS answered ${response.status}`); - const value = (await response.json()) as T; - cache.set(path, { - value, - etag: response.headers.get("etag"), - checkedAt: now(), - }); - return value; - }; - - const load = async ( - path: string, - locale: string | null, - snapshot: () => Promise, - ): Promise => { - const cached = cache.get(path) as Entry | undefined; - if (cached && now() - cached.checkedAt < freshMs) return cached.value; - try { - return await live(path, cached); - } catch (error) { - if (isNotFound(error)) throw error; - const reason = String(error); - if (cached) { - cached.checkedAt = now(); - log({ event: "cms_fallback", source: "stale", locale, reason }); - return cached.value; - } - const value = await snapshot(); - if (value === null) - throw new Error(`CMS copy unavailable for ${locale ?? "locales"}`, { - cause: error, - }); - cache.set(path, { value, etag: null, checkedAt: now() }); - log({ event: "cms_fallback", source: "snapshot", locale, reason }); - return value; - } - }; - - const snapshotIndex = () => - readSnapshot("index.json") as Promise< - (LocalesIndex & { version: number }) | null - >; - - const locales = () => load("/v1/locales", null, snapshotIndex); - - const snapshotBundle = async (locale: string) => { - const index = await snapshotIndex(); - const chain = index?.locales.find((entry) => entry.code === locale) - ?.chain ?? [locale]; - for (const code of [...chain, index?.default ?? "en"]) { - const found = (await readSnapshot(`${code}.json`)) as Bundle | null; - if (found) return found; - } - return null; - }; - - const bundle = async (locale: string): Promise => { - try { - return await load(`/v1/content/${locale}`, locale, () => - snapshotBundle(locale), - ); - } catch (error) { - if (!isNotFound(error)) throw error; - // The locale was disabled or removed since the locale list was cached. - const known = cache.get("/v1/locales")?.value as LocalesIndex | undefined; - const fallback = - known?.default ?? (await snapshotIndex())?.default ?? "en"; - if (fallback === locale) throw error; - return bundle(fallback); - } - }; - - return { locales, bundle }; -}; - -export type ContentSource = ReturnType; diff --git a/src/lib/server/content/index.ts b/src/lib/server/content/index.ts new file mode 100644 index 0000000..790e74b --- /dev/null +++ b/src/lib/server/content/index.ts @@ -0,0 +1,33 @@ +import { dev } from "$app/environment"; +import type { Bundle, ContentEntries } from "../../copy/copy"; +import { english } from "../../copy/content/english"; + +const defaultCode = "en"; +const pseudo = + dev && import.meta.env.MODE === "e2e-i18n" + ? (await import("../../../../tests/fixtures/pseudo-locale.json")).default + : null; + +export const locales = [ + { code: defaultCode, name: "English" }, + ...(pseudo ? [{ code: pseudo.code, name: pseudo.name }] : []), +]; +export { defaultCode }; + +export const resolveEntries = ( + base: ContentEntries, + translated: ContentEntries, +): ContentEntries => ({ + ui: { ...base.ui, ...translated.ui }, + body: { ...base.body, ...translated.body }, + angle: { ...base.angle, ...translated.angle }, + sign: { ...base.sign, ...translated.sign }, + aspect: { ...base.aspect, ...translated.aspect }, + house: { ...base.house, ...translated.house }, +}); + +const pseudoEntries = pseudo ? resolveEntries(english, pseudo.entries) : null; +export const bundle = (locale: string): Bundle => + pseudo && pseudoEntries && locale === pseudo.code + ? { locale, entries: pseudoEntries } + : { locale: defaultCode, entries: english }; diff --git a/src/lib/server/content/locale.ts b/src/lib/server/content/locale.ts new file mode 100644 index 0000000..7286753 --- /dev/null +++ b/src/lib/server/content/locale.ts @@ -0,0 +1,96 @@ +const MAX_TAG_LENGTH = 35; + +/** Canonical BCP 47 tag (e.g. `es-mx` → `es-MX`), or null if invalid. */ +export const canonicalLocale = (tag: string): string | null => { + if (!tag || tag.length > MAX_TAG_LENGTH || !/^[A-Za-z0-9-]+$/.test(tag)) + return null; + try { + const [canonical] = Intl.getCanonicalLocales(tag); + if (!canonical) return null; + // ISO 639 two- or three-letter languages only (BCP 47 also allows 5–8). + return /^[a-z]{2,3}$/.test(new Intl.Locale(canonical).language) + ? canonical + : null; + } catch { + return null; + } +}; + +export const languageOf = (code: string) => new Intl.Locale(code).language; + +/** Language tags from an Accept-Language header, best first. */ +export const parseAcceptLanguage = (header: string) => + header + .split(",") + .map((part, position) => { + const [tag = "", ...params] = part.trim().split(";"); + const q = params + .map((param) => param.trim().match(/^q=([01](?:\.\d{0,3})?)$/)) + .find(Boolean); + return { tag: tag.trim(), q: q ? Number(q[1]) : 1, position }; + }) + .filter(({ tag, q }) => tag && tag !== "*" && q > 0 && canonicalLocale(tag)) + .sort((a, b) => b.q - a.q || a.position - b.position) + .map(({ tag }) => tag); + +/** + * First enabled locale matching a requested tag: exact, then base language, + * then a sibling sharing the language (alphabetical). Falls back to default. + */ +export const negotiate = ( + requested: string[], + enabled: string[], + fallbackDefault: string, +) => { + const available = [...enabled].sort(); + for (const tag of requested) { + const canonical = canonicalLocale(tag); + if (!canonical) continue; + if (available.includes(canonical)) return canonical; + const language = languageOf(canonical); + if (available.includes(language)) return language; + const sibling = available.find((code) => languageOf(code) === language); + if (sibling) return sibling; + } + return fallbackDefault; +}; + +const NO_MATCH = ""; + +/** The enabled locale matching `tag` (exact, base, sibling), or null. */ +const match = (tag: string | null | undefined, enabled: string[]) => { + if (!tag) return null; + const found = negotiate([tag], enabled, NO_MATCH); + return found === NO_MATCH ? null : found; +}; + +/** + * Locale for a request: `?lang` (persisted in a + * cookie) → cookie → Accept-Language → default. + */ +export const chooseLocale = ({ + query, + cookie, + acceptLanguage, + enabled, + defaultCode, +}: { + query: string | null; + cookie?: string; + acceptLanguage: string | null; + enabled: string[]; + defaultCode: string; +}) => { + const fromQuery = match(query, enabled); + if (fromQuery) return { locale: fromQuery, persist: true }; + const fromCookie = match(cookie, enabled); + if (fromCookie) return { locale: fromCookie, persist: false }; + return { + locale: negotiate( + parseAcceptLanguage(acceptLanguage ?? ""), + enabled, + defaultCode, + ), + persist: false, + }; +}; diff --git a/src/lib/wheel/body-symbols.ts b/src/lib/wheel/body-symbols.ts index 5050cfb..8309be1 100644 --- a/src/lib/wheel/body-symbols.ts +++ b/src/lib/wheel/body-symbols.ts @@ -22,7 +22,7 @@ const planetSymbols = Object.fromEntries( ) as Record<(typeof planetIds)[number], { path: string }>; // SVG glyphs ported from astrology-engine-website at 9613598; Earth and Ceres retained for this app. -/** Glyphs only; display names come from the CMS `body` and `angle` entries. */ +/** Glyphs only; display names come from the web content files `body` and `angle` entries. */ export const bodySymbols: Record = { ...planetSymbols, EARTH: { diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 07ed01e..2ad7b31 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,17 +1,8 @@ -import { contentSource } from "$lib/server/cms"; +import { bundle, locales } from "$lib/server/content"; import type { LayoutServerLoad } from "./$types"; -export const load: LayoutServerLoad = async ({ locals, platform, url }) => { - // Re-run when ?lang changes (the hook negotiates from it). +export const load: LayoutServerLoad = ({ locals, url }) => { + // Re-run when the requested language changes. url.searchParams.get("lang"); - const source = contentSource({ platform, origin: url.origin }); - const [locales, content] = await Promise.all([ - source.locales(), - source.bundle(locals.locale), - ]); - return { - locale: locals.locale, - locales: locales.locales.map(({ code, name }) => ({ code, name })), - content, - }; + return { locale: locals.locale, locales, content: bundle(locals.locale) }; }; diff --git a/tests/cms-down.spec.ts b/tests/cms-down.spec.ts deleted file mode 100644 index 67a93f7..0000000 --- a/tests/cms-down.spec.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { enterBirth } from "./helpers"; - -// Runs against a web server whose CMS is unreachable: copy comes from the -// bundled snapshot and the site keeps working. -test("the landing page renders snapshot copy", async ({ page }) => { - await page.goto("/"); - await expect(page.locator("html")).toHaveAttribute("lang", "en"); - await expect( - page.getByRole("heading", { name: /explore your birth chart/i }), - ).toBeVisible(); - await expect( - page.getByText("A LITTLE CURIOSITY GOES A LONG WAY"), - ).toBeVisible(); -}); - -test("a visitor can still create and explore a chart", async ({ page }) => { - await page.goto("/app"); - await enterBirth(page); - const chart = page.getByRole("group", { name: /natal chart/i }); - await expect(chart).toBeVisible({ timeout: 30000 }); - await chart.getByRole("button", { name: "Sun" }).click(); - await expect( - page.getByText(/The Sun symbolizes identity, purpose/), - ).toBeVisible(); -}); diff --git a/tests/fixtures/cms-pseudo-locale.json b/tests/fixtures/cms-pseudo-locale.json deleted file mode 100644 index a4224c4..0000000 --- a/tests/fixtures/cms-pseudo-locale.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "locales": [{ "code": "en-XA", "name": "English (pseudo)", "enabled": true }], - "seeds": [ - { - "locale": "en-XA", - "entries": { - "ui": { - "brand.name": { "text": "[Àśţŕöĺöĝý Ëñĝîñë]" }, - "landing.hero.eyebrow": { - "text": "[À ĹÎŢŢĹË ÇÛŔÎÖŚÎŢÝ ĜÖËŚ À ĹÖÑĜ ŴÀÝ]" - }, - "language.switcher": { "text": "[Ĺàñĝûàĝë]" }, - "app.entry.headingEmpty": { - "text": "[Šţàŕţ ŵîţĥ ýöûŕ ƀîŕţĥ ðëţàîĺš]" - } - }, - "body": { - "SUN": { - "name": "[Šûñ]", - "insight": "[Ţĥë Šûñ šýɱƀöĺîžëš îðëñţîţý.]", - "keywords": ["[îðëñţîţý]", "[þûŕþöšë]"] - } - } - } - } - ] -} diff --git a/tests/fixtures/pseudo-locale.json b/tests/fixtures/pseudo-locale.json new file mode 100644 index 0000000..5cf6992 --- /dev/null +++ b/tests/fixtures/pseudo-locale.json @@ -0,0 +1,19 @@ +{ + "code": "en-XA", + "name": "English (pseudo)", + "entries": { + "ui": { + "brand.name": "[Àśţŕöĺöĝý Ëñĝîñë]", + "landing.hero.eyebrow": "[À ĹÎŢŢĹË ÇÛŔÎÖŚÎŢÝ ĜÖËŚ À ĹÖÑĜ ŴÀÝ]", + "language.switcher": "[Ĺàñĝûàĝë]", + "app.entry.headingEmpty": "[Šţàŕţ ŵîţĥ ýöûŕ ƀîŕţĥ ðëţàîĺš]" + }, + "body": { + "SUN": { + "name": "[Šûñ]", + "insight": "[Ţĥë Šûñ šýɱƀöĺîžëš îðëñţîţý.]", + "keywords": ["[îðëñţîţý]", "[þûŕþöšë]"] + } + } + } +} diff --git a/tests/i18n.spec.ts b/tests/i18n.spec.ts index 7175013..590567b 100644 --- a/tests/i18n.spec.ts +++ b/tests/i18n.spec.ts @@ -1,7 +1,7 @@ import { expect, test } from "@playwright/test"; import { enterBirth } from "./helpers"; -// Runs against a CMS seeded with tests/fixtures/cms-pseudo-locale.json. +// Runs with the partial pseudo-locale enabled by Playwright. const pseudoEyebrow = "[À ĹÎŢŢĹË ÇÛŔÎÖŚÎŢÝ ĜÖËŚ À ĹÖÑĜ ŴÀÝ]"; test.describe("with a browser preferring the pseudo-locale", () => { diff --git a/verification/content-source.test.ts b/verification/content-source.test.ts deleted file mode 100644 index a88e383..0000000 --- a/verification/content-source.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { beforeEach, describe, expect, test } from "bun:test"; -import { createContentSource } from "../src/lib/server/cms/source"; - -const bundle = (locale: string, version: number) => ({ - locale, - default: "en", - chain: locale === "en" ? ["en"] : [locale, "en"], - version, - entries: { ui: { "brand.name": { text: `${locale} v${version}` } } }, - fallbacks: {}, -}); -const index = { - default: "en", - version: 1, - locales: [ - { code: "en", name: "English", chain: ["en"] }, - { code: "es-ES", name: "Español", chain: ["es-ES", "es-419", "en"] }, - { code: "es-419", name: "Latam", chain: ["es-419", "en"] }, - ], -}; - -type Reply = Response | Error | "hang"; -let clock = 0; -let replies: Reply[] = []; -let requests: { path: string; etag: string | null }[] = []; -let logs: Record[] = []; -let snapshots: Record = {}; - -const json = (body: unknown, etag: string) => - new Response(JSON.stringify(body), { status: 200, headers: { etag } }); -const source = () => - createContentSource({ - fetchCms: (path, init) => { - requests.push({ - path, - etag: new Headers(init?.headers).get("if-none-match"), - }); - const reply = replies.shift() ?? new Error("no reply queued"); - if (reply === "hang") - return new Promise((_, reject) => - init?.signal?.addEventListener("abort", () => - reject(new Error("aborted")), - ), - ); - return reply instanceof Error - ? Promise.reject(reply) - : Promise.resolve(reply); - }, - readSnapshot: async (file) => snapshots[file] ?? null, - now: () => clock, - log: (event) => logs.push(event), - freshMs: 60_000, - timeoutMs: 20, - }); - -beforeEach(() => { - clock = 0; - replies = []; - requests = []; - logs = []; - snapshots = { "index.json": index, "en.json": bundle("en", 1) }; -}); - -describe("bundle", () => { - test("fetches live once, then serves the fresh cache", async () => { - const cms = source(); - replies = [json(bundle("en", 5), '"v5"')]; - expect((await cms.bundle("en")).version).toBe(5); - clock = 59_999; - expect((await cms.bundle("en")).version).toBe(5); - expect(requests).toEqual([{ path: "/v1/content/en", etag: null }]); - expect(logs).toEqual([]); - }); - - test("revalidates with If-None-Match after the fresh window", async () => { - const cms = source(); - replies = [ - json(bundle("en", 5), '"v5"'), - new Response(null, { status: 304 }), - ]; - await cms.bundle("en"); - clock = 60_000; - expect((await cms.bundle("en")).version).toBe(5); - expect(requests[1]).toEqual({ path: "/v1/content/en", etag: '"v5"' }); - clock = 100_000; - await cms.bundle("en"); - expect(requests).toHaveLength(2); - }); - - test("replaces the cache when the content changed", async () => { - const cms = source(); - replies = [json(bundle("en", 5), '"v5"'), json(bundle("en", 6), '"v6"')]; - await cms.bundle("en"); - clock = 60_000; - expect((await cms.bundle("en")).version).toBe(6); - }); - - test("serves the stale cache when the CMS fails, then backs off", async () => { - const cms = source(); - replies = [ - json(bundle("en", 5), '"v5"'), - new Response("down", { status: 500 }), - ]; - await cms.bundle("en"); - clock = 500_000; - expect((await cms.bundle("en")).version).toBe(5); - expect(logs).toEqual([ - expect.objectContaining({ - event: "cms_fallback", - source: "stale", - locale: "en", - }), - ]); - clock = 559_999; - await cms.bundle("en"); - expect(requests).toHaveLength(2); - }); - - test("serves the snapshot when the CMS is unreachable and nothing is cached", async () => { - const cms = source(); - replies = [new Error("network")]; - expect((await cms.bundle("en")).version).toBe(1); - expect(logs).toEqual([ - expect.objectContaining({ - event: "cms_fallback", - source: "snapshot", - locale: "en", - }), - ]); - }); - - test("times out a hanging CMS", async () => { - const cms = source(); - replies = ["hang"]; - expect((await cms.bundle("en")).version).toBe(1); - }); - - test("walks the snapshot chain for a locale without its own file", async () => { - snapshots["es-419.json"] = bundle("es-419", 1); - const cms = source(); - replies = [new Error("network")]; - expect((await cms.bundle("es-ES")).locale).toBe("es-419"); - replies = [new Error("network")]; - expect((await cms.bundle("fr")).locale).toBe("en"); - }); - - test("throws when neither the CMS nor a snapshot is available", async () => { - snapshots = {}; - const cms = source(); - replies = [new Error("network")]; - await expect(cms.bundle("en")).rejects.toThrow(/unavailable/i); - }); - - test("falls back to the default locale when a locale disappeared", async () => { - const cms = source(); - replies = [ - new Response( - JSON.stringify({ error: { code: "locale_not_found", message: "x" } }), - { status: 404 }, - ), - json(bundle("en", 7), '"v7"'), - ]; - expect((await cms.bundle("es-ES")).locale).toBe("en"); - expect(requests.map((r) => r.path)).toEqual([ - "/v1/content/es-ES", - "/v1/content/en", - ]); - }); -}); - -describe("locales", () => { - test("fetches live with the same caching", async () => { - const cms = source(); - const live = { default: "en", locales: [index.locales[0]] }; - replies = [json(live, '"v3"')]; - expect(await cms.locales()).toEqual(live); - await cms.locales(); - expect(requests).toEqual([{ path: "/v1/locales", etag: null }]); - }); - - test("falls back to the snapshot index", async () => { - const cms = source(); - replies = [new Error("network")]; - expect((await cms.locales()).locales).toHaveLength(3); - expect(logs[0]).toMatchObject({ source: "snapshot", locale: null }); - }); -}); diff --git a/verification/content.test.ts b/verification/content.test.ts new file mode 100644 index 0000000..280a4c7 --- /dev/null +++ b/verification/content.test.ts @@ -0,0 +1,94 @@ +import { expect, test } from "bun:test"; +import { english } from "../src/lib/copy/content/english"; +import { placeholders } from "../src/lib/copy/content/placeholders"; +import { angleIds, aspectTypes, bodyIds, signIds } from "../src/lib/identities"; +import pseudo from "../tests/fixtures/pseudo-locale.json"; + +const signature = (text: string) => + [ + ...new Set( + Array.from( + text.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g), + ([, name]) => name, + ), + ), + ].sort(); + +test("English UI files contain unique keys for their feature and valid placeholders", async () => { + const ui = new Map(); + const root = new URL("../src/lib/copy/content/en/ui/", import.meta.url) + .pathname; + for await (const file of new Bun.Glob("*.json").scan(root)) { + const values = (await Bun.file(root + file).json()) as Record< + string, + string + >; + for (const [key, value] of Object.entries(values)) { + expect(key.split(".")[0] + ".json", key).toBe(file); + expect(ui.has(key), key).toBe(false); + expect(typeof value, key).toBe("string"); + expect(value.trim(), key).not.toBe(""); + expect(signature(value), key).toEqual( + [ + ...(Object.entries(placeholders).find( + ([entry]) => entry === key, + )?.[1] ?? []), + ].sort(), + ); + ui.set(key, value); + } + } + expect(Object.fromEntries(ui)).toEqual(english.ui); +}); + +const verifyReference = (key: string, entry: unknown, named: boolean) => { + expect(entry, key).toBeObject(); + const fields = entry as Record; + expect(Object.keys(fields).sort(), key).toEqual( + named ? ["insight", "keywords", "name"] : ["insight", "keywords"], + ); + expect(typeof fields.insight, key).toBe("string"); + expect((fields.insight as string).trim(), key).not.toBe(""); + if (named) { + expect(typeof fields.name, key).toBe("string"); + expect((fields.name as string).trim(), key).not.toBe(""); + } + expect(Array.isArray(fields.keywords), key).toBe(true); + const keywords = fields.keywords as unknown[]; + expect(keywords.length, key).toBeGreaterThan(0); + for (const keyword of keywords) { + expect(typeof keyword, key).toBe("string"); + expect((keyword as string).trim(), key).not.toBe(""); + } +}; + +test("English defines each chart reference with the expected fields", () => { + const collections = { + body: bodyIds, + angle: angleIds, + sign: signIds, + aspect: aspectTypes, + house: Array.from({ length: 12 }, (_, index) => String(index + 1)), + }; + for (const key of Object.keys(collections) as (keyof typeof collections)[]) { + expect(Object.keys(english[key]).sort(), key).toEqual( + [...collections[key]].sort(), + ); + for (const [id, entry] of Object.entries(english[key])) + verifyReference(`${key}:${id}`, entry, key !== "house"); + } +}); + +test("the pseudo-locale translates known entries with matching fields and placeholders", () => { + const ui = new Map(Object.entries(english.ui)); + for (const [key, value] of Object.entries(pseudo.entries.ui)) { + const original = ui.get(key); + expect(original, key).toBeDefined(); + expect(value.trim(), key).not.toBe(""); + expect(signature(value), key).toEqual(signature(original!)); + } + for (const [key, entry] of Object.entries(pseudo.entries.body)) { + expect(Object.hasOwn(english.body, key), key).toBe(true); + verifyReference(key, entry, true); + } +}); diff --git a/verification/copy.test.ts b/verification/copy.test.ts index 528db7a..5d75add 100644 --- a/verification/copy.test.ts +++ b/verification/copy.test.ts @@ -3,9 +3,6 @@ import { createCopy, type Bundle } from "../src/lib/copy/copy"; const bundle: Bundle = { locale: "en", - default: "en", - chain: ["en"], - version: 3, entries: { body: { SUN: { name: "Sun", insight: "Identity.", keywords: ["identity"] }, @@ -21,13 +18,12 @@ const bundle: Bundle = { }, house: { "1": { insight: "Presence.", keywords: ["presence"] } }, ui: { - "brand.name": { text: "Astrology Engine" }, - "chart.house.name": { text: "House {number}" }, - "app.entry.summary": { text: "{date} at {time} in {place}" }, - "landing.hero.title": { text: "Explore your\nbirth chart." }, + "brand.name": "Astrology Engine", + "chart.house.name": "House {number}", + "app.entry.summary": "{date} at {time} in {place}", + "landing.hero.title": "Explore your\nbirth chart.", }, }, - fallbacks: {}, }; describe("createCopy", () => { diff --git a/verification/locale.test.ts b/verification/locale.test.ts index a1b350a..9e7be12 100644 --- a/verification/locale.test.ts +++ b/verification/locale.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { chooseLocale } from "../src/lib/server/cms/locale"; +import { chooseLocale } from "../src/lib/server/content/locale"; const enabled = ["en", "es-419", "pt"]; const choose = (input: { diff --git a/vite.config.ts b/vite.config.ts index 2e95d9d..7fd75b9 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,16 +1,4 @@ import { sveltekit } from "@sveltejs/kit/vite"; -import { defineConfig, searchForWorkspaceRoot } from "vite"; -import { resolve } from "node:path"; -export default defineConfig({ - plugins: [sveltekit()], - server: process.env.CMS_REPO_PATH - ? { - fs: { - allow: [ - searchForWorkspaceRoot(process.cwd()), - resolve(process.env.CMS_REPO_PATH, "packages/contract"), - ], - }, - } - : {}, -}); +import { defineConfig } from "vite"; + +export default defineConfig({ plugins: [sveltekit()] }); diff --git a/wrangler.jsonc b/wrangler.jsonc index 2b1e636..29d3db0 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -8,9 +8,6 @@ "binding": "ASSETS", "directory": ".svelte-kit/cloudflare", }, - // CMS copy via Service Binding (docs/designs/cms.md §9.1). Bindings are not - // inherited by environments, so each environment names its CMS Worker. - "services": [{ "binding": "CMS", "service": "astrology-engine-cms-local" }], "workers_dev": false, "preview_urls": false, "observability": { @@ -26,15 +23,8 @@ "env": { "staging": { "preview_urls": true, - "previews": { - "services": [ - { "binding": "CMS", "service": "astrology-engine-cms-staging" }, - ], - }, + "previews": {}, "name": "astrology-engine-web-staging", - "services": [ - { "binding": "CMS", "service": "astrology-engine-cms-staging" }, - ], "routes": [ { "pattern": "staging.astrologyengine.dev", @@ -44,9 +34,6 @@ }, "alpha": { "name": "astrology-engine-web-alpha", - "services": [ - { "binding": "CMS", "service": "astrology-engine-cms-alpha" }, - ], "routes": [ { "pattern": "alpha.astrologyengine.dev",