Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.
23 changes: 23 additions & 0 deletions docusaurus.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,28 @@ const commonDocsPluginConfig = {
...remarkPluginsConfig,
}

const metadataEndpoint = process.env.SHOWCASE_METADATA_API_URL
const metadataFields: NonNullable<ShowcasePresetOptions['computedFields']> = 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',
Expand Down Expand Up @@ -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,
],
[
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
68 changes: 68 additions & 0 deletions src/utils/showcaseMetadata.ts
Original file line number Diff line number Diff line change
@@ -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<string, { expires: number; promise: Promise<ComputedFieldValue[]> }>()

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<ComputedFieldValue[]> {
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
}
Loading
Loading