Skip to content
Myr

pipeline.ts

This file

Path

apps/web/src/features/markdown/pipeline.ts

215 lines · 5.9 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

line 1why, one step back
1/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 2–8why, one step back
2 * The order is the security property: 1. `remarkGfm`; 2. `rehypeRaw`, so
3 * everything after sees the README's own HTML; 3. `rehypeRepoUrls`, before the4 * sanitizer judges the URLs; 4. `rehypeFootnoteIds`, dropping remark-rehype's5 * `user-content-` prefix, which the sanitizer adds next; 5. `rehypeSanitize`6 * with `schema`, the last gate (no script, handler, `javascript:` or `data:`7 * URL, iframe, style or form; every `id` and `name` prefixed, so a README8 * cannot clobber the page's globals); 6. `rehypeSlug`, after the sanitizer, so

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 9–11why, one step back
9 * `#usage` finds `## Usage` unprefixed; 7. `rehypeFragmentLinks`, once
10 * every id is final; 8. `rehypeShiftHeadings`, a README's only, which moves no11 * id or URL. react-markdown's `defaultUrlTransform` stays on as a second net.

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 12–30why, one step back
12 */
13import { Predicate } from "effect";14import type { Element, Properties, Root } from "hast";15import type { Options } from "react-markdown";16import rehypeRaw from "rehype-raw";17import rehypeSanitize, { defaultSchema } from "rehype-sanitize";18import type { Options as Schema } from "rehype-sanitize";19import rehypeSlug from "rehype-slug";20import remarkGfm from "remark-gfm";21import { visit } from "unist-util-visit";2223import { resolveRepoUrl } from "./resolve.ts";24import type { RepoUrlContext } from "./resolve.ts";2526export type PluggableList = NonNullable<Options["rehypePlugins"]>;2728export type MarkdownAt = Omit<RepoUrlContext, "kind">;2930/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 31–33why, one step back
31 * A code block's `language-…` class is kept, and a `style` element is dropped
32 * with its CSS (the default drops only a `script` whole, so a style's rules33 * would show as text).

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 34–36why, one step back
34 */
35export const schema: Schema = {36 ...defaultSchema,

Close the code browser and drafting wave: its decisions in two ADRs, every rule it added held, and its leftovers folded inoscabrielbefore adoption009640c

line 37why, one step back
37 strip: [...(defaultSchema.strip ?? []), "style"],

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 38–80why, one step back
38 attributes: {
39 ...defaultSchema.attributes,40 code: [41 ...(defaultSchema.attributes?.code ?? []),42 ["className", /^language-./u],43 ],44 },45};4647const media = new Set(["img", "source", "video"]);4849const candidate = (value: string, at: RepoUrlContext) => {50 const [url = "", ...descriptor] = value.trim().split(/\s+/u);5152 return [resolveRepoUrl(url, at), ...descriptor].join(" ");53};5455const rewrite = (56 properties: Properties,57 key: "href" | "src" | "srcSet",58 to: (value: string) => string59) => {60 const value = properties[key];6162 if (Predicate.isString(value)) {63 properties[key] = to(value);64 }65};6667const resolveElement = (node: Element, at: MarkdownAt) => {68 if (node.tagName === "a") {69 rewrite(node.properties, "href", (href) =>70 resolveRepoUrl(href, { ...at, kind: "link" })71 );72 }7374 if (!media.has(node.tagName)) {75 return;76 }7778 const here = { ...at, kind: "media" } as const;7980 rewrite(node.properties, "src", (src) => resolveRepoUrl(src, here));

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 81–82why, one step back
81 // rehype-raw keeps `srcset` as written: one string, candidates split by
82 // commas.

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 83–96why, one step back
83 rewrite(node.properties, "srcSet", (srcSet) =>
84 srcSet85 .split(",")86 .map((value) => candidate(value, here))87 .join(", ")88 );89};9091export const rehypeRepoUrls = (at: MarkdownAt) => (tree: Root) => {92 visit(tree, "element", (node) => {93 resolveElement(node, at);94 });95};96

Merge build/1005oscabrielbefore adoptionb124cbb

lines 97–112why, one step back
97const CLOBBER = schema.clobberPrefix ?? "user-content-";
9899const unprefixed = (value: string, lead = "") =>100 value.startsWith(`${lead}${CLOBBER}`)101 ? `${lead}${value.slice(lead.length + CLOBBER.length)}`102 : value;103104const unprefix = (properties: Properties, key: "href" | "id", lead = "") => {105 const value = properties[key];106107 if (Predicate.isString(value)) {108 properties[key] = unprefixed(value, lead);109 }110};111112/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 113–114why, one step back
113 * So the sanitizer's prefix is their only one; twice made
114 * `user-content-user-content-fn-1`.

Merge build/1005oscabrielbefore adoptionb124cbb

lines 115–143why, one step back
115 */
116export const rehypeFootnoteIds = () => (tree: Root) => {117 visit(tree, "element", (node, _index, parent) => {118 const { properties } = node;119120 if (node.tagName === "a" && properties.dataFootnoteRef !== undefined) {121 unprefix(properties, "id");122 unprefix(properties, "href", "#");123 }124125 if (node.tagName === "a" && properties.dataFootnoteBackref !== undefined) {126 unprefix(properties, "href", "#");127 }128129 if (130 node.tagName === "ol" &&131 parent?.type === "element" &&132 parent.properties.dataFootnotes !== undefined133 ) {134 for (const item of node.children) {135 if (item.type === "element" && item.tagName === "li") {136 unprefix(item.properties, "id");137 }138 }139 }140 });141};142143/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 144–145why, one step back
144 * As GitHub's page script does: a link to `#x` where the file has no `x` but
145 * has `user-content-x` points there.

Merge build/1005oscabrielbefore adoptionb124cbb

lines 146–180why, one step back
146 */
147export const rehypeFragmentLinks = () => (tree: Root) => {148 const ids = new Set<string>();149150 visit(tree, "element", (node) => {151 const { id, name } = node.properties;152153 if (Predicate.isString(id)) {154 ids.add(id);155 }156157 if (node.tagName === "a" && Predicate.isString(name)) {158 ids.add(name);159 }160 });161162 visit(tree, "element", (node) => {163 const { href } = node.properties;164165 if (node.tagName !== "a" || !Predicate.isString(href)) {166 return;167 }168169 if (!href.startsWith("#")) {170 return;171 }172173 const target = href.slice(1);174175 if (!ids.has(target) && ids.has(`${CLOBBER}${target}`)) {176 node.properties.href = `#${CLOBBER}${target}`;177 }178 });179};180

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 181–198why, one step back
181const SHIFTED = new Map([
182 ["h1", "h2"],183 ["h2", "h3"],184 ["h3", "h4"],185 ["h4", "h5"],186 ["h5", "h6"],187]);188189/**190 * A README sits under the page's own h1 (the project's name), so its headings191 * go down a level: its `# name` reads as an h2, and an h6 stays an h6.192 */193export const rehypeShiftHeadings = () => (tree: Root) => {194 visit(tree, "element", (node) => {195 node.tagName = SHIFTED.get(node.tagName) ?? node.tagName;196 });197};198

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 199–203why, one step back
199export const remarkPlugins: PluggableList = [remarkGfm];
200201export const rehypePluginsFor = (at: MarkdownAt): PluggableList => [202 rehypeRaw,203 [rehypeRepoUrls, at],

Merge build/1005oscabrielbefore adoptionb124cbb

line 204why, one step back
204 rehypeFootnoteIds,

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 205–206why, one step back
205 [rehypeSanitize, schema],
206 rehypeSlug,

Merge build/1005oscabrielbefore adoptionb124cbb

line 207why, one step back
207 rehypeFragmentLinks,

Merge redesign into mainoscabrielbefore adoptioncaedd21

line 208why, one step back
208 rehypeShiftHeadings,

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

line 209why, one step back
209];

Merge build/1313-docs into mainoscabrielbefore adoption9000f4e

lines 210–215why, one step back
210
211export const sitePlugins: PluggableList = [212 [rehypeSanitize, schema],213 rehypeSlug,214 rehypeFragmentLinks,215];