Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 35 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
50 changes: 50 additions & 0 deletions src/__tests__/issue.351.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, it, expect } from 'vitest';

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is copied from #352 to prevent regressions

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',
]);
});
});
});
144 changes: 53 additions & 91 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -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[];
Expand All @@ -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;
Expand Down
Loading