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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,25 @@ const css_sources = await scrape_css(page, 'https://projectwallace.com')
await browser.close()
```

`scrape_css` rejects when the navigation fails (DNS error, timeout, ...), so a failed scrape can be told apart from a page without CSS. It accepts `waitUntil` and `timeout`, which are passed to `page.goto()`.

### Errors while collecting

A frame or stylesheet body that cannot be read (a detached frame, a response body the browser already dropped) is skipped, so the rest of the page is still collected. Pass `on_error` to `scrape_css` or `collect_css` to find out about it:

```js
const css_sources = await collect_css(page, css_responses, {
on_error({ source, url, error }) {
// source is 'frame' or 'response'
console.warn(`Skipped ${source} ${url}`, error)
},
})
```

### Stylesheets without a recorded response

A `<link>` stylesheet that loaded, but has no response recorded by `track_css_responses` (it came from the cache or a service worker, or tracking started late), is fetched again from the page, as long as it is served as `text/css` and readable from the page. `@import`ed stylesheets cannot be recovered this way.

## Design principles

- Scrape every stylesheet the page declares, regardless of whether its conditions currently apply. A `<link href="dark.css" rel="stylesheet" media="(prefers-color-scheme: dark)">` is scraped even when the user prefers a light color scheme, because the browser downloads it anyway and the page's full CSS is what we want.
Expand Down
135 changes: 135 additions & 0 deletions src/browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Functions in this file run inside the browser, via `frame.evaluate()`. Playwright serializes
// them with `toString()`, so each one must be fully self-contained: no imports, no references to
// anything outside its own body. They are excluded from Node coverage (see vitest.config.ts)
// because v8 coverage in the Node process cannot see them; the integration tests exercise them.

/** What `read_page_css` finds in a frame. */
export type CSSWalkEntry =
| {
type: 'link'
href: string
/** Normalized: lowercased, whitespace collapsed, e.g. `stylesheet alternate`. */
rel: string
disabled?: string
/** The stylesheet text, only for a loaded link that had no recorded network response
* (cache hit, service worker, late tracking), obtained by fetching it again. */
fetched_css?: string
}
| { type: 'inline'; css: string }
| { type: 'adopted'; css: string }
| { type: 'style'; css: string }
| { type: 'cssom'; css: string }

/** Walks a frame's document and every nested open shadow root exactly once, in document order,
* and reports each `<link rel="stylesheet">`, each non-empty `<style>` element's text, each
* non-empty `style` attribute, each distinct adopted `CSSStyleSheet`'s CSS text, and the rules
* added to each `<style>` or `<link>` sheet after it was parsed (e.g. via `insertRule`).
*
* `shipped_by_url` holds the network response bodies recorded for the page. They are the
* reference a `<link>` sheet's current rules are compared against. */
export async function read_page_css(
shipped_by_url: Record<string, string>,
): Promise<CSSWalkEntry[]> {
const found: CSSWalkEntry[] = []
const seen_sheets = new Set<CSSStyleSheet>()

// Reports only the rules of `sheet` that are not in `shipped_css`, i.e. the ones added after
// parsing. @import rules are skipped: they are reported as import sources, and their
// serialization changes once fetched, which would otherwise look like an addition.
function added_rules_css(sheet: CSSStyleSheet, shipped_css: string): string | undefined {
let current_rules: CSSRule[]
try {
current_rules = Array.from(sheet.cssRules)
} catch {
// Cross-origin sheets without CORS cannot be read
return undefined
}
const parsed = new CSSStyleSheet()
parsed.replaceSync(shipped_css)
const parsed_rules = new Set(Array.from(parsed.cssRules, (rule) => rule.cssText))
const added = current_rules
.filter((rule) => !(rule instanceof CSSImportRule) && !parsed_rules.has(rule.cssText))
.map((rule) => rule.cssText)
return added.length > 0 ? added.join('\n') : undefined
}

async function fetch_css(href: string): Promise<string | undefined> {
try {
const response = await fetch(href)
const content_type = response.headers.get('content-type') ?? ''
return response.ok && content_type.toLowerCase().startsWith('text/css')
? await response.text()
: undefined
} catch {
return undefined
}
}

async function visit(root: Document | ShadowRoot) {
for (const sheet of root.adoptedStyleSheets) {
if (seen_sheets.has(sheet)) {
continue
}
seen_sheets.add(sheet)
found.push({
type: 'adopted',
css: Array.from(sheet.cssRules, (rule) => rule.cssText).join('\n'),
})
}

for (const sheet of root.styleSheets) {
if (sheet.ownerNode instanceof HTMLStyleElement) {
const added_css = added_rules_css(sheet, sheet.ownerNode.textContent ?? '')
if (added_css !== undefined) {
found.push({ type: 'cssom', css: added_css })
}
}
}

for (const el of root.querySelectorAll('*')) {
if (el.matches('link[rel~="stylesheet" i]')) {
const link = el as HTMLLinkElement
const href = link.href
let shipped_css: string | undefined = shipped_by_url[href]
let fetched_css: string | undefined
if (shipped_css === undefined && link.sheet !== null) {
fetched_css = await fetch_css(href)
shipped_css = fetched_css
}
found.push({
type: 'link',
href,
rel: (link.getAttribute('rel') ?? '')
.toLowerCase()
.split(/\s+/)
.filter(Boolean)
.join(' '),
disabled: link.getAttribute('disabled') ?? undefined,
fetched_css,
})
if (shipped_css !== undefined && link.sheet !== null) {
const added_css = added_rules_css(link.sheet, shipped_css)
if (added_css !== undefined) {
found.push({ type: 'cssom', css: added_css })
}
}
} else if (el.matches('style')) {
const style_contents = el.textContent ?? ''
if (style_contents.trim().length > 0) {
found.push({ type: 'style', css: style_contents })
}
}

const style_attr = el.getAttribute('style')?.trim()
if (style_attr) {
found.push({ type: 'inline', css: style_attr })
}
if (el.shadowRoot) {
await visit(el.shadowRoot)
}
}
}

await visit(document)
return found
}
163 changes: 45 additions & 118 deletions src/dom-css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,150 +2,77 @@ import type {
CSSAdoptedStylesheetSource,
CSSCSSOMSource,
CSSInlineSource,
CSSLinkSource,
CSSSource,
CSSStyleSource,
} from './css-source.types.ts'
import type { PageLike, FrameLike } from './types.ts'
import { read_page_css, type CSSWalkEntry } from './browser.ts'
import type { OnScrapeError, PageLike } from './types.ts'

type CSSWalkEntry =
| { type: 'link'; href: string; disabled?: string }
| { type: 'inline'; css: string }
| { type: 'adopted'; css: string }
| { type: 'style'; css: string }
| { type: 'cssom'; css: string }

/** Walks a frame's document and every nested open shadow root exactly once, in document
* order, invoking `on_entry` for each `<link rel="stylesheet">` href, each non-empty
* `<style>` element's text, each non-empty `style` attribute, each distinct adopted
* `CSSStyleSheet`'s CSS text, and the rules added to each `<style>` sheet after parsing
* (e.g. via `insertRule`). */
async function walk_css_entries(
frame: FrameLike,
on_entry: (entry: CSSWalkEntry) => void,
): Promise<void> {
/* v8 ignore start -- runs inside the browser via Playwright, not in the Node coverage process */
const entries = await frame.evaluate(() => {
const found: CSSWalkEntry[] = []
const seen_sheets = new Set<CSSStyleSheet>()

function rules_css(sheet: CSSStyleSheet): string {
return Array.from(sheet.cssRules, (rule) => rule.cssText).join('\n')
}

function visit(root: Document | ShadowRoot) {
for (const sheet of root.adoptedStyleSheets) {
if (seen_sheets.has(sheet)) {
continue
}
seen_sheets.add(sheet)
found.push({ type: 'adopted', css: rules_css(sheet) })
}

for (const sheet of root.styleSheets) {
if (!(sheet.ownerNode instanceof HTMLStyleElement)) {
continue
}
// Parse the element's text into a reference sheet, and report only the rules
// that are not in it, i.e. the ones added after parsing. @import rules are
// skipped: they are reported as import sources, and their serialization
// changes once fetched, which would otherwise look like an addition.
const parsed = new CSSStyleSheet()
parsed.replaceSync(sheet.ownerNode.textContent ?? '')
const parsed_rules = new Set(Array.from(parsed.cssRules, (rule) => rule.cssText))
const added_css = Array.from(sheet.cssRules)
.filter((rule) => !(rule instanceof CSSImportRule) && !parsed_rules.has(rule.cssText))
.map((rule) => rule.cssText)
if (added_css.length > 0) {
found.push({ type: 'cssom', css: added_css.join('\n') })
}
}

for (const el of root.querySelectorAll('*')) {
if (el.matches('link[rel~="stylesheet" i]')) {
found.push({
type: 'link',
href: (el as HTMLLinkElement).href,
disabled: el.getAttribute('disabled') ?? undefined,
})
} else if (el.matches('style')) {
const style_contents = el.textContent ?? ''
if (style_contents.trim().length > 0) {
found.push({ type: 'style', css: style_contents })
}
}

const style_attr = el.getAttribute('style')?.trim()
if (style_attr) {
found.push({ type: 'inline', css: style_attr })
}
if (el.shadowRoot) {
visit(el.shadowRoot)
}
}
}
visit(document)
return found
})
/* v8 ignore stop */

// Cannot call on_entry within page.evaluate(), so call it here afterwards
for (const entry of entries) {
on_entry(entry)
}
}

/** What the DOM walk found: the `<link>` hrefs for the network cross-check, and every
* other source, already in output order. */
/** What the DOM walk found: the `<link>`s the network cross-check needs to classify responses,
* the links that had to be fetched again because no response was recorded, and every other
* source, already in output order. */
export interface DOMCSS {
link_hrefs: Map<string, string | undefined>
links: Map<string, { rel: string; disabled?: string }>
fetched_links: CSSLinkSource[]
sources: CSSSource[]
}

/** Collects the CSS that lives in the DOM of every frame on the page. */
export async function collect_dom_css(page: PageLike): Promise<DOMCSS> {
const link_hrefs = new Map<string, string | undefined>()
/** Collects the CSS that lives in the DOM of every frame on the page. A frame that cannot be
* read (detached or navigated away mid-walk) is reported to `on_error` and skipped, so one bad
* frame does not lose the CSS of the others. */
export async function collect_dom_css(
page: PageLike,
shipped_by_url: Record<string, string>,
on_error?: OnScrapeError,
): Promise<DOMCSS> {
const links = new Map<string, { rel: string; disabled?: string }>()
const fetched_links: CSSLinkSource[] = []
const inline_sources: CSSInlineSource[] = []
const style_sources: CSSStyleSource[] = []
const adopted_sources: CSSAdoptedStylesheetSource[] = []
const cssom_sources: CSSCSSOMSource[] = []

for (const frame of page.frames()) {
const frame_url = frame.url()
let entries: CSSWalkEntry[]
try {
entries = await frame.evaluate(read_page_css, shipped_by_url)
} catch (error) {
on_error?.({ source: 'frame', url: frame_url, error })
continue
}

const seen_adopted_css = new Set<string>()
await walk_css_entries(frame, (entry) => {
for (const entry of entries) {
if (entry.type === 'link') {
link_hrefs.set(entry.href, entry.disabled)
links.set(entry.href, { rel: entry.rel, disabled: entry.disabled })
if (entry.fetched_css !== undefined) {
fetched_links.push({
type: 'link',
href: entry.href,
url: entry.href,
rel: entry.rel,
css: entry.fetched_css,
disabled: entry.disabled,
})
}
} else if (entry.type === 'inline') {
inline_sources.push({
type: 'inline',
url: frame_url,
css: entry.css,
} satisfies CSSInlineSource)
inline_sources.push({ type: 'inline', url: frame_url, css: entry.css })
} else if (entry.type === 'style') {
style_sources.push({
type: 'style',
url: frame_url,
css: entry.css,
} satisfies CSSStyleSource)
style_sources.push({ type: 'style', url: frame_url, css: entry.css })
} else if (entry.type === 'cssom') {
cssom_sources.push({
type: 'cssom',
url: frame_url,
css: entry.css,
} satisfies CSSCSSOMSource)
cssom_sources.push({ type: 'cssom', url: frame_url, css: entry.css })
} else if (!seen_adopted_css.has(entry.css)) {
seen_adopted_css.add(entry.css)
adopted_sources.push({
type: 'adopted-stylesheet',
url: frame_url,
css: entry.css,
} satisfies CSSAdoptedStylesheetSource)
adopted_sources.push({ type: 'adopted-stylesheet', url: frame_url, css: entry.css })
}
})
}
}

return {
link_hrefs,
links,
fetched_links,
sources: [...adopted_sources, ...style_sources, ...cssom_sources, ...inline_sources],
}
}
Loading
Loading