Skip to content
Merged
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
6 changes: 6 additions & 0 deletions docs/reference/lint-rules.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -907,6 +907,12 @@ Source: the project lint pass in `packages/lint/src/project.ts`, `packages/lint/

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

### `missing_stylesheet_asset`

**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.

**Fix:** Change the `url()` to be relative to the stylesheet (for example `../assets/fonts/x.ttf` from `styles/main.css`), or add the file.

### `inaccessible_media_url`

**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.
Expand Down
67 changes: 66 additions & 1 deletion packages/lint/src/project.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { ChildProcess, execFile } from "node:child_process";
import { mkdirSync, mkdtempSync, writeFileSync, rmSync, symlinkSync } from "node:fs";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
import type { HyperframeLintFinding } from "./types.js";
import { lintProject } from "./project.js";
Expand Down Expand Up @@ -399,6 +399,71 @@ describe("missing_or_empty_sub_composition", () => {
});
});

describe("missing_stylesheet_asset", () => {
const lintLinked = async (css: string, files: Record<string, string> = {}) => {
const project = makeProject(
validHtml().replace(
"<body>",
'<head><link rel="stylesheet" href="styles/main.css"></head><body>',
),
);
mkdirSync(join(project, "styles"), { recursive: true });
writeFileSync(join(project, "styles/main.css"), css);
for (const [name, body] of Object.entries(files)) {
mkdirSync(dirname(join(project, name)), { recursive: true });
writeFileSync(join(project, name), body);
}
const { results } = await lintProject(project);
return results
.flatMap((entry) => entry.result.findings)
.filter((finding) => finding.code === "missing_stylesheet_asset");
};

it("names the path that exists when a url() is relative to the wrong folder", async () => {
const findings = await lintLinked('@font-face{font-family:X;src:url("assets/fonts/x.ttf")}', {
"assets/fonts/x.ttf": "font",
});

expect(findings).toHaveLength(1);
expect(findings[0]).toMatchObject({ severity: "warning" });
expect(findings[0]?.message).toContain("assets/fonts/x.ttf");
expect(findings[0]?.fixHint).toContain("../assets/fonts/x.ttf");
});

it("hints the encoded url when the encoded file is in a parent folder", async () => {
const findings = await lintLinked('@font-face{src:url("fonts/Open%20Sans.ttf")}', {
"fonts/Open Sans.ttf": "font",
});

expect(findings).toHaveLength(1);
expect(findings[0]?.fixHint).toContain("../fonts/Open%20Sans.ttf");
});

it("asks for the file when it exists nowhere", async () => {
const findings = await lintLinked(".a{background:url(nope.png)}");

expect(findings).toHaveLength(1);
expect(findings[0]?.fixHint).toContain("Add");
});

it("stays quiet for urls that resolve beside the stylesheet, remote, data and placeholder urls", async () => {
const css = [
'@font-face{src:url("../assets/fonts/x.ttf")}',
".a{background:url(img/a.png)} .b{background:url(https://cdn.example/b.png)}",
".c{background:url(data:image/png;base64,AAAA)} .d{background:url(#frag)}",
".e{background:url(${asset})}",
'@font-face{src:url("fonts/Open%20Sans.ttf")}',
].join("\n");
const findings = await lintLinked(css, {
"assets/fonts/x.ttf": "font",
"styles/img/a.png": "png",
"styles/fonts/Open Sans.ttf": "font",
});

expect(findings).toEqual([]);
});
});

describe("texture_mask_asset_not_found declarations", () => {
it("still reports a missing inline mask beside a malformed declaration", async () => {
const project = makeProject(
Expand Down
67 changes: 67 additions & 0 deletions packages/lint/src/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ export async function lintProject(
...lintAudioSrcNotFound(projectDir, allHtmlSources),
...lintMissingLocalAsset(projectDir, allHtmlSources),
...lintTextureMaskAssetNotFound(projectDir, allHtmlSources),
...lintLinkedStylesheetAssets(projectDir, allHtmlSources),
...(!entryFile ? lintMultipleRootCompositions(projectDir) : []),
...(!entryFile ? lintBlankRootWithStandaloneComposition(rootHtml, allHtmlSources) : []),
...lintDuplicateAudioTracks(projectDir, rootHtml),
Expand Down Expand Up @@ -624,6 +625,72 @@ function lintTextureMaskAssetNotFound(
});
}

function nearestAncestorMatch(projectDir: string, cssRootRelativePath: string, url: string) {
const root = resolve(projectDir);
for (let dir = resolve(root, dirname(cssRootRelativePath), ".."); ; dir = dirname(dir)) {
if (!isWithinProjectRoot(projectDir, dir)) return null;
if (resolveLocalAssetCandidates(projectDir, relative(root, join(dir, url))).some(existsSync)) {
return relative(dirname(resolve(root, cssRootRelativePath)), join(dir, url)).replace(
/\\/g,
"/",
);
}
if (dir === root) return null;
}
}

function lintLinkedStylesheetAssets(
projectDir: string,
htmlSources: HtmlSource[],
): HyperframeLintFinding[] {
const seen = new Set<string>();
const findings: HyperframeLintFinding[] = [];
for (const { html, compSrcPath } of htmlSources) {
for (const { content, rootRelativePath } of collectLocalStylesheets(
projectDir,
parseHTML(html).document,
compSrcPath,
)) {
let root: postcss.Root;
try {
root = postcss.parse(content);
} catch (error) {
if (!(error instanceof postcss.CssSyntaxError)) throw error;
continue;
}
root.walkDecls((declaration) => {
if (/^(?:-webkit-)?mask-image$/i.test(declaration.prop)) return;
for (const match of declaration.value.matchAll(CSS_URL_RE)) {
const rawUrl = match[1] ?? match[2] ?? match[3] ?? "";
if (isUnresolvedAssetPlaceholder(rawUrl)) continue;
const url = cleanAssetUrl(rawUrl);
if (!url || isRemoteOrInlineUrl(url) || url.startsWith("/")) continue;
if (
resolveCssAssetCandidates(projectDir, url, undefined, rootRelativePath).some(existsSync)
)
continue;
const key = `${rootRelativePath}\0${url}`;
if (seen.has(key)) continue;
seen.add(key);
const found = nearestAncestorMatch(projectDir, rootRelativePath, url);
findings.push({
code: "missing_stylesheet_asset",
severity: "warning",
file: join(projectDir, rootRelativePath),
message:
`${rootRelativePath} references url(${url}), which is not found beside the stylesheet ` +
`(looked in ${dirname(rootRelativePath)}/). The browser resolves url() from the stylesheet, so the file will 404.`,
fixHint: found
? `A file exists at "${found}" relative to the stylesheet. Change the url() to that path.`
: `Add "${url}" beside the stylesheet, or point the url() at an existing file.`,
});
}
});
}
}
return findings;
}

function lintMultipleRootCompositions(projectDir: string): HyperframeLintFinding[] {
const findings: HyperframeLintFinding[] = [];
try {
Expand Down
Loading