Repository navigation
feat(vite): dev-time overlay handle (@svelte-vitals/vite/hooks) #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
59b9ecb
feat(vite): add pure dev-report formatter and dedup signature
oekazuma 4216285
feat(vite): add svelteVitalsHandle dev-time SvelteKit handle (@svelte…
oekazuma 6310819
docs: document the dev-time overlay handle (@svelte-vitals/vite/hooks)
oekazuma 3c7c36e
chore: changeset for the dev-time overlay handle
oekazuma f14abdb
style: apply prettier to dev-format test
oekazuma a8ab418
fix(vite): mark @sveltejs/kit as an optional peer dependency
oekazuma afa9256
fix(vite): include detection presence/value in dev dedup signature
oekazuma 144624d
fix(vite): guard dev handle against undefined process on edge runtimes
oekazuma f4ae518
refactor(vite): gate dev handle with esm-env and run analysis off the…
oekazuma 3f88baf
test(vite): cover dev-handle option plumbing and debug hatch; documen…
oekazuma File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@svelte-vitals/vite': minor | ||
| --- | ||
|
|
||
| Add a dev-time SvelteKit handle, `svelteVitalsHandle` (exported from `@svelte-vitals/vite/hooks`). Added to `src/hooks.server.ts`, it analyzes each visited page's rendered `<head>` in dev and prints SEO warnings for the current route to the terminal — request-driven, dev-only, and never mutates the response. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import { isPenalized, effectiveSeverity, type Config, type Result, type Severity } from '@svelte-vitals/core'; | ||
|
|
||
| const GLYPH: Record<Severity, string> = { critical: '✗', warning: '⚠', info: '·' }; | ||
| const RANK: Record<Severity, number> = { critical: 0, warning: 1, info: 2 }; | ||
|
|
||
| function penalized(results: Result[], config: Config): Result[] { | ||
| return results.filter((r) => isPenalized(r.detection, config.treatDynamicAs)); | ||
| } | ||
|
|
||
| /** Compact terminal report for one route's penalized findings; '' when the route is clean. */ | ||
| export function formatDevReport(route: string, results: Result[], config: Config): string { | ||
| const failing = penalized(results, config).sort( | ||
| (a, b) => RANK[effectiveSeverity(a, config)] - RANK[effectiveSeverity(b, config)] || a.id.localeCompare(b.id) | ||
| ); | ||
| if (failing.length === 0) return ''; | ||
| const lines = [`[svelte-vitals] ${route}`]; | ||
| for (const r of failing) { | ||
| lines.push(` ${GLYPH[effectiveSeverity(r, config)]} ${r.id} ${r.message}`); | ||
| } | ||
| return lines.join('\n'); | ||
| } | ||
|
|
||
| /** Stable signature of a route's penalized findings, so a route is re-printed only when it changes. */ | ||
| export function findingSignature(results: Result[], config: Config): string { | ||
| return penalized(results, config) | ||
| .map((r) => `${r.id}:${effectiveSeverity(r, config)}:${r.detection.presence}:${r.detection.value}`) | ||
| .sort() | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| .join('|'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import { DEV } from 'esm-env'; | ||
| import type { Handle } from '@sveltejs/kit'; | ||
| import { | ||
| allRules, | ||
| applyRuleSeverities, | ||
| defineConfig, | ||
| runRules, | ||
| selectRules, | ||
| type Config, | ||
| type Project, | ||
| type ResolvedHead, | ||
| type Rule | ||
| } from '@svelte-vitals/core'; | ||
| import { parseHtmlHead } from '../providers/rendered/parse-html.js'; | ||
| import { findingSignature, formatDevReport } from './format.js'; | ||
| import type { SvelteVitalsHookOptions } from './options.js'; | ||
|
|
||
| async function analyzeAndWarn( | ||
| html: string, | ||
| route: string, | ||
| rules: Rule[], | ||
| config: Config, | ||
| lastSignature: Map<string, string> | ||
| ): Promise<void> { | ||
| try { | ||
| const { tags, htmlLang } = parseHtmlHead(html); | ||
| const head: ResolvedHead = { route, source: 'rendered', tags, file: route }; | ||
| // robots/sitemap are not page-scoped, so mark them present to suppress SEO006/SEO007; | ||
| // htmlLang comes from the rendered document so SEO009 is evaluated against reality. | ||
| const project: Project = { hasRobotsTxt: true, hasSitemap: true, htmlLang }; | ||
| const results = applyRuleSeverities(await runRules(rules, { heads: [head], project, config }), config); | ||
|
|
||
| const signature = findingSignature(results, config); | ||
| if (lastSignature.get(route) === signature) return; | ||
| lastSignature.set(route, signature); | ||
|
|
||
| const report = formatDevReport(route, results, config); | ||
| if (report) console.warn(report); | ||
| } catch (err) { | ||
| // Dev tooling must never break the request: swallow any parse/rule error. | ||
| // Set SVELTE_VITALS_DEBUG to surface tool-internal errors while debugging. | ||
| if (globalThis.process?.env?.SVELTE_VITALS_DEBUG) { | ||
| console.warn('[svelte-vitals] dev analysis failed:', err); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * SvelteKit `handle` that prints SEO warnings for each visited page's rendered `<head>`, | ||
| * in dev only. Add it to `src/hooks.server.ts`, e.g. `sequence(svelteVitalsHandle())`. | ||
| */ | ||
| export function svelteVitalsHandle(options: SvelteVitalsHookOptions = {}): Handle { | ||
| // Dev-only. `DEV` (esm-env) resolves statically to `true` under the dev server and | ||
| // `false` in production builds; on non-Node runtimes (edge) its fallback reads no | ||
| // bare `process`, so it stays `false`. Everywhere but dev this handle is a no-op, | ||
| // and we skip building the rule set entirely. | ||
| if (!DEV) return ({ event, resolve }) => resolve(event); | ||
|
|
||
| // treatDynamicAs/failOn intentionally left at defaults: rendered HTML never yields | ||
| // `dynamic` values (so treatDynamicAs is moot) and this handle reports rather than | ||
| // gates (so failOn is unused). | ||
| const config = defineConfig({ | ||
| metaComponents: options.metaComponents ?? [], | ||
| rules: options.rules ?? {} | ||
| }); | ||
| const rules = selectRules(allRules, config); | ||
| const lastSignature = new Map<string, string>(); | ||
|
|
||
| return ({ event, resolve }) => { | ||
| let buffer = ''; | ||
| return resolve(event, { | ||
| transformPageChunk: ({ html, done }) => { | ||
| buffer += html; | ||
| // Observe-only: return the chunk unchanged and never block the response on | ||
| // analysis. We fire-and-forget on the final chunk; analyzeAndWarn swallows | ||
| // its own errors, so the floating promise can never reject. | ||
| if (done) void analyzeAndWarn(buffer, event.route.id ?? event.url.pathname, rules, config, lastSignature); | ||
| return html; | ||
| } | ||
| }); | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export { svelteVitalsHandle } from './handle.js'; | ||
| export type { SvelteVitalsHookOptions } from './options.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import type { RuleSetting } from '@svelte-vitals/core'; | ||
|
|
||
| /** Options for the dev-time SvelteKit handle. A focused subset of the plugin options. */ | ||
| export interface SvelteVitalsHookOptions { | ||
| /** Component names treated as meta sources (design §11 layer 4). Mirrors the plugin option. */ | ||
| metaComponents?: string[]; | ||
| /** Per-rule overrides keyed by rule id, e.g. `{ SEO008: 'off' }`. Mirrors the plugin option. */ | ||
| rules?: Record<string, RuleSetting>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { formatDevReport, findingSignature } from '../src/hooks/format.js'; | ||
| import { defineConfig, type Result } from '@svelte-vitals/core'; | ||
|
|
||
| const config = defineConfig({}); | ||
|
|
||
| const failing: Result[] = [ | ||
| { | ||
| id: 'SEO003', | ||
| severity: 'warning', | ||
| detection: { presence: 'none', value: 'absent' }, | ||
| route: '/p', | ||
| message: 'Missing <link rel="canonical">' | ||
| }, | ||
| { | ||
| id: 'SEO001', | ||
| severity: 'critical', | ||
| detection: { presence: 'none', value: 'absent' }, | ||
| route: '/p', | ||
| message: 'Missing <title>' | ||
| } | ||
| ]; | ||
|
|
||
| const passing: Result[] = [ | ||
| { | ||
| id: 'SEO001', | ||
| severity: 'critical', | ||
| detection: { presence: 'own', value: 'static' }, | ||
| route: '/p', | ||
| message: '<title>' | ||
| } | ||
| ]; | ||
|
|
||
| describe('formatDevReport', () => { | ||
| it('lists only penalized findings, most-severe first, under a route header', () => { | ||
| const out = formatDevReport('/p', failing, config); | ||
| const lines = out.split('\n'); | ||
| expect(lines[0]).toBe('[svelte-vitals] /p'); | ||
| expect(lines[1]).toBe(' ✗ SEO001 Missing <title>'); | ||
| expect(lines[2]).toBe(' ⚠ SEO003 Missing <link rel="canonical">'); | ||
| }); | ||
|
|
||
| it('returns an empty string for a clean route', () => { | ||
| expect(formatDevReport('/p', passing, config)).toBe(''); | ||
| }); | ||
| }); | ||
|
|
||
| describe('findingSignature', () => { | ||
| it('is stable regardless of input order', () => { | ||
| const reversed = [...failing].reverse(); | ||
| expect(findingSignature(failing, config)).toBe(findingSignature(reversed, config)); | ||
| }); | ||
|
|
||
| it('ignores passing findings and changes when penalized findings change', () => { | ||
| expect(findingSignature(passing, config)).toBe(''); | ||
| const sigA = findingSignature(failing, config); | ||
| const sigB = findingSignature([failing[0]!], config); | ||
| expect(sigA).not.toBe(sigB); | ||
| }); | ||
|
|
||
| it('distinguishes a missing tag from an empty one (same id and severity)', () => { | ||
| const missing: Result[] = [ | ||
| { | ||
| id: 'SEO001', | ||
| severity: 'critical', | ||
| detection: { presence: 'none', value: 'absent' }, | ||
| route: '/p', | ||
| message: 'Missing <title>' | ||
| } | ||
| ]; | ||
| const empty: Result[] = [ | ||
| { | ||
| id: 'SEO001', | ||
| severity: 'critical', | ||
| detection: { presence: 'own', value: 'absent' }, | ||
| route: '/p', | ||
| message: 'Empty <title>' | ||
| } | ||
| ]; | ||
| expect(findingSignature(missing, config)).not.toBe(findingSignature(empty, config)); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.