Skip to content

Commit 6cddd1a

Browse files
feat(lint): warn when a url() in a linked stylesheet does not resolve beside it (#6844)
* feat(lint): warn when a url() in a linked stylesheet does not resolve beside it * fix(lint): a percent-encoded url() in a linked stylesheet resolves like the browser does
1 parent 4da50e2 commit 6cddd1a

3 files changed

Lines changed: 139 additions & 1 deletion

File tree

‎docs/reference/lint-rules.mdx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,12 @@ Source: the project lint pass in `packages/lint/src/project.ts`, `packages/lint/
907907

908908
**Fix:** Add the missing mask file(s) to the project, or update the `mask-image` URL.
909909

910+
### `missing_stylesheet_asset`
911+
912+
**Warning.** A `url()` in a linked local stylesheet does not resolve beside that stylesheet. Browsers resolve `url()` from the stylesheet's own folder, so the font or image 404s and the render falls back silently. When the file exists in a parent folder, the fix hint names the working path.
913+
914+
**Fix:** Change the `url()` to be relative to the stylesheet (for example `../assets/fonts/x.ttf` from `styles/main.css`), or add the file.
915+
910916
### `inaccessible_media_url`
911917

912918
**Error.** A remote media URL did not answer a `HEAD` request with a 2xx status (or the request failed or timed out), so the media cannot load. Reported only by the async `lintMediaUrls()` export of `@hyperframes/lint`; `hyperframes lint` and `hyperframes check` do not run it.

‎packages/lint/src/project.test.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
22
import { ChildProcess, execFile } from "node:child_process";
33
import { mkdirSync, mkdtempSync, writeFileSync, rmSync, symlinkSync } from "node:fs";
4-
import { join } from "node:path";
4+
import { dirname, join } from "node:path";
55
import { tmpdir } from "node:os";
66
import type { HyperframeLintFinding } from "./types.js";
77
import { lintProject } from "./project.js";
@@ -399,6 +399,71 @@ describe("missing_or_empty_sub_composition", () => {
399399
});
400400
});
401401

402+
describe("missing_stylesheet_asset", () => {
403+
const lintLinked = async (css: string, files: Record<string, string> = {}) => {
404+
const project = makeProject(
405+
validHtml().replace(
406+
"<body>",
407+
'<head><link rel="stylesheet" href="styles/main.css"></head><body>',
408+
),
409+
);
410+
mkdirSync(join(project, "styles"), { recursive: true });
411+
writeFileSync(join(project, "styles/main.css"), css);
412+
for (const [name, body] of Object.entries(files)) {
413+
mkdirSync(dirname(join(project, name)), { recursive: true });
414+
writeFileSync(join(project, name), body);
415+
}
416+
const { results } = await lintProject(project);
417+
return results
418+
.flatMap((entry) => entry.result.findings)
419+
.filter((finding) => finding.code === "missing_stylesheet_asset");
420+
};
421+
422+
it("names the path that exists when a url() is relative to the wrong folder", async () => {
423+
const findings = await lintLinked('@font-face{font-family:X;src:url("assets/fonts/x.ttf")}', {
424+
"assets/fonts/x.ttf": "font",
425+
});
426+
427+
expect(findings).toHaveLength(1);
428+
expect(findings[0]).toMatchObject({ severity: "warning" });
429+
expect(findings[0]?.message).toContain("assets/fonts/x.ttf");
430+
expect(findings[0]?.fixHint).toContain("../assets/fonts/x.ttf");
431+
});
432+
433+
it("hints the encoded url when the encoded file is in a parent folder", async () => {
434+
const findings = await lintLinked('@font-face{src:url("fonts/Open%20Sans.ttf")}', {
435+
"fonts/Open Sans.ttf": "font",
436+
});
437+
438+
expect(findings).toHaveLength(1);
439+
expect(findings[0]?.fixHint).toContain("../fonts/Open%20Sans.ttf");
440+
});
441+
442+
it("asks for the file when it exists nowhere", async () => {
443+
const findings = await lintLinked(".a{background:url(nope.png)}");
444+
445+
expect(findings).toHaveLength(1);
446+
expect(findings[0]?.fixHint).toContain("Add");
447+
});
448+
449+
it("stays quiet for urls that resolve beside the stylesheet, remote, data and placeholder urls", async () => {
450+
const css = [
451+
'@font-face{src:url("../assets/fonts/x.ttf")}',
452+
".a{background:url(img/a.png)} .b{background:url(https://cdn.example/b.png)}",
453+
".c{background:url(data:image/png;base64,AAAA)} .d{background:url(#frag)}",
454+
".e{background:url(${asset})}",
455+
'@font-face{src:url("fonts/Open%20Sans.ttf")}',
456+
].join("\n");
457+
const findings = await lintLinked(css, {
458+
"assets/fonts/x.ttf": "font",
459+
"styles/img/a.png": "png",
460+
"styles/fonts/Open Sans.ttf": "font",
461+
});
462+
463+
expect(findings).toEqual([]);
464+
});
465+
});
466+
402467
describe("texture_mask_asset_not_found declarations", () => {
403468
it("still reports a missing inline mask beside a malformed declaration", async () => {
404469
const project = makeProject(

‎packages/lint/src/project.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,7 @@ export async function lintProject(
329329
...lintAudioSrcNotFound(projectDir, allHtmlSources),
330330
...lintMissingLocalAsset(projectDir, allHtmlSources),
331331
...lintTextureMaskAssetNotFound(projectDir, allHtmlSources),
332+
...lintLinkedStylesheetAssets(projectDir, allHtmlSources),
332333
...(!entryFile ? lintMultipleRootCompositions(projectDir) : []),
333334
...(!entryFile ? lintBlankRootWithStandaloneComposition(rootHtml, allHtmlSources) : []),
334335
...lintDuplicateAudioTracks(projectDir, rootHtml),
@@ -624,6 +625,72 @@ function lintTextureMaskAssetNotFound(
624625
});
625626
}
626627

628+
function nearestAncestorMatch(projectDir: string, cssRootRelativePath: string, url: string) {
629+
const root = resolve(projectDir);
630+
for (let dir = resolve(root, dirname(cssRootRelativePath), ".."); ; dir = dirname(dir)) {
631+
if (!isWithinProjectRoot(projectDir, dir)) return null;
632+
if (resolveLocalAssetCandidates(projectDir, relative(root, join(dir, url))).some(existsSync)) {
633+
return relative(dirname(resolve(root, cssRootRelativePath)), join(dir, url)).replace(
634+
/\\/g,
635+
"/",
636+
);
637+
}
638+
if (dir === root) return null;
639+
}
640+
}
641+
642+
function lintLinkedStylesheetAssets(
643+
projectDir: string,
644+
htmlSources: HtmlSource[],
645+
): HyperframeLintFinding[] {
646+
const seen = new Set<string>();
647+
const findings: HyperframeLintFinding[] = [];
648+
for (const { html, compSrcPath } of htmlSources) {
649+
for (const { content, rootRelativePath } of collectLocalStylesheets(
650+
projectDir,
651+
parseHTML(html).document,
652+
compSrcPath,
653+
)) {
654+
let root: postcss.Root;
655+
try {
656+
root = postcss.parse(content);
657+
} catch (error) {
658+
if (!(error instanceof postcss.CssSyntaxError)) throw error;
659+
continue;
660+
}
661+
root.walkDecls((declaration) => {
662+
if (/^(?:-webkit-)?mask-image$/i.test(declaration.prop)) return;
663+
for (const match of declaration.value.matchAll(CSS_URL_RE)) {
664+
const rawUrl = match[1] ?? match[2] ?? match[3] ?? "";
665+
if (isUnresolvedAssetPlaceholder(rawUrl)) continue;
666+
const url = cleanAssetUrl(rawUrl);
667+
if (!url || isRemoteOrInlineUrl(url) || url.startsWith("/")) continue;
668+
if (
669+
resolveCssAssetCandidates(projectDir, url, undefined, rootRelativePath).some(existsSync)
670+
)
671+
continue;
672+
const key = `${rootRelativePath}\0${url}`;
673+
if (seen.has(key)) continue;
674+
seen.add(key);
675+
const found = nearestAncestorMatch(projectDir, rootRelativePath, url);
676+
findings.push({
677+
code: "missing_stylesheet_asset",
678+
severity: "warning",
679+
file: join(projectDir, rootRelativePath),
680+
message:
681+
`${rootRelativePath} references url(${url}), which is not found beside the stylesheet ` +
682+
`(looked in ${dirname(rootRelativePath)}/). The browser resolves url() from the stylesheet, so the file will 404.`,
683+
fixHint: found
684+
? `A file exists at "${found}" relative to the stylesheet. Change the url() to that path.`
685+
: `Add "${url}" beside the stylesheet, or point the url() at an existing file.`,
686+
});
687+
}
688+
});
689+
}
690+
}
691+
return findings;
692+
}
693+
627694
function lintMultipleRootCompositions(projectDir: string): HyperframeLintFinding[] {
628695
const findings: HyperframeLintFinding[] = [];
629696
try {

0 commit comments

Comments
 (0)