From eb2df0d2d774739f1c264f9fd92f6489b73ad50e Mon Sep 17 00:00:00 2001 From: Mikey O'Toole Date: Mon, 16 Nov 2026 19:47:40 +0000 Subject: [PATCH] feat: implement metadata worker for npm and GitHub integration with caching --- .github/workflows/publish.yml | 52 ++++++- README.md | 52 +++++++ docusaurus.config.ts | 23 ++++ package.json | 2 +- src/utils/showcaseMetadata.ts | 68 +++++++++ tests/showcase-metadata.test.mjs | 228 +++++++++++++++++++++++++++++++ workers/metadata/LICENSE | 13 ++ workers/metadata/package.json | 5 + workers/metadata/worker.mjs | 141 +++++++++++++++++++ workers/metadata/wrangler.jsonc | 10 ++ yarn.lock | 10 +- 11 files changed, 597 insertions(+), 7 deletions(-) create mode 100644 src/utils/showcaseMetadata.ts create mode 100644 tests/showcase-metadata.test.mjs create mode 100644 workers/metadata/LICENSE create mode 100644 workers/metadata/package.json create mode 100644 workers/metadata/worker.mjs create mode 100644 workers/metadata/wrangler.jsonc diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 776adca..df20f0e 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -34,22 +34,66 @@ permissions: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: + metadata: + name: Deploy metadata Worker + runs-on: ubuntu-latest + if: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} + permissions: + contents: read + concurrency: + group: community-metadata-production + cancel-in-progress: false + timeout-minutes: 10 + outputs: + endpoint: ${{ steps.worker.outputs.deployment-url }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-node@v6 + with: + node-version: '24' + - name: Test metadata Worker and resolvers + run: node --test tests/showcase-metadata.test.mjs + - name: Deploy metadata Worker + id: worker + uses: cloudflare/wrangler-action@v4 + with: + accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + workingDirectory: workers/metadata + packageManager: npm + command: deploy + secrets: ${{ secrets.METADATA_GITHUB_TOKEN != '' && 'GITHUB_TOKEN' || '' }} + env: + GITHUB_TOKEN: ${{ secrets.METADATA_GITHUB_TOKEN }} + - name: Check metadata endpoint + env: + ENDPOINT: ${{ steps.worker.outputs.deployment-url }} + run: | + test -n "$ENDPOINT" + curl --fail --retry 5 --retry-delay 3 --retry-all-errors --max-time 15 "$ENDPOINT/health" + # Deploy deploy: name: Deploy + needs: metadata runs-on: ${{ matrix.os }} # push event in main branch # workflow_dispatch event # pull_request event from not forked repo # pull_request_target event with label "🚀request-deploy" from forked repo if: ${{ + always() && + (needs.metadata.result == 'success' || needs.metadata.result == 'skipped') && + ( github.event_name == 'push' || github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false) || (github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.pull_request.head.repo.fork == true && - contains(github.event.label.name, '🚀request-deploy')) + contains(github.event.label.name, '🚀request-deploy'))) }} strategy: @@ -89,8 +133,14 @@ jobs: - name: Install dependencies run: yarn install --check-cache + - name: Test metadata Worker and resolvers + if: ${{ needs.metadata.result == 'skipped' }} + run: node --test tests/showcase-metadata.test.mjs + - name: Build website run: yarn build + env: + SHOWCASE_METADATA_API_URL: ${{ needs.metadata.outputs.endpoint || vars.SHOWCASE_METADATA_API_URL }} - name: Publish to Cloudflare Pages id: cloudflare-pages-deploy diff --git a/README.md b/README.md index ab4641d..61140f2 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,46 @@ assets and a [simplified favicon](static/img/community-favicon.svg). The desktop navbar and mobile menu. Keep the two mark variants geometrically identical. The green Docusaurus icon in the external link and footer still identifies the upstream project. +## Live plugin metadata + +The plugin directory can show npm's `latest` version, the latest stable GitHub release, and the +latest default-branch commit. These fields load in the browser through +[`showcaseMetadata.ts`](src/utils/showcaseMetadata.ts) and the separate +[metadata Worker](workers/metadata/worker.mjs), adapted from the +[showcase plugin example](https://github.com/homotechsual/docusaurus-plugin-showcase/tree/13e25e2b6fc3bc1f10d663027686f41abfeff1c6/examples/metadata-worker) +and its [demo resolvers](https://github.com/homotechsual/docusaurus-plugin-showcase/blob/13e25e2b6fc3bc1f10d663027686f41abfeff1c6/demo/src/lib/metadata-resolvers.ts). +The imported code is Apache-2.0 licensed; see [its licence](workers/metadata/LICENSE). + +Set `SHOWCASE_METADATA_API_URL` when building or starting the website. Without it, the build logs +a warning and leaves the fields disabled. No GitHub token belongs in this variable or in the site +configuration. + +For local development, run `npx wrangler dev` from `workers/metadata`, then in a second terminal: + +```powershell +$env:SHOWCASE_METADATA_API_URL = 'http://localhost:8787' +yarn start +``` + +The Worker's private `package.json` isolates Wrangler's npm tooling from the parent Yarn project. +The [Wrangler configuration](workers/metadata/wrangler.jsonc) permits the production site, local +development, and HTTPS previews for the `docusauruscommunity-website` Pages project. +These are CORS rules, not authentication: the Worker is a public, read-only API. +It only fetches validated npm packages and public GitHub repositories from fixed upstream hosts. + +Successful responses and public-repository checks are cached for 15 minutes within a Cloudflare +data centre. The browser resolvers cache results for five minutes. Provider errors are not cached +by the Worker; the showcase component displays an error with a retry option. Caching is best-effort, +not a guarantee against upstream rate limits. + +Run the Worker and resolver tests with Node.js 24 or newer: + +```powershell +node --test tests\showcase-metadata.test.mjs +``` + +## Social share image + The default social share image is [community-social-card.png](static/img/community-social-card.png) (1200 x 630). Its editable source is [community-social-card.svg](static/img/community-social-card.svg). After editing the SVG, regenerate the PNG from the repository root with the existing Sharp dependency: @@ -99,5 +139,17 @@ Pull requests from the same repository receive preview deployments. For forked p a maintainer must review the changes and add the `🚀request-deploy` label to request deployment. The workflow requires the `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` repository secrets. +The Cloudflare token needs Pages deployment and Workers editing permissions. On `main`, the workflow +deploys the metadata Worker first, checks `/health`, and passes its URL to the site build. PRs and +manual runs on other branches do not deploy the production Worker. + +Set the repository **variable** `SHOWCASE_METADATA_API_URL` to the deployed Worker URL (or a custom +domain) so preview builds can reuse it. Optionally add a long-lived, public-only GitHub token as +the repository **secret** `METADATA_GITHUB_TOKEN`; deployment stores it as the Worker's +`GITHUB_TOKEN` secret. The short-lived Actions token is not used for upstream metadata. Removing +the repository secret does not delete a previously stored Worker secret; use +`npx wrangler secret delete GITHUB_TOKEN` from `workers/metadata` to remove that binding. +No live Worker deployment is performed by a local website build. + For local work, use `yarn build` and `yarn serve`; `yarn deploy` is Docusaurus's GitHub Pages deployment command and is not the deployment path for this site. diff --git a/docusaurus.config.ts b/docusaurus.config.ts index b30779e..daeb548 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -66,6 +66,28 @@ const commonDocsPluginConfig = { ...remarkPluginsConfig, } +const metadataEndpoint = process.env.SHOWCASE_METADATA_API_URL +const metadataFields: NonNullable = metadataEndpoint ? { + npmVersions: { + label: 'npm version', + resolver: { module: '@site/src/utils/showcaseMetadata.ts', exportName: 'npmVersions' }, + options: { endpoint: metadataEndpoint }, + }, + githubRelease: { + label: 'Latest GitHub release', + resolver: { module: '@site/src/utils/showcaseMetadata.ts', exportName: 'githubRelease' }, + options: { endpoint: metadataEndpoint }, + }, + githubCommit: { + label: 'Latest code update', + resolver: { module: '@site/src/utils/showcaseMetadata.ts', exportName: 'githubCommit' }, + options: { endpoint: metadataEndpoint }, + }, +} : {} +if (!metadataEndpoint) { + console.warn('[showcase] SHOWCASE_METADATA_API_URL is unset; live plugin metadata is disabled.') +} + /** @type {import('@docusaurus/types').Config} */ const config: Config = { title: 'Docusaurus.community', @@ -289,6 +311,7 @@ const config: Config = { screenshotUrl: 'https://screengrabber.tools.homotechsual.dev/{url}/opengraph/_width:640?format=jpeg', submitUrl: '/contributing/plugins/', submitLabel: 'Add a plugin', + computedFields: metadataFields, } satisfies ShowcasePresetOptions, ], [ diff --git a/package.json b/package.json index 03a65cd..c7208a4 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "@fortawesome/free-solid-svg-icons": "^7.3.1", "@fortawesome/react-fontawesome": "^3.5.0", "@homotechsual/docusaurus-plugin-plausible": "^1.1.1", - "@homotechsual/docusaurus-plugin-showcase": "1.2.3", + "@homotechsual/docusaurus-plugin-showcase": "1.3.0", "@iconify/react": "^6.0.4", "@mdx-js/react": "^3.1.1", "@popperjs/core": "^2.11.8", diff --git a/src/utils/showcaseMetadata.ts b/src/utils/showcaseMetadata.ts new file mode 100644 index 0000000..87cba6e --- /dev/null +++ b/src/utils/showcaseMetadata.ts @@ -0,0 +1,68 @@ +// Adapted from homotechsual/docusaurus-plugin-showcase, demo/src/lib/metadata-resolvers.ts. +// SPDX-License-Identifier: Apache-2.0 +import type { + ComputedFieldContext, + ComputedFieldResolver, + ComputedFieldValue, +} from '@homotechsual/docusaurus-plugin-showcase' + +const requests = new Map }>() + +function isValue(value: unknown): value is ComputedFieldValue { + return !!value && typeof value === 'object' && + 'text' in value && typeof value.text === 'string' && + (!('href' in value) || (typeof value.href === 'string' && /^https?:\/\//i.test(value.href))) && + (!('date' in value) || (typeof value.date === 'string' && Number.isFinite(Date.parse(value.date)))) +} + +function metadata(path: string, context: ComputedFieldContext): Promise { + const endpoint = context.options.endpoint + if (typeof endpoint !== 'string' || !endpoint) throw new Error('Metadata API endpoint is not configured.') + const url = new URL(path, `${endpoint.replace(/\/$/, '')}/`).href + const cached = requests.get(url) + if (cached && cached.expires > Date.now()) return cached.promise + const promise = fetch(url, { signal: AbortSignal.timeout(15_000) }).then(async (response) => { + if (!response.ok) throw new Error(`Metadata API request failed (${response.status}).`) + const body: unknown = await response.json() + if (!body || typeof body !== 'object' || !('values' in body) || + !Array.isArray(body.values) || !body.values.every(isValue)) { + throw new Error('Invalid metadata API response.') + } + return body.values + }).catch((error: unknown) => { + requests.delete(url) + throw error + }) + requests.set(url, { expires: Date.now() + 300_000, promise }) + return promise +} + +function repository(source: string | null | undefined): string | null { + if (!source) return null + let url: URL + try { + url = new URL(source) + } catch { + throw new Error('Invalid source URL.') + } + if (url.hostname !== 'github.com') return null + const parts = url.pathname.split('/').filter(Boolean) + if (parts.length < 2) throw new Error('GitHub source URL must identify a repository.') + return `${parts[0]}/${parts[1].replace(/\.git$/, '')}` +} + +export const npmVersions: ComputedFieldResolver = async (item, context) => { + if (!item.npmPackages?.length) return null + return (await Promise.all(item.npmPackages.map((name) => + metadata(`npm?package=${encodeURIComponent(name)}`, context)))).flat() +} + +export const githubRelease: ComputedFieldResolver = (item, context) => { + const repo = repository(item.source) + return repo ? metadata(`github/release?repo=${encodeURIComponent(repo)}`, context) : null +} + +export const githubCommit: ComputedFieldResolver = (item, context) => { + const repo = repository(item.source) + return repo ? metadata(`github/commit?repo=${encodeURIComponent(repo)}`, context) : null +} diff --git a/tests/showcase-metadata.test.mjs b/tests/showcase-metadata.test.mjs new file mode 100644 index 0000000..e98b251 --- /dev/null +++ b/tests/showcase-metadata.test.mjs @@ -0,0 +1,228 @@ +import assert from 'node:assert/strict' +import { afterEach, beforeEach, test } from 'node:test' +import worker from '../workers/metadata/worker.mjs' +import { githubCommit, githubRelease, npmVersions } from '../src/utils/showcaseMetadata.ts' + +const env = { + ALLOWED_ORIGINS: 'https://docusaurus.community,http://localhost:3000', + PAGES_PROJECT: 'docusauruscommunity-website', + GITHUB_TOKEN: 'test-token', +} +const originalFetch = globalThis.fetch +const originalCaches = globalThis.caches +let stored +let pending +let calls +let responses + +beforeEach(() => { + stored = new Map() + pending = [] + calls = [] + responses = [] + globalThis.fetch = async (...args) => { + calls.push(args) + const response = responses.shift() + assert.ok(response, 'Unexpected upstream request') + return response + } + globalThis.caches = { default: { + match: async (key) => stored.get(key.url)?.clone(), + put: async (key, response) => { stored.set(key.url, response.clone()) }, + } } +}) + +afterEach(() => { + globalThis.fetch = originalFetch + if (originalCaches === undefined) delete globalThis.caches + else globalThis.caches = originalCaches +}) + +async function request(path, origin = 'https://docusaurus.community', method = 'GET') { + const response = await worker.fetch(new Request(`https://metadata.example.com${path}`, { + method, headers: { Origin: origin }, + }), env, { waitUntil: (promise) => pending.push(promise) }) + await Promise.all(pending) + pending = [] + return response +} + +test('npm versions use latest, normalize cache keys, and attach CORS per request', async () => { + responses.push(Response.json({ version: '1.2.3' })) + const first = await request('/npm?package=%40scope%2Fname&ignored=1') + assert.equal(first.status, 200) + assert.deepEqual(await first.json(), { + values: [{ text: '@scope/name: 1.2.3', href: 'https://www.npmjs.com/package/@scope/name' }], + }) + assert.equal(calls[0][0], 'https://registry.npmjs.org/%40scope%2Fname/latest') + assert.equal(calls[0][1].headers.Authorization, undefined) + assert.equal(first.headers.get('Cache-Control'), 'public, max-age=900') + const preview = 'https://branch.docusauruscommunity-website.pages.dev' + const second = await request('/npm?package=@scope/name', preview) + assert.equal(second.headers.get('Access-Control-Allow-Origin'), preview) + assert.equal(calls.length, 1) + assert.equal([...stored.values()][0].headers.has('Access-Control-Allow-Origin'), false) +}) + +test('GitHub release and commit use distinct endpoints and share the repository check', async () => { + const date = '2026-11-01T12:00:00Z' + const sha = 'a'.repeat(40) + responses.push( + Response.json({ private: false }), + Response.json({ tag_name: 'v2.0.0', published_at: date }), + Response.json([{ sha, commit: { committer: { date } } }]), + ) + const release = await request('/github/release?repo=owner/repo') + assert.deepEqual(await release.json(), { + values: [{ text: 'v2.0.0', date, href: 'https://github.com/owner/repo/releases/tag/v2.0.0' }], + }) + const commit = await request('/github/commit?repo=owner/repo') + assert.deepEqual(await commit.json(), { + values: [{ text: 'aaaaaaa', date, href: `https://github.com/owner/repo/commit/${sha}` }], + }) + assert.deepEqual(calls.map(([url]) => url), [ + 'https://api.github.com/repos/owner/repo', + 'https://api.github.com/repos/owner/repo/releases/latest', + 'https://api.github.com/repos/owner/repo/commits?per_page=1', + ]) + assert.equal(calls[0][1].headers.Authorization, `Bearer ${env.GITHUB_TOKEN}`) +}) + +test('repositories without releases or commits return explicit values', async () => { + responses.push( + Response.json({ private: false }), + new Response(null, { status: 404 }), + Response.json({ message: 'Git Repository is empty.' }, { status: 409 }), + ) + assert.deepEqual(await (await request('/github/release?repo=owner/empty')).json(), { + values: [{ text: 'No stable releases published' }], + }) + assert.deepEqual(await (await request('/github/commit?repo=owner/empty')).json(), { + values: [{ text: 'No code updates' }], + }) +}) + +test('health and preflight do not call upstream; CORS excludes lookalike domains', async () => { + assert.deepEqual(await (await request('/health')).json(), { ok: true }) + assert.equal((await request('/npm', 'http://localhost:3000', 'OPTIONS')).status, 204) + for (const origin of [ + 'https://docusauruscommunity-website.pages.dev.evil.example', + 'https://other.pages.dev', + 'http://branch.docusauruscommunity-website.pages.dev', + 'https://branch.docusauruscommunity-website.pages.dev:8443', + ]) { + assert.equal((await request('/health', origin)).headers.get('Access-Control-Allow-Origin'), null) + } + assert.equal(calls.length, 0) +}) + +test('invalid inputs, private repositories, and provider failures are errors, not cached values', async (t) => { + t.mock.method(console, 'error', () => {}) + for (const path of ['/npm?package=../secret', '/github/release?repo=owner/..', '/other']) { + assert.ok((await request(path)).status >= 400) + } + assert.equal((await request('/health', undefined, 'POST')).status, 405) + assert.equal(calls.length, 0) + responses.push(Response.json({ private: true })) + assert.equal((await request('/github/release?repo=owner/private')).status, 404) + assert.equal(calls.length, 1) + responses.push(new Response(null, { status: 429 })) + const failed = await request('/npm?package=rate-limited') + assert.equal(failed.status, 503) + assert.equal(failed.headers.get('Cache-Control'), 'no-store') + responses.push(Response.json({ version: '2.0.0' })) + assert.equal((await request('/npm?package=rate-limited')).status, 200) +}) + +test('malformed provider responses are rejected', async (t) => { + t.mock.method(console, 'error', () => {}) + responses.push(Response.json({ version: 123 })) + assert.equal((await request('/npm?package=invalid-version')).status, 502) + responses.push( + Response.json({ private: false }), + Response.json({ tag_name: 'v1', published_at: 'not-a-date' }), + Response.json([{ sha: 'bad', commit: { committer: { date: 'not-a-date' } } }]), + ) + assert.equal((await request('/github/release?repo=owner/invalid')).status, 502) + assert.equal((await request('/github/commit?repo=owner/invalid')).status, 502) +}) + +function context(name) { + return { options: { endpoint: `https://${name}.example.com` } } +} + +function item(fields = {}) { + return { id: 'test.plugin', name: 'Test', description: 'Test plugin', tags: [], ...fields } +} + +test('resolvers skip inapplicable fields without requests', async () => { + assert.equal(await npmVersions(item(), context('skip')), null) + assert.equal(await githubRelease(item({ source: 'https://gitlab.com/owner/repo' }), context('skip')), null) + assert.equal(await githubCommit(item(), context('skip')), null) + assert.equal(calls.length, 0) +}) + +test('npm resolver resolves all packages and deduplicates shared requests', async () => { + const values = [{ text: '@scope/one: 1.0.0' }, { text: 'two: 2.0.0' }] + responses.push(Response.json({ values: [values[0]] }), Response.json({ values: [values[1]] })) + const packages = item({ npmPackages: ['@scope/one', 'two'] }) + const [first, second] = await Promise.all([ + npmVersions(packages, context('npm')), + npmVersions(packages, context('npm')), + ]) + assert.deepEqual(first, values) + assert.deepEqual(second, values) + assert.equal(calls.length, 2) + assert.equal(calls[0][0], 'https://npm.example.com/npm?package=%40scope%2Fone') +}) + +test('GitHub resolvers normalize source URLs and keep release and commit independent', async () => { + responses.push(Response.json({ values: [{ text: 'v1' }] }), Response.json({ values: [{ text: 'abcdefg' }] })) + const plugin = item({ source: 'https://github.com/owner/repo.git/tree/main' }) + await githubRelease(plugin, context('github')) + await githubCommit(plugin, context('github')) + assert.deepEqual(calls.map(([url]) => url), [ + 'https://github.example.com/github/release?repo=owner%2Frepo', + 'https://github.example.com/github/commit?repo=owner%2Frepo', + ]) +}) + +test('resolver reports failures and lets a subsequent retry succeed', async () => { + const plugin = item({ npmPackages: ['retry-package'] }) + responses.push(new Response(null, { status: 503 }), Response.json({ values: [{ text: '1.0.0' }] })) + await assert.rejects(npmVersions(plugin, context('retry')), /503/) + assert.deepEqual(await npmVersions(plugin, context('retry')), [{ text: '1.0.0' }]) +}) + +test('resolver refreshes successful results after five minutes', async (t) => { + let now = Date.now() + t.mock.method(Date, 'now', () => now) + responses.push( + Response.json({ values: [{ text: '1.0.0' }] }), + Response.json({ values: [{ text: '2.0.0' }] }), + ) + const plugin = item({ npmPackages: ['expiring-package'] }) + assert.deepEqual(await npmVersions(plugin, context('expiry')), [{ text: '1.0.0' }]) + assert.deepEqual(await npmVersions(plugin, context('expiry')), [{ text: '1.0.0' }]) + assert.equal(calls.length, 1) + now += 300_001 + assert.deepEqual(await npmVersions(plugin, context('expiry')), [{ text: '2.0.0' }]) + assert.equal(calls.length, 2) +}) + +test('resolver rejects missing configuration and malformed metadata', async () => { + const plugin = item({ npmPackages: ['invalid-package'] }) + await assert.rejects(npmVersions(plugin, { options: {} }), /not configured/) + for (const values of [ + [{ text: 123 }], + [{ text: 'bad link', href: 'javascript:alert(1)' }], + [{ text: 'bad date', date: 'yesterday' }], + ]) { + responses.push(Response.json({ values })) + await assert.rejects(npmVersions(plugin, context('invalid')), /Invalid metadata API response/) + } + responses.push(Response.json({ values: [{ text: 'v1', date: '2026-11-01T12:00:00Z' }] })) + assert.equal((await npmVersions(plugin, context('invalid'))).length, 1) + assert.throws(() => githubRelease(item({ source: 'not a URL' }), context('source')), /Invalid source URL/) + assert.throws(() => githubRelease(item({ source: 'https://github.com/owner' }), context('source')), /identify a repository/) +}) diff --git a/workers/metadata/LICENSE b/workers/metadata/LICENSE new file mode 100644 index 0000000..651ce14 --- /dev/null +++ b/workers/metadata/LICENSE @@ -0,0 +1,13 @@ +Copyright 2024 Mikey O'Toole + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/workers/metadata/package.json b/workers/metadata/package.json new file mode 100644 index 0000000..1bd1116 --- /dev/null +++ b/workers/metadata/package.json @@ -0,0 +1,5 @@ +{ + "name": "docusaurus-community-metadata", + "private": true, + "type": "module" +} diff --git a/workers/metadata/worker.mjs b/workers/metadata/worker.mjs new file mode 100644 index 0000000..4b30fc3 --- /dev/null +++ b/workers/metadata/worker.mjs @@ -0,0 +1,141 @@ +// Adapted from homotechsual/docusaurus-plugin-showcase, examples/metadata-worker. +// SPDX-License-Identifier: Apache-2.0 +const TTL = 900 + +class HttpError extends Error { + constructor(status, message) { + super(message) + this.status = status + } +} + +function corsHeaders(request, env) { + const origin = request.headers.get('Origin') + const allowed = (env.ALLOWED_ORIGINS ?? '').split(',').map((value) => value.trim()) + let preview = false + if (origin && env.PAGES_PROJECT) { + const url = new URL(origin) + const domain = `${env.PAGES_PROJECT}.pages.dev` + preview = url.protocol === 'https:' && !url.port && + (url.hostname === domain || url.hostname.endsWith(`.${domain}`)) + } + return { + ...(origin && (allowed.includes(origin) || preview) ? { 'Access-Control-Allow-Origin': origin } : {}), + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Vary': 'Origin', + } +} + +async function upstream(url, env, github = false) { + const response = await fetch(url, { + headers: github ? { + Accept: 'application/vnd.github+json', + 'User-Agent': 'docusaurus-community-metadata', + 'X-GitHub-Api-Version': '2022-11-28', + ...(env.GITHUB_TOKEN ? { Authorization: `Bearer ${env.GITHUB_TOKEN}` } : {}), + } : { Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }) + if (response.status === 404) return null + if (github && url.endsWith('/commits?per_page=1') && response.status === 409) { + const body = await response.json() + if (body.message === 'Git Repository is empty.') return [] + } + if (!response.ok) { + throw new HttpError(response.status === 429 || response.status === 403 ? 503 : 502, + `Metadata provider request failed (${response.status}).`) + } + return response.json() +} + +async function githubRepository(repo, env, cache, origin) { + const key = new Request(`${origin}/_repository?repo=${encodeURIComponent(repo)}`) + const cached = await cache.match(key) + if (cached) return cached.json() + const value = await upstream(`https://api.github.com/repos/${repo}`, env, true) + if (!value || value.private !== false) throw new HttpError(404, 'Public GitHub repository not found.') + const response = Response.json(value, { headers: { 'Cache-Control': `public, max-age=${TTL}` } }) + await cache.put(key, response) + return value +} + +export default { + async fetch(request, env, context) { + let cors = {} + try { + cors = corsHeaders(request, env) + if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors }) + if (request.method !== 'GET') throw new HttpError(405, 'Only GET is supported.') + const url = new URL(request.url) + if (url.pathname === '/health') return Response.json({ ok: true }, { headers: cors }) + let providerUrl + let packageName + let repo + if (url.pathname === '/npm') { + packageName = url.searchParams.get('package') + if (!packageName || packageName.length > 214 || + !/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(packageName)) { + throw new HttpError(400, 'Invalid npm package name.') + } + providerUrl = `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest` + } else if (url.pathname === '/github/release' || url.pathname === '/github/commit') { + repo = url.searchParams.get('repo') + if (!repo || repo.length > 200 || !/^[a-z0-9][a-z0-9-]*\/[a-z0-9._-]+$/i.test(repo) || + repo.split('/')[1] === '.' || repo.split('/')[1] === '..') { + throw new HttpError(400, 'Invalid GitHub repository.') + } + providerUrl = `https://api.github.com/repos/${repo}/${url.pathname.endsWith('release') ? 'releases/latest' : 'commits?per_page=1'}` + } else { + throw new HttpError(404, 'Unknown metadata endpoint.') + } + const cache = caches.default + const keyUrl = new URL(url.pathname, url.origin) + keyUrl.searchParams.set(packageName ? 'package' : 'repo', packageName ?? repo) + const key = new Request(keyUrl) + const cached = await cache.match(key) + if (cached) { + const response = new Response(cached.body, cached) + for (const [name, value] of Object.entries(cors)) response.headers.set(name, value) + return response + } + if (repo) await githubRepository(repo, env, cache, url.origin) + const data = await upstream(providerUrl, env, !!repo) + let values + if (packageName) { + if (!data) throw new HttpError(404, 'npm package not found.') + if (typeof data.version !== 'string') throw new HttpError(502, 'Invalid npm version response.') + values = [{ text: `${packageName}: ${data.version}`, href: `https://www.npmjs.com/package/${packageName}` }] + } else if (url.pathname.endsWith('release')) { + if (data === null) { + values = [{ text: 'No stable releases published' }] + } else { + if (typeof data.tag_name !== 'string' || typeof data.published_at !== 'string' || + !Number.isFinite(Date.parse(data.published_at))) throw new HttpError(502, 'Invalid GitHub release response.') + values = [{ text: data.tag_name, date: data.published_at, href: `https://github.com/${repo}/releases/tag/${encodeURIComponent(data.tag_name)}` }] + } + } else { + if (!Array.isArray(data)) throw new HttpError(502, 'Invalid GitHub commit response.') + if (data.length === 0) { + values = [{ text: 'No code updates' }] + } else { + const commit = data[0] + if (typeof commit.sha !== 'string' || !/^[a-f0-9]{40,64}$/i.test(commit.sha) || + !Number.isFinite(Date.parse(commit.commit?.committer?.date))) throw new HttpError(502, 'Invalid GitHub commit response.') + values = [{ text: commit.sha.slice(0, 7), date: commit.commit.committer.date, href: `https://github.com/${repo}/commit/${commit.sha}` }] + } + } + const response = Response.json({ values }, { + headers: { 'Cache-Control': `public, max-age=${TTL}`, 'X-Content-Type-Options': 'nosniff' }, + }) + context.waitUntil(cache.put(key, response.clone())) + for (const [name, value] of Object.entries(cors)) response.headers.set(name, value) + return response + } catch (error) { + console.error('Metadata request failed:', error) + return Response.json({ error: error instanceof HttpError ? error.message : 'Metadata request failed.' }, { + status: error instanceof HttpError ? error.status : 502, + headers: { ...cors, 'Cache-Control': 'no-store' }, + }) + } + }, +} diff --git a/workers/metadata/wrangler.jsonc b/workers/metadata/wrangler.jsonc new file mode 100644 index 0000000..f29fc6b --- /dev/null +++ b/workers/metadata/wrangler.jsonc @@ -0,0 +1,10 @@ +{ + "name": "docusaurus-community-metadata", + "main": "worker.mjs", + "compatibility_date": "2026-11-01", + "workers_dev": true, + "vars": { + "ALLOWED_ORIGINS": "https://docusaurus.community,https://www.docusaurus.community,http://localhost:3000,http://127.0.0.1:3000", + "PAGES_PROJECT": "docusauruscommunity-website" + } +} diff --git a/yarn.lock b/yarn.lock index bd56057..7328541 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4782,9 +4782,9 @@ __metadata: languageName: node linkType: hard -"@homotechsual/docusaurus-plugin-showcase@npm:1.2.3": - version: 1.2.3 - resolution: "@homotechsual/docusaurus-plugin-showcase@npm:1.2.3" +"@homotechsual/docusaurus-plugin-showcase@npm:1.3.0": + version: 1.3.0 + resolution: "@homotechsual/docusaurus-plugin-showcase@npm:1.3.0" dependencies: "@docusaurus/faster": "npm:^3.10.1" "@popperjs/core": "npm:^2.11.8" @@ -4798,7 +4798,7 @@ __metadata: "@docusaurus/core": ">=3.0.0 <5.0.0" react: ~19.2.7 react-dom: ~19.2.7 - checksum: 10c0/86462b54a857f516abb9a8f8fdf9939bfde51aad47066ab7183d3a2c5f4268adb665fc8a7dda69f0508721aeababea298ef709ab4fa128a8f38de64b07017593 + checksum: 10c0/4e75fa5574cb624818043ea73afb0d2c93e4f5686b26c4926ca3c169dc097deff81be6f42875e19fc689dfd7f358d6baa4d1701ca01227dcbb3e70a0e7585ee4 languageName: node linkType: hard @@ -10642,7 +10642,7 @@ __metadata: "@fortawesome/free-solid-svg-icons": "npm:^7.3.1" "@fortawesome/react-fontawesome": "npm:^3.5.0" "@homotechsual/docusaurus-plugin-plausible": "npm:^1.1.1" - "@homotechsual/docusaurus-plugin-showcase": "npm:1.2.3" + "@homotechsual/docusaurus-plugin-showcase": "npm:1.3.0" "@iconify/react": "npm:^6.0.4" "@mdx-js/react": "npm:^3.1.1" "@popperjs/core": "npm:^2.11.8"