From b7f1abb0d079e0cebb2a1bb9ab5d8c7925003684 Mon Sep 17 00:00:00 2001 From: Christian Svensson Date: Tue, 5 Aug 2025 23:56:04 +0200 Subject: [PATCH] test(docs): type check docs code examples (#3180) This PR adds the initial seeds of type checking the code in all code blocks for the Markdown Docs. - Adds a unit test, disabled due to the many remaining errors, that can help find incorrect code - Fixes a bunch of syntax errors, type errors, and other code issues found in the docs ## Future improvements A lot of remaining issues is mostly related to missing imports, e.g. `App`, `staticFiles`, `HttpError` etc. There's a couple of different directions to solve this in future PR's. - Add explicit imports to all docs examples (may become unnecessarily verbose) - Add code to docs code blocks, but with a hint to remove it when rendering the markdown as HTML ```tsx import { App } from "fresh"; // #docs-start // Everything above marker above is trimmed away const app = new App(); ``` - Add a `types.d.ts` with "global" types used during type checking, so globals, imports and so on can be handled globally I do think that some examples probably should be more explicit with imports, but it would be overkill for a lot of places such as `app.md` and `context.md`. --- docs/canary/concepts/app.md | 8 +- docs/canary/concepts/context.md | 2 +- docs/canary/concepts/file-routing.md | 2 +- docs/canary/concepts/islands.md | 6 +- docs/canary/concepts/middleware.md | 2 +- docs/canary/concepts/routing.md | 14 +-- docs/canary/examples/migration-guide.md | 3 +- docs/canary/introduction/index.md | 4 +- docs/canary/plugins/csrf.md | 2 + docs/canary/plugins/tailwindcss.md | 2 +- docs/canary/testing/index.md | 5 +- tests/doc_examples_test.tsx | 109 ++++++++++++++++++++++++ www/utils/markdown.ts | 7 +- 13 files changed, 142 insertions(+), 24 deletions(-) create mode 100644 tests/doc_examples_test.tsx diff --git a/docs/canary/concepts/app.md b/docs/canary/concepts/app.md index 685df681..4af8f6a4 100644 --- a/docs/canary/concepts/app.md +++ b/docs/canary/concepts/app.md @@ -20,7 +20,7 @@ app.listen(); All items are applied from top to bottom. This means that when you defined a middleware _after_ a `.get()` handler, it won't be included. -```ts main.ts +```tsx main.tsx const app = new App() .use((ctx) => { // Will be called for all middlewares @@ -278,9 +278,9 @@ Setting a middleware: ```ts // top level error handler -app.onError("*", ctx => { - return new Response(String(ctx.error), { status: 500 }) -})) +app.onError("*", (ctx) => { + return new Response(String(ctx.error), { status: 500 }); +}); ``` Setting a route: diff --git a/docs/canary/concepts/context.md b/docs/canary/concepts/context.md index a7f74fba..47396661 100644 --- a/docs/canary/concepts/context.md +++ b/docs/canary/concepts/context.md @@ -28,7 +28,7 @@ app.get("/", (ctx) => { console.log("path: ", ctx.url.pathname); const hasParam = ctx.url.searchParams.has("q"); - return new Response(`Has q param: ${String(hasParam)}); + return new Response(`Has q param: ${hasParam}`); }); ``` diff --git a/docs/canary/concepts/file-routing.md b/docs/canary/concepts/file-routing.md index f34e7160..5d40b999 100644 --- a/docs/canary/concepts/file-routing.md +++ b/docs/canary/concepts/file-routing.md @@ -25,7 +25,7 @@ if (Deno.args.includes("build")) { ```ts main.ts import { App, staticFiles } from "fresh"; -const app = new App({ root: import.meta.url }) +const app = new App({ basePath: "/foo" }) .use(staticFiles()) .fsRoutes(); // This inserts all file based routes here ``` diff --git a/docs/canary/concepts/islands.md b/docs/canary/concepts/islands.md index 9157416f..0f25cb5a 100644 --- a/docs/canary/concepts/islands.md +++ b/docs/canary/concepts/islands.md @@ -29,7 +29,7 @@ An island can be used anywhere like a regular Preact component. Fresh will take care of making it interactive on the client. ```tsx main.tsx -import MyIsland from "../islands/my-island.tsx"; +import MyIsland from "./islands/my-island.tsx"; const app = new App() .get("/", (ctx) => ctx.render()); @@ -94,6 +94,10 @@ In essence, Fresh allows you to mix static and interactive parts in your app in a way that's most optimal for your app. We'll keep sending only the JavaScript that is needed for the islands to the browser. +```tsx islands/other-island.tsx +export default (props: { foo: string }) => <>{props.foo}; +``` + ```tsx route/index.tsx import MyIsland from "../islands/my-island.tsx"; import OtherIsland from "../islands/other-island.tsx"; diff --git a/docs/canary/concepts/middleware.md b/docs/canary/concepts/middleware.md index ac69235a..7253e0af 100644 --- a/docs/canary/concepts/middleware.md +++ b/docs/canary/concepts/middleware.md @@ -80,7 +80,7 @@ const middleware1 = define.middleware(async (ctx) => { return await ctx.next(); }); -const middleware1 = define.middleware(async (ctx) => { +const middleware2 = define.middleware(async (ctx) => { console.log("B"); return await ctx.next(); }); diff --git a/docs/canary/concepts/routing.md b/docs/canary/concepts/routing.md index 298c130c..da5f1850 100644 --- a/docs/canary/concepts/routing.md +++ b/docs/canary/concepts/routing.md @@ -10,21 +10,21 @@ request. const app = new App() .get("/", () => new Response("hello")) // Responds to: GET / .get("/other", () => new Response("other")) // Responds to: GET /other - .post("/upload", () => new Response("upload")); // Responds to: POST /upload + .post("/upload", () => new Response("upload")) // Responds to: POST /upload .get("/books/:id", (ctx) => { // Responds to: GET /books/my-book, /books/cool-book, etc - const id = ctx.params.id - return new Response(`Book id: ${id}`)); + const id = ctx.params.id; + return new Response(`Book id: ${id}`); }) .get("/blog/:post/comments", () => { // Responds to: GET /blog/my-post/comments, /blog/hello/comments, etc - const post = ctx.params.post - return new Response(`Blog post comments for post: ${post}`) + const post = ctx.params.post; + return new Response(`Blog post comments for post: ${post}`); }) .get("/foo/*", (ctx) => { // Responds to: GET /foo/bar, /foo/bar/baz, etc - return new Response("foo")); - }) + return new Response("foo"); + }); ``` Fresh supports the full diff --git a/docs/canary/examples/migration-guide.md b/docs/canary/examples/migration-guide.md index eae71403..c2534a3b 100644 --- a/docs/canary/examples/migration-guide.md +++ b/docs/canary/examples/migration-guide.md @@ -252,9 +252,10 @@ function testApp() { .get("/", () => new Response("hello")); // Applies build snapshot to this app instance. applySnapshot(app); + return app; } -Deno.test("My Test", () => { +Deno.test("My Test", async () => { const handler = testApp().handler(); const response = await handler(new Request("http://localhost")); diff --git a/docs/canary/introduction/index.md b/docs/canary/introduction/index.md index 314cbe9f..fd5f512b 100644 --- a/docs/canary/introduction/index.md +++ b/docs/canary/introduction/index.md @@ -13,8 +13,8 @@ web applications. import { App } from "fresh"; const app = new App() - .get("/", () => new Response("hello world")); - .get("/jsx", ctx => ctx.render(

render JSX!

)); + .get("/", () => new Response("hello world")) + .get("/jsx", (ctx) => ctx.render(

render JSX!

)); app.listen(); ``` diff --git a/docs/canary/plugins/csrf.md b/docs/canary/plugins/csrf.md index 2e289bff..c1e7ad24 100644 --- a/docs/canary/plugins/csrf.md +++ b/docs/canary/plugins/csrf.md @@ -14,6 +14,8 @@ header. to HTTP requests. These allow the server to indicate which origins from. ```ts main.ts +import { app, csrf } from "fresh"; + const app = new App(); app.use(csrf()); diff --git a/docs/canary/plugins/tailwindcss.md b/docs/canary/plugins/tailwindcss.md index f6ab2306..b9a39ac4 100644 --- a/docs/canary/plugins/tailwindcss.md +++ b/docs/canary/plugins/tailwindcss.md @@ -60,7 +60,7 @@ decided on your own when it's best to update to v4. ```ts dev.ts import { Builder } from "fresh/dev"; -import { tailwind } from "@fresh/plugin-tailwindcss-v3"; +import { tailwind } from "@fresh/plugin-tailwind-v3"; tailwind(builder, {}); ``` diff --git a/docs/canary/testing/index.md b/docs/canary/testing/index.md index 6795f46d..c87f7755 100644 --- a/docs/canary/testing/index.md +++ b/docs/canary/testing/index.md @@ -19,7 +19,7 @@ import { App } from "fresh"; const middleware = define.middleware((ctx) => { ctx.state.text = "middleware text"; - return await ctx.next(); + return ctx.next(); }); Deno.test("My middleware - sets ctx.state.text", async () => { @@ -124,9 +124,10 @@ function testApp() { // Applies build snapshot to this app instance. applySnapshot(app); + return app; } -Deno.test("My Test", () => { +Deno.test("My Test", async () => { const handler = testApp().handler(); const response = await handler(new Request("http://localhost")); diff --git a/tests/doc_examples_test.tsx b/tests/doc_examples_test.tsx new file mode 100644 index 00000000..3a963323 --- /dev/null +++ b/tests/doc_examples_test.tsx @@ -0,0 +1,109 @@ +import twDenoJson from "../plugin-tailwindcss/deno.json" with { type: "json" }; +import * as Marked from "marked"; +import { ensureDir, walk } from "@std/fs"; +import { dirname, join, relative } from "@std/path"; +// import { expect } from "@std/expect/expect"; +import { withTmpDir } from "../src/test_utils.ts"; +import { FRESH_VERSION, PREACT_VERSION } from "../update/src/update.ts"; + +Deno.test("Docs Code example checks", async () => { + await using tmp = await withTmpDir(); + + for await (const { path, code } of docsMarkdownFiles()) { + const codePath = join(tmp.dir, path); + await ensureDir(dirname(codePath)); + await Deno.writeTextFile(codePath, code); + } + + const denoJson = { + lock: false, + imports: { + fresh: `jsr:@fresh/core@${FRESH_VERSION}`, + "@fresh/plugin-tailwind-v3": + `jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`, + "@fresh/plugin-tailwind": + `jsr:@fresh/plugin-tailwind@^${twDenoJson.version}`, + preact: `npm:preact@^${PREACT_VERSION}`, + "@deno/gfm": "jsr:@deno/gfm@^0.11.0", + "@std/expect": "jsr:@std/expect@^1.0.16", + }, + compilerOptions: { + lib: ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"], + jsx: "precompile", + jsxImportSource: "preact", + jsxPrecompileSkipElements: ["a", "img", "source", "body", "html", "head"], + }, + }; + await Deno.writeTextFile( + join(tmp.dir, "deno.json"), + JSON.stringify(denoJson, undefined, 2), + ); + + // Download and cache all dependencies (reduces `stdout` noise) + await new Deno.Command(Deno.execPath(), { + args: ["cache", "**/*"], + cwd: tmp.dir, + }).output(); + + const { stdout, stderr } = await new Deno.Command(Deno.execPath(), { + args: ["check", "**/*"], + cwd: tmp.dir, + }).output(); + + const decoder = new TextDecoder(); + const output = `${decoder.decode(stdout)}\n${decoder.decode(stderr)}`; + // Log `deno check` output (can be removed if expects below are enabled) + // deno-lint-ignore no-console + console.log(output); + + // TODO: Enable after fixing docs check issues + // expect(code).toBe(0); + // expect(output).toBe(""); +}); + +async function* docsMarkdownFiles() { + // Limit to checking Fresh v2 (canary) docs for now + const docsDir = join(import.meta.dirname!, "..", "docs", "canary"); + const docsIter = walk(docsDir, { exts: [".md"], includeDirs: false }); + + for await (const entry of docsIter) { + for (const { file, code } of await extractTsCode(entry.path)) { + const path = join(relative(docsDir, entry.path), file); + yield { path, code }; + } + } +} + +async function extractTsCode(path: string) { + const code: { file: string; code: string }[] = []; + const input = await Deno.readTextFile(path); + let index = 0; + + const tokens = await Marked.lexer(input, { gfm: true, async: true }); + + Marked.walkTokens(tokens, (token) => { + // Get rid of `Marked.Tokens.Generic` + const t = token as Marked.MarkedToken; + if (t.type !== "code") return; + + const result = /^([tj]sx?)\s*/.exec(t.lang ?? ""); + if (!result) return; + + // Codeblock must be TS/JS + index += 1; + + // Probably a filename, but perhaps a title, + // so get rid of non-file safe characters + const [match, ext] = result; + let file = t.lang!.slice(match.length) + .toLocaleLowerCase() + .replaceAll(/[^a-z0-9._\-\/\\]/g, "_") + .replaceAll(/_{2,}/g, "_") || String(index); + + if (!file.endsWith(ext)) file += `.${ext}`; + + code.push({ file, code: t.text }); + }); + + return code; +} diff --git a/www/utils/markdown.ts b/www/utils/markdown.ts index 9caede9a..d5553a34 100644 --- a/www/utils/markdown.ts +++ b/www/utils/markdown.ts @@ -235,15 +235,16 @@ export function renderMarkdown( opts: MarkdownOptions = {}, ): { headings: MarkdownHeading[]; html: string } { const renderer = new DefaultRenderer(); - const markedOpts: Marked.MarkedOptions = { + const markedOpts: Marked.MarkedOptions & { async: false } = { gfm: true, + async: false, renderer, }; try { const html = opts.inline - ? Marked.parseInline(input, markedOpts) as string - : Marked.parse(input, markedOpts) as string; + ? Marked.parseInline(input, markedOpts) + : Marked.parse(input, markedOpts); return { headings: renderer.headings, html }; } catch (err) {