markedjs/marked

Error in rewriting custom code function

jiaopengzi opened this issue · 2 comments

Hello

Problem Reproduction

ENV

PS C:\Desktop> node -v
v20.15.1

"marked": "^13.0.2"

Setp

Step 1: Initialize the projec

mkdir marked-code-test
cd marked-code-test
npm init -y
npm install --save-dev typescript
npx tsc --init
npm install --save-dev jest ts-jest @types/jest
npm install marked@latest -P

Step 2: Create a jest.config.js file and input the following content:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

Step 4: Create a __test__ directory for the test code, navigate into the directory and create the test code main.test.ts.

mkdir __test__
/**
 * @FilePath     : \test-marked\__tests__\main.test.ts
 * @Description  : Testing the use of the 'code' function rewrite in the 'marked' library
 */
import { Marked, type Tokens } from 'marked'

const renderer = {
  // Rewrite of the 'code' function using the original 'code' function from the source code
  code({ text, lang, escaped }: Tokens.Code): string {
    const langString = (lang || '').match(/^\S*/)?.[0]

    const code = text.replace(/\n$/, '') + '\n'

    if (!langString) {
      return (
        '<pre><code>' +
        (escaped ? code : escape(code, true)) +
        '</code></pre>\n'
      )
    }

    return (
      '<pre><code class="language-' +
      escape(langString) +
      '">' +
      (escaped ? code : escape(code, true)) +
      '</code></pre>\n'
    )
  },
}

// =============================================== Copy of content from the 'marked' source code begins here

/**
 * Helpers
 */
const escapeTest = /[&<>"']/
const escapeReplace = new RegExp(escapeTest.source, 'g')
const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/
const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g')
const escapeReplacements: { [index: string]: string } = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
}
const getEscapeReplacement = (ch: string) => escapeReplacements[ch]

export function escape(html: string, encode?: boolean) {
  if (encode) {
    if (escapeTest.test(html)) {
      return html.replace(escapeReplace, getEscapeReplacement)
    }
  } else {
    if (escapeTestNoEncode.test(html)) {
      return html.replace(escapeReplaceNoEncode, getEscapeReplacement)
    }
  }

  return html
}
// =============================================== Copy of content from the 'marked' source code ends here

// Create a factory function to generate new instances of 'Marked'
const createMarked = () => {
  const marked = new Marked()

  // For business reasons, the 'code' function is overwritten to achieve custom code block rendering
  // If the custom 'renderer' 'code' function is used, an error will occur
  // After commenting out 'use', the error will not occur
  // Any help would be appreciated. Thank you.

  //   marked.use({
  //     renderer: renderer,
  //   })

  return marked
}

// Test code
test('marked test', () => {
  // Define a string of code blocks
  const codeStr = `
\`\`\`js
console.log('hello world')
\`\`\`
`

  const htmlStr = createMarked().parse(codeStr).toString()
  console.log(htmlStr)
})

Step 5: Run npx jest.

image

image

Why am I still getting an error even when using the code function from the source code?

Thank you very much

try

marked.use({
  useNewRenderer: true,
  renderer: renderer,
});

The new renderer style is an opt-in for v13 with useNewRenderer. in v14 the new renderers will be used by default.

try

marked.use({
  useNewRenderer: true,
  renderer: renderer,
});

The new renderer style is an opt-in for v13 with useNewRenderer. in v14 the new renderers will be used by default.

nice,it working now, thanks.