🎥 Make videos programmatically with React
`@remotion/remotion-media`: optimize content negotiation for coding agents fetch calls (#10307)
Igor Samokhovets0f209676a87f
diff --git a/packages/remotion-media/README.md b/packages/remotion-media/README.mdindex e1c1560d64..b4cf843367 100644--- a/packages/remotion-media/README.md+++ b/packages/remotion-media/README.md@@ -29,3 +29,34 @@ bun run build```HLS files are uploaded through the AWS CLI so their MIME types are preserved.++## Production hosting and content negotiation++Production is served directly from the Cloudflare R2 bucket `parser-media`; the+Bun server in `src/index.tsx` is only used locally. Cloudflare Rules mirror its+content negotiation for requests to `https://remotion.media/`.++The conditional URL Rewrite Rule runs after the existing `/` to `/index.html`+rewrite and rewrites the path to `/llms.txt` when this expression matches:++```txt+raw.http.request.uri.path eq "/" and http.request.method in {"GET" "HEAD"} and (http.user_agent contains "Claude-User" or http.user_agent contains "opencode" or any(http.request.headers["accept"][*] contains "text/markdown") or any(http.request.headers["accept"][*] contains "text/x-markdown") or (any(http.request.headers["accept"][*] contains "text/plain") and not any(http.request.headers["accept"][*] contains "text/html")))+```++The following additional rules apply to the original root path:++- A Response Header Transform Rule sets `Vary: Accept, User-Agent` for+ `raw.http.request.uri.path eq "/"`.+- A Response Header Transform Rule uses the negotiation expression above and+ sets `Content-Type: text/markdown; charset=utf-8`.+- A Cache Rule bypasses caching for `raw.http.request.uri.path eq "/"`, avoiding+ collisions between the HTML and Markdown representations.++After deploying, verify browser, Markdown `Accept`, and known-agent requests:++```bash+curl -I -H 'Accept: text/html' https://remotion.media/+curl -I -H 'Accept: text/markdown' https://remotion.media/+curl -I -A 'Claude-User' https://remotion.media/+curl -I https://remotion.media/llms.txt+```diff --git a/packages/remotion-media/build.ts b/packages/remotion-media/build.tsindex 48587c7443..da7ce04f18 100644--- a/packages/remotion-media/build.ts+++ b/packages/remotion-media/build.ts@@ -1,10 +1,10 @@#!/usr/bin/env bunimport {$, build, S3Client, type BuildConfig} from 'bun';import plugin from 'bun-plugin-tailwind';-import {cpSync, existsSync, readdirSync, writeFileSync} from 'fs';+import {cpSync, existsSync, mkdirSync, readdirSync, writeFileSync} from 'fs';import {rm} from 'fs/promises';import path from 'path';-import {makeAgentsMarkdown} from './src/agents';+import {makeLlmsText} from './src/llms';import variants from './variants.json';// Print help text if requested@@ -192,6 +192,7 @@ const buildTime = (end - start).toFixed(2);console.log(`\n✅ Build completed in ${buildTime}ms\n`);const filesDir = path.join(process.cwd(), 'files');+mkdirSync(filesDir, {recursive: true});for await (const file of new Bun.Glob('chunk-*').scan(filesDir)) {await rm(path.join(filesDir, file));@@ -202,12 +203,17 @@ if (existsSync(indexHtml)) {await rm(indexHtml);}+const agentsMarkdown = path.join(filesDir, 'AGENTS.md');+if (existsSync(agentsMarkdown)) {+ await rm(agentsMarkdown);+}+const files = readdirSync(outdir);for (const file of files) {cpSync(path.join(outdir, file), path.join(filesDir, file));}-writeFileSync(path.join(filesDir, 'AGENTS.md'), makeAgentsMarkdown(variants));+writeFileSync(path.join(filesDir, 'llms.txt'), makeLlmsText(variants));if (!Bun.env.AWS_ACCESS_KEY_ID || !Bun.env.AWS_SECRET_ACCESS_KEY) {console.log(@@ -245,4 +251,9 @@ if (!Bun.env.AWS_ACCESS_KEY_ID || !Bun.env.AWS_SECRET_ACCESS_KEY) {await client.write(file, fileToUpload);console.log(`Uploaded ${file}`);}++ if (await client.exists('AGENTS.md')) {+ await client.delete('AGENTS.md');+ console.log('Deleted AGENTS.md');+ }}diff --git a/packages/remotion-media/src/App.tsx b/packages/remotion-media/src/App.tsxindex 0eda5bf090..f6d518f0e3 100644--- a/packages/remotion-media/src/App.tsx+++ b/packages/remotion-media/src/App.tsx@@ -1,7 +1,7 @@import React, {useEffect, useState} from 'react';import variants from '../variants.json';-import {getCategoryLabel} from './agents';import './index.css';+import {getCategoryLabel} from './llms';const CopyLink = ({href}: {readonly href: string}) => {const [copied, setCopied] = React.useState(false);@@ -224,11 +224,8 @@ export function App() {bandwidth. <br />Files may be used royalty-free and without attribution.<br />- For agents, use{' '}- <a href="/AGENTS.md" className="font-brand text-brand hover:underline">- AGENTS.md- </a>- .+ You can safely pass this website to an AI agent - a Markdown version of+ this catalog will be returned automatically.</p><div className="flex gap-8 items-start"><Sidebardiff --git a/packages/remotion-media/src/index.tsx b/packages/remotion-media/src/index.tsxindex e5e052a91a..0303897858 100644--- a/packages/remotion-media/src/index.tsx+++ b/packages/remotion-media/src/index.tsx@@ -1,17 +1,72 @@import {serve} from 'bun';import variants from '../variants.json';-import {makeAgentsMarkdown} from './agents';import index from './index.html';+import {makeLlmsText} from './llms';-const agentsMarkdown = makeAgentsMarkdown(variants);+const llmsText = makeLlmsText(variants);+const varyHeader = 'Accept, User-Agent';++const parseAcceptHeader = (acceptHeader: string): string[] => {+ return acceptHeader+ .split(',')+ .map((type) => {+ const [mediaType, ...params] = type.trim().split(';');+ const qMatch = params.find((param) => param.trim().startsWith('q='));+ const quality = qMatch ? Number.parseFloat(qMatch.split('=')[1]) : 1;+ return {mediaType: mediaType.trim(), quality};+ })+ .sort((a, b) => b.quality - a.quality)+ .map(({mediaType}) => mediaType);+};++const prefersMarkdown = (request: Request): boolean => {+ const userAgent = request.headers.get('user-agent');+ if (+ userAgent &&+ ['Claude-User', 'opencode'].some((agent) => userAgent.includes(agent))+ ) {+ return true;+ }++ const acceptHeader = request.headers.get('accept');+ if (!acceptHeader) {+ return false;+ }++ for (const type of parseAcceptHeader(acceptHeader)) {+ if (['text/markdown', 'text/x-markdown', 'text/plain'].includes(type)) {+ return true;+ }++ if (type === 'text/html' || type === '*/*') {+ return false;+ }+ }++ return false;+};++const makeMarkdownResponse = (contentType: string) => {+ return new Response(llmsText, {+ headers: {+ 'Content-Type': `${contentType}; charset=utf-8`,+ Vary: varyHeader,+ },+ });+};serve({routes: {- '/AGENTS.md': new Response(agentsMarkdown, {- headers: {- 'Content-Type': 'text/markdown; charset=utf-8',- },- }),+ '/': async (request, server) => {+ if (prefersMarkdown(request)) {+ return makeMarkdownResponse('text/markdown');+ }++ const response = await fetch(new URL('/index.html', server.url));+ response.headers.set('Vary', varyHeader);+ return response;+ },+ '/llms.txt': makeMarkdownResponse('text/plain'),// Serve index.html for all unmatched routes.'/*': index,},diff --git a/packages/remotion-media/src/agents.ts b/packages/remotion-media/src/llms.tssimilarity index 96%rename from packages/remotion-media/src/agents.tsrename to packages/remotion-media/src/llms.tsindex 7e796e06e4..b1f61786f9 100644--- a/packages/remotion-media/src/agents.ts+++ b/packages/remotion-media/src/llms.ts@@ -62,7 +62,7 @@ const formatVariant = (variant: MediaVariant) => {].join('\n');};-export const makeAgentsMarkdown = (mediaVariants: readonly MediaVariant[]) => {+export const makeLlmsText = (mediaVariants: readonly MediaVariant[]) => {const groups = new Map<string, MediaVariant[]>();for (const variant of mediaVariants) {