### Enable Math with Rehype Katex Source: https://unifiedjs.com/explore/package/rehype-sanitize This example shows how to enable math rendering using rehype-katex by allowing specific classes for math content. It demonstrates the initial setup before sanitization. ```javascript import rehypeKatex from 'rehype-katex' import rehypeParse from 'rehype-parse' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeKatex) .use(rehypeSanitize) .use(rehypeStringify) .process('L') console.log(String(file)) ``` -------------------------------- ### Using rehype-sanitize Source: https://unifiedjs.com/explore/package/rehype-sanitize This example demonstrates how to use rehype-sanitize in a unified pipeline to parse, sanitize, and stringify HTML content. It shows the import statements, the unified process, and the expected output after sanitization. ```APIDOC ## Use rehype-sanitize This example shows how to integrate `rehype-sanitize` into a `unified` processing pipeline. ### Example Code ```javascript import rehypeParse from 'rehype-parse' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {read} from 'to-vfile' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize) .use(rehypeStringify) .process(await read('index.html')) console.log(String(file)) ``` ### Input HTML (`index.html`) ```html
delta
``` ### Expected Output ```html
delta
``` ``` -------------------------------- ### Enable Math with Rehype Katex (Sanitized) Source: https://unifiedjs.com/explore/package/rehype-sanitize This example demonstrates a safer approach to enabling math rendering by sanitizing HTML first, allowing only necessary classes for rehype-katex. This configuration is recommended for security. ```javascript import rehypeKatex from 'rehype-katex' import rehypeParse from 'rehype-parse' import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize, { ...defaultSchema, attributes: { ...defaultSchema.attributes, // The `language-*` regex is allowed by default. code: [['className', /^language-./, 'math-inline', 'math-display']] } }) .use(rehypeKatex) .use(rehypeStringify) .process('L') ``` -------------------------------- ### Enable Syntax Highlighting with Rehype Highlight Source: https://unifiedjs.com/explore/package/rehype-sanitize This example shows how to enable syntax highlighting with rehype-highlight by configuring rehype-sanitize to allow specific classes for code blocks. Highlighting is applied after sanitization. ```javascript import rehypeHighlight from 'rehype-highlight' import rehypeParse from 'rehype-parse' import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize, { ...defaultSchema, attributes: { ...defaultSchema.attributes, code: [ ...(defaultSchema.attributes.code || []), // List of all allowed languages: ['className', 'language-js', 'language-css', 'language-md'] ] } }) .use(rehypeHighlight, {subset: false}) .use(rehypeStringify) .process('
console.log(1)
') console.log(String(file)) ``` -------------------------------- ### Enable Syntax Highlighting Safely with Rehype Highlight Source: https://unifiedjs.com/explore/package/rehype-sanitize This example demonstrates a safer method for syntax highlighting by allowing all token classes used by rehype-highlight. Sanitization is configured to permit these specific classes on span elements. ```javascript const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeHighlight, {subset: false}) .use(rehypeSanitize, { ...defaultSchema, attributes: { ...defaultSchema.attributes, span: [ ...(defaultSchema.attributes.span || []), // List of all allowed tokens: ['className', 'hljs-addition', 'hljs-attr', 'hljs-attribute', 'hljs-built_in', 'hljs-bullet', 'hljs-char', 'hljs-code', 'hljs-comment', 'hljs-deletion', 'hljs-doctag', 'hljs-emphasis', 'hljs-formula', 'hljs-keyword', 'hljs-link', 'hljs-literal', 'hljs-meta', 'hljs-name', 'hljs-number', 'hljs-operator', 'hljs-params', 'hljs-property', 'hljs-punctuation', 'hljs-quote', 'hljs-regexp', 'hljs-section', 'hljs-selector-attr', 'hljs-selector-class', 'hljs-selector-id', 'hljs-selector-pseudo', 'hljs-selector-tag', 'hljs-string', 'hljs-strong', 'hljs-subst', 'hljs-symbol', 'hljs-tag', 'hljs-template-tag', 'hljs-template-variable', 'hljs-title', 'hljs-type', 'hljs-variable' ] } }) .use(rehypeStringify) .process('
console.log(1)
') ``` -------------------------------- ### Install rehype-sanitize with npm Source: https://unifiedjs.com/explore/package/rehype-sanitize Install the rehype-sanitize package using npm. This package is ESM only and requires Node.js version 16 or later. ```bash npm install rehype-sanitize ``` -------------------------------- ### Sanitize HTML with rehype-Sanitize Source: https://unifiedjs.com/explore/package/rehype-sanitize This example demonstrates how to use rehype-sanitize to process an HTML file. It parses the HTML, sanitizes it according to the default schema, and then stringifies it back to HTML. This is useful for cleaning user-provided HTML to prevent security vulnerabilities. ```html
delta
``` ```javascript import rehypeParse from 'rehype-parse' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {read} from 'to-vfile' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize) .use(rehypeStringify) .process(await read('index.html')) console.log(String(file)) ``` ```html
delta
``` -------------------------------- ### Import rehype-sanitize in Browsers Source: https://unifiedjs.com/explore/package/rehype-sanitize Import the rehype-sanitize package in the browser using esm.sh with the ?bundle flag for packaging. ```javascript ``` -------------------------------- ### unified().use(rehypeSanitize[, schema]) Source: https://unifiedjs.com/explore/package/rehype-sanitize This is the primary way to use the rehype-sanitize plugin with a unified processor. You can optionally provide a custom schema to configure the sanitization rules. ```APIDOC ## unified().use(rehypeSanitize[, schema]) ### Description Use the rehype-sanitize plugin with a unified processor to sanitize HTML. An optional schema can be passed to configure the sanitization rules. ### Method ``` unified().use(rehypeSanitize[, schema]) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import {unified} from 'unified' import rehypeSanitize from 'rehype-sanitize' const processor = unified().use(rehypeSanitize) ``` ### Response This method configures the unified processor. The result of the processing (e.g., HTML string) would be the response. #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Import rehype-sanitize in Deno Source: https://unifiedjs.com/explore/package/rehype-sanitize Import the rehype-sanitize package in Deno using esm.sh. Ensure you are using a compatible version. ```typescript import rehypeSanitize from 'https://esm.sh/rehype-sanitize@6' ``` -------------------------------- ### Options Source: https://unifiedjs.com/explore/package/rehype-sanitize Options that can be passed to the rehype-sanitize plugin to customize its behavior. These options typically relate to the sanitization schema. ```APIDOC ## Options ### Description Options can be passed to the `rehypeSanitize` plugin to customize the sanitization process. These options primarily relate to configuring the sanitization schema. ### Usage Pass an options object as the second argument to `unified().use(rehypeSanitize, options)`. ```javascript import rehypeSanitize from 'rehype-sanitize' import {unified} from 'unified' const customSchema = { allowElement: [ 'a', { 'h1': [ 'id' ] } ] } const processor = unified().use(rehypeSanitize, customSchema) ``` ### Available Options - **schema** (object): An object that defines the sanitization rules. This can be the `defaultSchema` or a custom schema object. The structure of the schema object is detailed in the `hast-util-sanitize` documentation. It typically includes rules for allowed elements and attributes. ``` -------------------------------- ### Sanitize HTML with rehype-sanitize Source: https://unifiedjs.com/explore/package/rehype-sanitize This code snippet shows how to add `rehype-sanitize` to a `unified` pipeline to sanitize HTML, specifically prefixing `id` and `name` attributes to prevent DOM clobbering. ```javascript /** * @typedef {import('hast').Root} Root */ import fs from 'node:fs/promises' import rehypeParse from 'rehype-parse' import rehypeStringify from 'rehype-stringify' import rehypeSanitize from 'rehype-sanitize' import {unified} from 'unified' const browser = String(await fs.readFile('browser.js')) const document = `

Current

${`

${'Lorem ipsum dolor sit amet. '.repeat(20)}

\n`.repeat(20)}

Link to current, link to old.` const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize) .use(function () { /** * @param {Root} tree */ return function (tree) { tree.children.push({ type: 'element', tagName: 'script', properties: {type: 'module'}, children: [{type: 'text', value: browser}] }) } }) .use(rehypeStringify) .process(document) await fs.writeFile('output.html', String(file)) ``` -------------------------------- ### Log current global variable Source: https://unifiedjs.com/explore/package/rehype-sanitize This snippet logs the value of the `current` global variable to the console. It's used to demonstrate DOM clobbering. ```javascript console.log(current) ``` -------------------------------- ### rehypeSanitize API Source: https://unifiedjs.com/explore/package/rehype-sanitize Details on the main export and configuration options for rehype-sanitize. ```APIDOC ## API This package exports the identifier `defaultSchema`. The default export is `rehypeSanitize`. ### `defaultSchema` Default schema (`Options`). Follows GitHub style sanitation. ### `unified().use(rehypeSanitize[, schema])` Sanitize HTML. #### Parameters * `options` (`Options`, optional) — configuration #### Returns Transform (`Transformer`). ### `Options` Schema that defines what nodes and properties are allowed (TypeScript type). This option is a bit advanced as it requires knowledge of syntax trees, so see the docs for `Schema` in `hast-util-sanitize`. ``` -------------------------------- ### Process HTML with rehype to inline script Source: https://unifiedjs.com/explore/package/rehype-sanitize This code processes an HTML string, parses it, injects a script tag containing browser-side JavaScript, and then stringifies the result. It's used to create an HTML file that demonstrates DOM clobbering. ```javascript /** * @typedef {import('hast').Root} Root */ import fs from 'node:fs/promises' import rehypeParse from 'rehype-parse' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const browser = String(await fs.readFile('browser.js')) const document = `

Current

${`

${'Lorem ipsum dolor sit amet. '.repeat(20)}

\n`.repeat(20)}

Link to current, link to old.` const file = await unified() .use(rehypeParse, {fragment: true}) .use(function () { /** * @param {Root} tree */ return function (tree) { tree.children.push({ type: 'element', tagName: 'script', properties: {type: 'module'}, children: [{type: 'text', value: browser}] }) } }) .use(rehypeStringify) .process(document) await fs.writeFile('output.html', String(file)) ``` -------------------------------- ### Fix broken links after sanitization Source: https://unifiedjs.com/explore/package/rehype-sanitize This browser-side JavaScript handles `hashchange` and `click` events to ensure that links to sanitized IDs (prefixed with 'user-content-') still work correctly by scrolling to the target element. ```javascript /// /* eslint-env browser */ // Page load (you could wrap this in a DOM ready if the script is loaded early). hashchange() // When URL changes. window.addEventListener('hashchange', hashchange) // When on the URL already, perhaps after scrolling, and clicking again, which // doesn’t emit `hashchange`. document.addEventListener( 'click', function (event) { if ( event.target && event.target instanceof HTMLAnchorElement && event.target.href === location.href && location.hash.length > 1 ) { setImmediate(function () { if (!event.defaultPrevented) { hashchange() } }) } }, false ) function hashchange() { /** @type {string | undefined} */ let hash try { hash = decodeURIComponent(location.hash.slice(1)).toLowerCase() } catch { return } const name = 'user-content-' + hash const target = document.getElementById(name) || document.getElementsByName(name)[0] if (target) { setImmediate(function () { target.scrollIntoView() }) } } ``` -------------------------------- ### defaultSchema Source: https://unifiedjs.com/explore/package/rehype-sanitize The default schema used by rehype-sanitize, which is based on how github.com sanitizes HTML. This schema defines allowed elements, attributes, and their properties. ```APIDOC ## defaultSchema ### Description The default schema for rehype-sanitize. This schema defines the allowed HTML elements, attributes, and their properties, mirroring the sanitization rules of github.com. ### Usage This schema can be passed as an argument to the `rehypeSanitize` plugin to customize sanitization. ```javascript import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' import {unified} from 'unified' // Using the default schema (implicitly) const processor1 = unified().use(rehypeSanitize) // Explicitly using the default schema const processor2 = unified().use(rehypeSanitize, defaultSchema) ``` ### Schema Structure (Conceptual) The schema is an object that typically includes: - `allowElement`: A function or object defining which elements are allowed. - `allowAttribute`: A function or object defining which attributes are allowed on elements. - `strip`: A function or object defining how to handle disallowed content. (Note: The exact structure of `defaultSchema` is complex and detailed in the underlying `hast-util-sanitize` library.) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.