diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index b60116f..c1930f0 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -26,7 +26,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [20, 22, 24, 26] + node-version: [22, 24, 26] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/package-lock.json b/package-lock.json index f1de936..d2edf35 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,10 @@ "license": "MIT", "dependencies": { "is-url-superb": "^4.0.0", - "postcss-values-parser": "^6.0.2" + "postcss-values-parser": "^8.0.0" }, "devDependencies": { + "@types/css-tree": "^3.2.0", "@types/node": "^20.19.43", "@vitest/coverage-v8": "^4.1.12", "lint-staged": "^17.6.0", @@ -23,7 +24,7 @@ "vitest": "^4.1.12" }, "engines": { - "node": ">=20.19.0 || >=22.12.0" + "node": ">=22.12.0" }, "peerDependencies": { "postcss": "^8.4.47" @@ -415,6 +416,13 @@ "assertion-error": "^2.0.1" } }, + "node_modules/@types/css-tree": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@types/css-tree/-/css-tree-3.2.0.tgz", + "integrity": "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -661,6 +669,19 @@ "dev": true, "license": "MIT" }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1154,6 +1175,12 @@ "node": ">=10" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "license": "CC0-1.0" + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", @@ -1258,20 +1285,21 @@ } }, "node_modules/postcss-values-parser": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/postcss-values-parser/-/postcss-values-parser-6.0.2.tgz", - "integrity": "sha512-YLJpK0N1brcNJrs9WatuJFtHaV9q5aAOj+S4DI5S7jgHlRfm0PIbDCAFRYMQD5SHq7Fy6xsDhyutgS0QOAs0qw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/postcss-values-parser/-/postcss-values-parser-8.0.0.tgz", + "integrity": "sha512-gPdtA/H7HgRThMg+QoXJ1EX0EX7zrVF7c3062jaHB4HijLg11QqC2hz9h/nUCZ6O/FljJ+qj2fUvAF2FWhVjFg==", "license": "MPL-2.0", "dependencies": { "color-name": "^1.1.4", + "css-tree": "^3.1.0", "is-url-superb": "^4.0.0", "quote-unquote": "^1.0.0" }, "engines": { - "node": ">=10" + "node": ">=22.0.0" }, "peerDependencies": { - "postcss": "^8.2.9" + "postcss": "^8.4.14" } }, "node_modules/prettier": { diff --git a/package.json b/package.json index 97b48b0..66c4697 100644 --- a/package.json +++ b/package.json @@ -25,16 +25,17 @@ "!**/__tests__/**" ], "engines": { - "node": ">=20.19.0 || >=22.12.0" + "node": ">=22.12.0" }, "peerDependencies": { "postcss": "^8.4.47" }, "dependencies": { "is-url-superb": "^4.0.0", - "postcss-values-parser": "^6.0.2" + "postcss-values-parser": "^8.0.0" }, "devDependencies": { + "@types/css-tree": "^3.2.0", "@types/node": "^20.19.43", "@vitest/coverage-v8": "^4.1.12", "lint-staged": "^17.6.0", diff --git a/src/__tests__/issue.351.spec.ts b/src/__tests__/issue.351.spec.ts new file mode 100644 index 0000000..207e0a5 --- /dev/null +++ b/src/__tests__/issue.351.spec.ts @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest'; +import detective from '../index.js'; + +describe('issue 351: unquoted data: URLs', () => { + describe('declaration ({ url: true })', () => { + const dataDecl = + '.icon { background: url(data:image/png;base64,iVBORw0KGgo=) no-repeat; }'; + const fileDecl = '.logo { background: url(logo.png); }'; + + it('ignores the data URL', () => { + expect(detective(dataDecl, { url: true })).toStrictEqual([]); + }); + + it('still finds the file URL next to a data URL', () => { + expect(detective(`${dataDecl} ${fileDecl}`, { url: true })).toStrictEqual( + ['logo.png'], + ); + }); + }); + + describe('@value (default)', () => { + const dataValue = '@value icon: url(data:image/png;base64,iVBORw0KGgo=);'; + const fileValue = '@value primary from "colors.css";'; + + it('ignores the data URL', () => { + expect(detective(dataValue)).toStrictEqual([]); + }); + + it('still finds the file import next to a data URL', () => { + expect(detective(`${dataValue}\n${fileValue}`)).toStrictEqual([ + 'colors.css', + ]); + }); + }); + + describe('@import (default)', () => { + const dataImport = '@import url(data:text/css;base64,LmF7fQ==);'; + const fileImport = '@import "b.css";'; + + it('ignores the data URL', () => { + expect(detective(dataImport)).toStrictEqual([]); + }); + + it('still finds the file import next to a data URL', () => { + expect(detective(`${dataImport}\n${fileImport}`)).toStrictEqual([ + 'b.css', + ]); + }); + }); +}); diff --git a/src/index.ts b/src/index.ts index 02bc7c1..99eeb76 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,11 @@ import { debuglog } from 'node:util'; import isUrl from 'is-url-superb'; -import { parse, type AtRule, type Root } from 'postcss'; +import { list, parse, type Root } from 'postcss'; import { parse as postCssParseValue, - type ChildNode, - type Func, - type Word, - type Numeric, - type Operator, - type Punctuation, - type Quoted, + Quoted, + Word, + type Node, } from 'postcss-values-parser'; const debug = debuglog('detective-postcss'); @@ -31,48 +27,33 @@ function detective(src: string, options: Options = {}): string[] { const references: string[] = []; - root.walkAtRules((rule) => { - let file = null; - - if (isImportRule(rule)) { - const firstNode = postCssParseValue(rule.params).first; - if (firstNode) { - file = getValueOrUrl(firstNode); - if (file) { - debug('found %s of %s', '@import', file); - } - } + root.walkAtRules(/^(import|value)$/, (rule) => { + // at-rule params aren't plain values (media queries, layer(), + // `name: value`), so only parse the component holding the reference: + // the first one for @import, the last one for @value + const parts = list.space(rule.params); + const isImport = rule.name === 'import'; + const part = isImport ? parts[0] : parts.at(-1); + const nodes = part ? parseValue(part) : []; + const node = isImport ? nodes[0] : nodes.at(-1); + if (!node) return; + + const isReference = + isImport || parts.at(-2) === 'from' || (options.url && isUrlNode(node)); + const file = isReference ? getValueOrUrl(node) : undefined; + + if (file) { + debug('found %s of %s', `@${rule.name}`, file); + references.push(file); } - - if (isValueRule(rule)) { - const lastNode = postCssParseValue(rule.params).last; - if (!lastNode) return; - - const prevNode = lastNode.prev(); - - if (prevNode && isFrom(prevNode)) { - file = getValueOrUrl(lastNode); - if (file) { - debug('found %s of %s', '@value with import', file); - } - } - - if (options.url && isUrlNode(lastNode)) { - file = getValueOrUrl(lastNode); - if (file) { - debug('found %s of %s', 'url() in @value', file); - } - } - } - - if (file) references.push(file); }); if (!options.url) return references; root.walkDecls((decl) => { - const { nodes } = postCssParseValue(decl.value); - const files = nodes + if (!/url\(/i.test(decl.value)) return; + + const files = parseValue(decl.value) .filter((node) => isUrlNode(node)) .map((node) => getValueOrUrl(node)) .filter(Boolean) as string[]; @@ -87,60 +68,41 @@ function detective(src: string, options: Options = {}): string[] { return references; } -function getValueOrUrl(node: ChildNode): string | undefined { - const ret = isUrlNode(node) ? getUrlContent(node) : getValue(node); - - // is-url-superb uses new URL() which doesn't accept protocol-relative URLs; - // prepend http: so they get correctly identified and filtered out - return isUrl(ret.startsWith('//') ? `http:${ret}` : ret) ? undefined : ret; -} - -function getUrlContent(urlNode: Func): string { - const first = urlNode.nodes[0]; - - // Quoted: url('foo.css') or url("foo.css") - if (first && first.type === 'quoted') { - return first.contents; +function parseValue(value: string): Node[] { + try { + return postCssParseValue(value).nodes as unknown as Node[]; + } catch { + throw new MalformedCssError(); } - - // Unquoted: reconstruct the full string from all child nodes (handles - // absolute URLs like url(https://...) which parse as multiple tokens) - return urlNode.nodes - .filter((n) => isNodeWithValue(n)) - .map((n) => getValue(n)) - .join(''); } -function getValue(node: ChildNode) { - if (!isNodeWithValue(node)) { - throw new Error('Unexpectedly found a node without a value'); +function getValueOrUrl(node: Node): string | undefined { + // url() nodes are Word nodes holding the url's contents + let ret: string; + if (node instanceof Quoted) { + ret = node.contents; + } else if (node instanceof Word) { + ret = node.value; + } else { + return undefined; } - return node.type === 'quoted' ? node.contents : node.value; -} - -function isNodeWithValue( - node: ChildNode, -): node is Word | Numeric | Operator | Punctuation | Quoted { - return ['word', 'numeric', 'operator', 'punctuation', 'quoted'].includes( - node.type, - ); -} - -function isUrlNode(node: ChildNode): node is Func { - return node.type === 'func' && node.name === 'url'; -} - -function isValueRule(rule: AtRule) { - return rule.name === 'value'; -} - -function isImportRule(rule: AtRule) { - return rule.name === 'import'; + // is-url-superb uses new URL() which doesn't accept protocol-relative URLs; + // prepend http: so they get correctly identified and filtered out + return isUrl(ret.startsWith('//') ? `http:${ret}` : ret) ? undefined : ret; } -function isFrom(node: ChildNode): node is Word { - return node.type === 'word' && node.value === 'from'; +/** + * postcss-values-parser turns url() into a Word node holding just the url's + * contents, so the only way to tell it apart from a plain word is to look at + * the source text it was parsed from. + */ +function isUrlNode(node: Node): boolean { + if (!(node instanceof Word) || !node.source?.input) return false; + + const { input, start, end } = node.source; + const sourceText = input.css.slice(start?.offset, end?.offset); + return /^url\(/i.test(sourceText); } detective.MalformedCssError = MalformedCssError;