Skip to content

Commit 7fad1ae

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
feat(docs): MDX components in gated docs
Mono-RevId: 979595aa8dbdd4b59da4be68720b749563a050b3
1 parent 872ce43 commit 7fad1ae

15 files changed

Lines changed: 334 additions & 212 deletions

File tree

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
import { gatedNav, gatedPage, gatedSection } from "@/lib/gated";
1+
import { gatedNav } from "@/lib/gated";
22
import { requestGrant, verifyGrant } from "@/lib/gated-grant";
33

4-
// Gated docs for a reader whose grant (from the dashboard's /resources/docs/me) carries the flag:
5-
// GET /api/gated/nav the gated pages the grant opens, for the sidebar
6-
// GET /api/gated/page/<slug...> a gated page's title, description and HTML
7-
// GET /api/gated/section/<id> a gated section's HTML
8-
// A page or section the grant doesn't open answers like one that doesn't exist.
4+
// The gated pages a reader's grant (from the dashboard's /resources/docs/me) opens, for the sidebar:
5+
// GET /api/gated/nav [{ url, title, after }]
6+
// Page and section bodies come from the loadGated server action (lib/gated-action.tsx).
97

108
export const dynamic = "force-dynamic";
119

@@ -21,14 +19,8 @@ export async function GET(request: Request, { params }: { params: Promise<{ path
2119
const grant = verifyGrant(requestGrant(request), process.env.DOCS_GRANT_PUBLIC_KEY);
2220
if (!grant) return json({ error: "No valid grant" }, 401);
2321

24-
const [kind, ...rest] = (await params).path;
25-
const body =
26-
kind === "nav" && rest.length === 0
27-
? gatedNav(grant.flags)
28-
: kind === "page"
29-
? await gatedPage(rest.join("/"), grant.flags)
30-
: kind === "section" && rest.length === 1
31-
? await gatedSection(rest[0]!, grant.flags)
32-
: null;
33-
return body ? json(body) : json({ error: "Not found" }, 404);
22+
const path = (await params).path;
23+
return path.length === 1 && path[0] === "nav"
24+
? json(gatedNav(grant.flags))
25+
: json({ error: "Not found" }, 404);
3426
}

‎apps/docs/components/gated.tsx‎

Lines changed: 64 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,44 +9,76 @@ import {
99
type CSSProperties,
1010
type ReactNode,
1111
} from "react";
12-
import { usePathname } from "next/navigation";
12+
import { unstable_isUnrecognizedActionError, usePathname } from "next/navigation";
1313
import { DocsLayout } from "fumadocs-ui/layouts/notebook";
1414
import { DocsBody, DocsDescription, DocsPage, DocsTitle } from "fumadocs-ui/layouts/notebook/page";
1515
import { EmbedFrame } from "@/components/embed";
1616
import { gatedPageView, withGatedPages, withGatedTabs, type GatedNavItem } from "@/lib/gated-view";
17-
import { fetchGated, hasSignedInHint, useReader } from "@/lib/reader";
17+
import { loadGated } from "@/lib/gated-action";
18+
import { fetchGated, hasSignedInHint, useReader, withGrant } from "@/lib/reader";
1819

19-
// Gated docs in the browser (lib/gated-content.ts): fetched from /api/gated with the reader's
20-
// grant after the page loads, so the static HTML, and everyone without the flag, never has them.
21-
// The HTML comes from our own MDX, compiled by lib/rehype-gated.ts with components refused.
20+
// Gated docs in the browser (lib/gated-content.ts), asked for with the reader's grant after the
21+
// page loads, so the static HTML, and everyone without the flag, never has them: the sidebar entries
22+
// from /api/gated/nav, page and section bodies from the loadGated server action, rendered on the
23+
// server with the public pages' MDX components.
2224

23-
type GatedPageData = { title: string; description: string | null; html: string };
25+
type Loaded = Exclude<Awaited<ReturnType<typeof loadGated>>, "refused" | null>;
26+
type GatedSection = Pick<Loaded, "body">;
27+
type GatedPageData = Extract<Loaded, { title: string }>;
2428

25-
/** The gated response at `path` for this reader: undefined until it answers, null if it found nothing. */
26-
function useGated<T>(path: string): T | null | undefined {
29+
/** Gives up on a slow answer, as fetchGated does, so a page shows its 404 instead of a skeleton. */
30+
const within10s = <T,>(p: Promise<T>) =>
31+
Promise.race([p, new Promise<null>((done) => setTimeout(() => done(null), 10_000))]);
32+
33+
function ask(kind: "nav" | "page" | "section", id: string): Promise<unknown> {
34+
if (kind === "nav") return fetchGated("nav").then((res) => (res?.ok ? res.json() : null));
35+
return within10s(
36+
withGrant(
37+
(grant) => loadGated(grant, kind, id),
38+
(a) => a === "refused"
39+
)
40+
).then((a) => (a === "refused" ? null : a), reloadIfRedeployed);
41+
}
42+
43+
const RELOADED = "trigger-docs:reloaded";
44+
45+
/** A deploy since this page loaded retires its action ids. Reload into the new build, keeping the
46+
* skeleton meanwhile; at most once a minute, so a rollout serving both builds can't loop. */
47+
function reloadIfRedeployed(error: unknown): Promise<never> {
48+
if (unstable_isUnrecognizedActionError(error)) {
49+
try {
50+
if (Date.now() - Number(sessionStorage.getItem(RELOADED)) > 60_000) {
51+
sessionStorage.setItem(RELOADED, String(Date.now()));
52+
location.reload();
53+
return new Promise(() => {});
54+
}
55+
} catch {}
56+
}
57+
return Promise.reject(error);
58+
}
59+
60+
/** The gated answer for this reader: undefined until it comes, null if it found nothing. */
61+
function useGated<T>(kind: "nav" | "page" | "section", id = ""): T | null | undefined {
2762
const reader = useReader();
2863
const flags = reader.kind === "signed-in" ? reader.docsFlags.join() : "";
29-
const key = `${flags} ${path}`;
64+
const key = `${flags} ${kind} ${id}`;
3065
const [got, setGot] = useState<{ key: string; data: T | null }>();
3166
useEffect(() => {
3267
if (!flags) return;
3368
let live = true;
34-
fetchGated(path)
35-
.then((res) => (res?.ok ? (res.json() as Promise<T>) : null))
69+
ask(kind, id)
3670
.catch(() => null)
37-
.then((data) => live && setGot({ key, data }));
71+
.then((data) => live && setGot({ key, data: data as T | null }));
3872
return () => {
3973
live = false;
4074
};
41-
}, [path, flags, key]);
75+
}, [kind, id, flags, key]);
4276
// Keyed, so another URL or reader never shows the last answer while its own loads.
4377
return got?.key === key ? got.data : undefined;
4478
}
4579

46-
const Html = ({ html }: { html: string }) => <div dangerouslySetInnerHTML={{ __html: html }} />;
47-
48-
// Gated MDX can't use components, so the site marks it as a private beta here, in the callout
49-
// "tip" tone (app/global.css), and authors never write the note themselves.
80+
// The site marks gated content as a private beta here, in the callout "tip" tone (app/global.css),
81+
// and authors never write the note themselves.
5082
const tone = {
5183
"--tone": "var(--callout-tip)",
5284
"--tint": "var(--callout-tip-tint)",
@@ -71,7 +103,7 @@ function PrivateBetaBadge() {
71103

72104
/** `<Gated id="..." />` in a page: the section's content for readers whose flags open it. */
73105
export function Gated({ id }: { id: string }) {
74-
const section = useGated<{ html: string }>(`section/${encodeURIComponent(id)}`);
106+
const section = useGated<GatedSection>("section", id);
75107
if (!section) return null;
76108
return (
77109
<section
@@ -83,7 +115,7 @@ export function Gated({ id }: { id: string }) {
83115
<PrivateBetaBadge />
84116
</div>
85117
<div className="px-4 [&>div>:first-child]:mt-4 [&>div>:last-child]:mb-4">
86-
<Html html={section.html} />
118+
<div>{section.body}</div>
87119
</div>
88120
</section>
89121
);
@@ -102,10 +134,19 @@ export function GatedDocsLayout(props: ComponentProps<typeof DocsLayout>) {
102134

103135
const noSubscribe = () => () => {};
104136

137+
const decodePath = (p: string) => {
138+
try {
139+
return decodeURIComponent(p);
140+
} catch {
141+
return p; // a malformed escape can't name a gated page; it stays a 404
142+
}
143+
};
144+
105145
function useGatedPage() {
106146
const reader = useReader();
107147
const path = usePathname().replace(/^\/embed(?=\/)/, "");
108-
const page = useGated<GatedPageData>(`page${path}`);
148+
// usePathname keeps percent escapes; gated pages are keyed by their file names.
149+
const page = useGated<GatedPageData>("page", decodePath(path.slice(1)));
109150
const hint = useSyncExternalStore(
110151
noSubscribe,
111152
() => hasSignedInHint(document.cookie),
@@ -141,7 +182,7 @@ export function GatedPageOr({ children }: { children: ReactNode }) {
141182
const { view, page } = useGatedPage();
142183
if (view === "404") return children;
143184
return (
144-
<DocsPage toc={[]}>
185+
<DocsPage toc={page?.toc ?? []}>
145186
{page ? (
146187
<>
147188
<header className="flex flex-col gap-2 border-b pb-6">
@@ -151,9 +192,7 @@ export function GatedPageOr({ children }: { children: ReactNode }) {
151192
)}
152193
<PrivateBetaBadge />
153194
</header>
154-
<DocsBody>
155-
<Html html={page.html} />
156-
</DocsBody>
195+
<DocsBody>{page.body}</DocsBody>
157196
</>
158197
) : (
159198
<Skeleton />
@@ -184,9 +223,7 @@ export function EmbedGatedPageOr({ title, children }: { title: string; children:
184223
)}
185224
<PrivateBetaBadge />
186225
</header>
187-
<DocsBody>
188-
<Html html={page.html} />
189-
</DocsBody>
226+
<DocsBody>{page.body}</DocsBody>
190227
</>
191228
) : (
192229
<Skeleton />

‎apps/docs/lib/gated-action.tsx‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"use server";
2+
3+
import { getMDXComponents } from "@/components/mdx";
4+
import { gatedEntry } from "./gated";
5+
import { verifyGrant } from "./gated-grant";
6+
7+
// Gated pages and sections, rendered per request as React Server Components with the same MDX
8+
// components as public pages. The browser calls this with the reader's grant (components/gated.tsx);
9+
// interactive components hydrate from client code the public pages already load. A server action
10+
// is a POST, so no CDN or browser caches its answer, and Next sends it with `Cache-Control: no-store`.
11+
12+
/**
13+
* A gated page (`kind: "page"`, `id` its slug) or section (`id` from `<Gated id>`) the grant opens:
14+
* its rendered body, plus the title, description and TOC for a page. "refused" for a grant that
15+
* fails verification (the caller renews it once); null for content it doesn't open, the same as
16+
* content that doesn't exist.
17+
*/
18+
export async function loadGated(grant: unknown, kind: unknown, id: unknown) {
19+
// Arguments come from the browser as is.
20+
if (typeof grant !== "string") return "refused" as const;
21+
const claims = verifyGrant(grant, process.env.DOCS_GRANT_PUBLIC_KEY);
22+
if (!claims) return "refused" as const;
23+
if ((kind !== "page" && kind !== "section") || typeof id !== "string") return null;
24+
const entry = await gatedEntry(kind, id, claims.flags);
25+
if (!entry) return null;
26+
const body = <entry.body components={getMDXComponents()} />;
27+
return kind === "section"
28+
? { body }
29+
: { title: entry.title, description: entry.description, toc: entry.toc, body };
30+
}

‎apps/docs/lib/gated-grant.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { isDocsFlag, type DocsFlag } from "./gated-flags.ts";
44
// The grant the dashboard's `/resources/docs/me` gives a reader whose orgs have docs flags on:
55
// `<payload>.<signature>`, both base64url, the signature Ed25519 over the payload. The webapp signs
66
// it with DOCS_GRANT_PRIVATE_KEY (docsGrant in apps/webapp/app/services/docsReader.server.ts);
7-
// /api/gated verifies it with DOCS_GRANT_PUBLIC_KEY, so the docs site can't mint one. Keys are
7+
// the docs site verifies it with DOCS_GRANT_PUBLIC_KEY, so it can't mint one. Keys are
88
// base64 DER: PKCS#8 for the private key, SPKI for the public one.
99

1010
export type GatedGrant = { userId: string; flags: DocsFlag[]; exp: number };

‎apps/docs/lib/gated.test.ts‎

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { frontmatter, prepareGatedContent } from "./gated-content.ts";
1010
import { DOCS_FLAGS } from "./gated-flags.ts";
1111
import { requestGrant, signGrant, verifyGrant } from "./gated-grant.ts";
1212
import { checkPublicPage, gatedSlots } from "./gated-slots.ts";
13-
import { rehypeGated } from "./rehype-gated.ts";
13+
import { rehypeGated, remarkGated } from "./rehype-gated.ts";
1414
import { remarkNpmTabs } from "./remark-npm-tabs.ts";
1515

1616
// Base64 DER, as DOCS_GRANT_PRIVATE_KEY and DOCS_GRANT_PUBLIC_KEY hold them.
@@ -277,49 +277,69 @@ describe("prepareGatedContent", () => {
277277
});
278278
});
279279

280-
describe("rehypeGated", () => {
280+
describe("gated MDX", () => {
281281
const el = (tagName: string, properties = {}, children: Element["children"] = []): Element => ({
282282
type: "element",
283283
tagName,
284284
properties,
285285
children,
286286
});
287-
const run = (children: Root["children"], file = "/app/.generated/gated/sections/ab12.mdx") => {
287+
const gatedFile = "/app/.generated/gated/sections/ab12.mdx";
288+
const run = (children: Root["children"], file = gatedFile) => {
288289
const tree: Root = { type: "root", children };
289290
rehypeGated()(tree, new VFile({ path: file }));
290291
return tree;
291292
};
293+
const jsx = (name: string) => ({ type: "mdxJsxFlowElement", name, attributes: [], children: [] });
292294

293-
it("exports the body as html, with links under the base path", () => {
294-
const tree = run([
295-
el("h2", { id: "setup" }, [{ type: "text", value: "Setup" }]),
296-
el("p", {}, [el("a", { href: "/queues" }, [{ type: "text", value: "queues" }])]),
297-
]);
298-
const esm = tree.children.at(-1) as unknown as {
299-
data: {
300-
estree: { body: { declaration: { declarations: { init: { value: string } }[] } }[] };
301-
};
302-
};
303-
const html = esm.data.estree.body[0]!.declaration.declarations[0]!.init.value;
304-
expect(html).toBe('<h2 id="setup">Setup</h2><p><a href="/docs/queues">queues</a></p>');
295+
// Catches: media in gated content, which the build would publish in public/, and a nested slot.
296+
it("refuses images, videos, iframes and <Gated>", () => {
297+
for (const node of [
298+
el("img", { src: "/x.png" }),
299+
jsx("img"),
300+
jsx("video"),
301+
el("source"),
302+
jsx("iframe"),
303+
jsx("Gated"),
304+
{ ...jsx("Card"), attributes: [{ type: "mdxJsxAttribute", name: "img", value: "/x.png" }] },
305+
])
306+
expect(() => run([node as never])).toThrow(/Gated content can't hold/);
307+
expect(() => run([jsx("Card") as never])).not.toThrow();
305308
});
306309

307-
// Catches: a component or image in gated content, which would need public assets or code.
308-
it("refuses components, expressions, images and type hovers", () => {
309-
const jsx = { type: "mdxJsxFlowElement", name: "Callout", attributes: [], children: [] };
310-
const expr = { type: "mdxFlowExpression", value: "1" };
311-
for (const node of [jsx, expr, el("img", { src: "/x.png" }), el("Popup")])
312-
expect(() => run([node as never])).toThrow(/plain MDX only/);
310+
// Catches: type hovers in gated code, which would be published under /hovers.
311+
it("turns type hovers off for every gated code block", () => {
312+
const code = (lang: string, meta?: string) => ({
313+
type: "code" as const,
314+
lang,
315+
meta,
316+
value: "",
317+
});
318+
const tree: MdRoot = {
319+
type: "root",
320+
children: [code("ts"), code("typescript"), code("tsx", 'title="a.tsx"'), code("bash")],
321+
};
322+
remarkGated()(tree, new VFile({ path: gatedFile }));
323+
expect(tree.children.map((c) => (c as { meta?: string }).meta)).toEqual([
324+
"no-twoslash",
325+
"no-twoslash",
326+
'title="a.tsx" no-twoslash',
327+
"no-twoslash",
328+
]);
329+
const pub: MdRoot = { type: "root", children: [code("ts")] };
330+
remarkGated()(pub, new VFile({ path: "/repo/docs/queues.mdx" }));
331+
expect((pub.children[0] as { meta?: string }).meta).toBeUndefined();
313332
});
314333

315-
// Catches: a plain npm fence turned into a <CodeGroup>, which gated content refuses.
316-
it("keeps npm fences in gated content as plain code", () => {
334+
// Catches: npm fences in gated content left as one plain block instead of package manager tabs.
335+
it("turns npm fences into package manager tabs", () => {
317336
const tree: MdRoot = {
318337
type: "root",
319338
children: [{ type: "code", lang: "bash", value: "npm i -D @trigger.dev/build" }],
320339
};
321-
remarkNpmTabs()(tree, new VFile({ path: "/app/.generated/gated/sections/ab12.mdx" }));
322-
expect(tree.children[0]!.type).toBe("code");
340+
// With a gated file, as unified passes it: the plugin used to skip gated files.
341+
(remarkNpmTabs() as (tree: MdRoot, file: VFile) => void)(tree, new VFile({ path: gatedFile }));
342+
expect((tree.children[0] as { name?: string }).name).toBe("CodeGroup");
323343
});
324344

325345
it("leaves public pages alone", () => {

0 commit comments

Comments
 (0)