Skip to content

Commit c4f55aa

Browse files
committed
fix(audits): recognize default-as next/script imports and skip MDX code examples
1 parent 3eb8131 commit c4f55aa

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

‎scripts/check-source-text.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,12 @@ const EXECUTABLE_SCRIPT_TYPES = new Set([
5555
'text/partytown',
5656
])
5757

58-
const NEXT_SCRIPT_IMPORT = /import\s+(\w+)\s*(?:,\s*\{[^}]*\}\s*)?from\s*['"]next\/script['"]/
58+
/** `import Script from 'next/script'` (optionally with named imports) or `import { default as Script }`. */
59+
const NEXT_SCRIPT_IMPORT =
60+
/import\s+(?:(\w+)\s*(?:,\s*\{[^}]*\}\s*)?|\{[^}]*\bdefault\s+as\s+(\w+)[^}]*\}\s*)from\s*['"]next\/script['"]/
61+
62+
/** MDX fenced and inline code, which a docs page displays rather than renders. */
63+
const MDX_CODE = /```[\s\S]*?```|`[^`\n]*`/g
5964
/** The start of the element's own `type` prop — not a suffix like `data-type`. */
6065
const TYPE_PROP = /(?:^|\s)type\s*=\s*/
6166
/** A statically known `type` value right after {@link TYPE_PROP}. */
@@ -78,7 +83,8 @@ function openingTagAttributes(source: string, start: number): string {
7883
* from an expression fails closed: the audit cannot prove it executable.
7984
*/
8085
function findDataNextScripts(source: string): number[] {
81-
const localName = NEXT_SCRIPT_IMPORT.exec(source)?.[1]
86+
const importMatch = NEXT_SCRIPT_IMPORT.exec(source)
87+
const localName = importMatch?.[1] ?? importMatch?.[2]
8288
if (!localName) return []
8389
const lines: number[] = []
8490
for (const match of source.matchAll(new RegExp(`<${localName}\\b`, 'g'))) {
@@ -117,7 +123,10 @@ for (const file of files) {
117123
const bytes = await source.bytes()
118124
if (bytes.includes(0)) nulOffenders.push(file)
119125
if (file.startsWith('apps/') && /\.(?:[jt]sx|mdx)$/.test(file)) {
120-
const text = new TextDecoder().decode(bytes)
126+
const decoded = new TextDecoder().decode(bytes)
127+
const text = file.endsWith('.mdx')
128+
? decoded.replace(MDX_CODE, (code) => code.replace(/[^\n]/g, ' '))
129+
: decoded
121130
if (!text.includes('next/script')) continue
122131
for (const line of findDataNextScripts(text)) dataScriptOffenders.push(`${file}:${line}`)
123132
}

0 commit comments

Comments
 (0)