@pairdraw/web-capture 0.0.0-stage → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/dist/capturer.d.ts +56 -0
- package/dist/capturer.d.ts.map +1 -0
- package/dist/capturer.js +3 -0
- package/dist/chunks/capturer/clipboard.js +575 -0
- package/dist/chunks/capturer/clipboard.js.map +1 -0
- package/dist/chunks/capturer/fonts.js +25 -0
- package/dist/chunks/capturer/fonts.js.map +1 -0
- package/dist/chunks/capturer/images.js +113 -0
- package/dist/chunks/capturer/images.js.map +1 -0
- package/dist/chunks/capturer/index.js +445 -0
- package/dist/chunks/capturer/index.js.map +1 -0
- package/dist/chunks/design-document.js +251 -0
- package/dist/chunks/design-document.js.map +1 -0
- package/dist/chunks/index.js +125 -0
- package/dist/chunks/index.js.map +1 -0
- package/dist/clipboard.d.ts +106 -0
- package/dist/clipboard.d.ts.map +1 -0
- package/dist/index.d.ts +110 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/package.json +43 -4
- package/src/capturer/clipboard.ts +59 -0
- package/src/capturer/fonts.ts +30 -0
- package/src/capturer/images.ts +153 -0
- package/src/capturer/index.ts +170 -0
- package/src/capturer/page.ts +51 -0
- package/src/capturer/svg.ts +79 -0
- package/src/capturer/walk.ts +283 -0
- package/src/clipboard.ts +85 -0
- package/src/design-document.ts +267 -0
- package/src/format.ts +17 -0
- package/src/html.ts +44 -0
- package/src/index.ts +41 -0
- package/src/limits.ts +23 -0
- package/src/parse.ts +165 -0
- package/src/record.ts +10 -0
- package/src/sanitize.ts +134 -0
- package/src/schema.ts +75 -0
- package/src/styles.ts +163 -0
- package/src/types.ts +28 -0
- package/src/urls.ts +27 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export {
|
|
2
|
+
WEB_CAPTURE_CLIPBOARD_END,
|
|
3
|
+
WEB_CAPTURE_CLIPBOARD_START,
|
|
4
|
+
encodeWebCaptureClipboard,
|
|
5
|
+
hasWebCaptureClipboardMarker,
|
|
6
|
+
readWebCaptureClipboard
|
|
7
|
+
} from './clipboard'
|
|
8
|
+
export type { WebCaptureClipboardPayload } from './clipboard'
|
|
9
|
+
export { webCaptureDesignDocument } from './design-document'
|
|
10
|
+
export type {
|
|
11
|
+
WebCaptureDesignDocument,
|
|
12
|
+
WebCaptureDesignElement,
|
|
13
|
+
WebCaptureDesignNode
|
|
14
|
+
} from './design-document'
|
|
15
|
+
export type {
|
|
16
|
+
WebCapture,
|
|
17
|
+
WebCaptureFont,
|
|
18
|
+
WebCaptureReadError,
|
|
19
|
+
WebCaptureReadResult,
|
|
20
|
+
WebCaptureViewport
|
|
21
|
+
} from './format'
|
|
22
|
+
export { webCaptureToHTML } from './html'
|
|
23
|
+
export type { WebCaptureHTMLOptions } from './html'
|
|
24
|
+
export {
|
|
25
|
+
MAX_CAPTURE_DEPTH,
|
|
26
|
+
MAX_CAPTURE_ELEMENTS,
|
|
27
|
+
MAX_CAPTURE_IMAGE_BYTES,
|
|
28
|
+
MAX_CAPTURE_IMAGES_BYTES,
|
|
29
|
+
MAX_CAPTURE_JSON_LENGTH,
|
|
30
|
+
MAX_WEB_HTML_LENGTH,
|
|
31
|
+
WEB_CAPTURE_FORMAT,
|
|
32
|
+
WEB_CAPTURE_VERSION
|
|
33
|
+
} from './limits'
|
|
34
|
+
export { normalizeWebCapture, parseWebCapture, readWebCapture } from './parse'
|
|
35
|
+
export { hasWebContent, sanitizeWebHTML } from './sanitize'
|
|
36
|
+
export type { SanitizeWebHTMLOptions } from './sanitize'
|
|
37
|
+
export { webCaptureSchema } from './schema'
|
|
38
|
+
export { CAPTURED_STYLE_PROPERTIES, isCapturedStyleProperty, withoutImpliedValues } from './styles'
|
|
39
|
+
export type { CapturedStyleProperty } from './styles'
|
|
40
|
+
export type { WebCaptureBox, WebCaptureElement, WebCaptureNode, WebCaptureText } from './types'
|
|
41
|
+
export { safeImageSource, safeLinkURL } from './urls'
|
package/src/limits.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The capture format identifier that clipboard payloads and files carry. */
|
|
2
|
+
export const WEB_CAPTURE_FORMAT = 'pairdraw/web-capture'
|
|
3
|
+
|
|
4
|
+
/** The capture format version this package writes and reads. */
|
|
5
|
+
export const WEB_CAPTURE_VERSION = 1
|
|
6
|
+
|
|
7
|
+
/** Elements one capture holds at most; a capturer stops descending once it reaches this. */
|
|
8
|
+
export const MAX_CAPTURE_ELEMENTS = 20_000
|
|
9
|
+
|
|
10
|
+
/** How deep a capture nests; deeper elements are left out, as browsers rarely draw them. */
|
|
11
|
+
export const MAX_CAPTURE_DEPTH = 256
|
|
12
|
+
|
|
13
|
+
/** Bytes one inlined image may take; a larger image stays a link the importer records. */
|
|
14
|
+
export const MAX_CAPTURE_IMAGE_BYTES = 8 * 1024 * 1024
|
|
15
|
+
|
|
16
|
+
/** Bytes all inlined images of a capture take together. */
|
|
17
|
+
export const MAX_CAPTURE_IMAGES_BYTES = 48 * 1024 * 1024
|
|
18
|
+
|
|
19
|
+
/** Characters of serialized capture JSON a reader accepts, images included. */
|
|
20
|
+
export const MAX_CAPTURE_JSON_LENGTH = 96 * 1024 * 1024
|
|
21
|
+
|
|
22
|
+
/** Characters of plain web HTML a paste styles; a larger fragment is refused. */
|
|
23
|
+
export const MAX_WEB_HTML_LENGTH = 8 * 1024 * 1024
|
package/src/parse.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import * as v from 'valibot'
|
|
2
|
+
|
|
3
|
+
import type { WebCapture, WebCaptureReadResult } from './format'
|
|
4
|
+
import {
|
|
5
|
+
MAX_CAPTURE_DEPTH,
|
|
6
|
+
MAX_CAPTURE_ELEMENTS,
|
|
7
|
+
MAX_CAPTURE_JSON_LENGTH,
|
|
8
|
+
WEB_CAPTURE_FORMAT,
|
|
9
|
+
WEB_CAPTURE_VERSION
|
|
10
|
+
} from './limits'
|
|
11
|
+
import { webCaptureSchema } from './schema'
|
|
12
|
+
import { isCapturedStyleProperty } from './styles'
|
|
13
|
+
import type { WebCaptureElement, WebCaptureNode } from './types'
|
|
14
|
+
import { safeImageSource, safeLinkURL } from './urls'
|
|
15
|
+
|
|
16
|
+
/** Read first, so a capture from a newer capturer is told apart from a damaged one. */
|
|
17
|
+
const captureHeaderSchema = v.looseObject({
|
|
18
|
+
format: v.literal(WEB_CAPTURE_FORMAT),
|
|
19
|
+
version: v.number()
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
/** Attributes a layer can use: names, links, images, and accessible labels. */
|
|
23
|
+
const KEPT_ATTRIBUTES = new Set([
|
|
24
|
+
'id',
|
|
25
|
+
'class',
|
|
26
|
+
'href',
|
|
27
|
+
'src',
|
|
28
|
+
'alt',
|
|
29
|
+
'title',
|
|
30
|
+
'role',
|
|
31
|
+
'aria-label',
|
|
32
|
+
'lang',
|
|
33
|
+
'dir'
|
|
34
|
+
])
|
|
35
|
+
|
|
36
|
+
/** Elements that never draw, whatever a capture claims. */
|
|
37
|
+
const DROPPED_TAGS = new Set([
|
|
38
|
+
'script',
|
|
39
|
+
'style',
|
|
40
|
+
'link',
|
|
41
|
+
'meta',
|
|
42
|
+
'head',
|
|
43
|
+
'title',
|
|
44
|
+
'template',
|
|
45
|
+
'noscript',
|
|
46
|
+
'iframe',
|
|
47
|
+
'frame',
|
|
48
|
+
'object',
|
|
49
|
+
'embed',
|
|
50
|
+
'base'
|
|
51
|
+
])
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* JSON nesting a capture within `MAX_CAPTURE_DEPTH` takes: an object and a `children` array per
|
|
55
|
+
* element, the capture around the root, and the records of the deepest element, with room to
|
|
56
|
+
* spare. Deeper values are refused before validation, whose recursion they could overflow.
|
|
57
|
+
*/
|
|
58
|
+
const MAX_JSON_NESTING = 2 * MAX_CAPTURE_DEPTH + 16
|
|
59
|
+
|
|
60
|
+
/** Whether a value nests deeper than `limit`, walked without recursion; a cycle counts as deep. */
|
|
61
|
+
function nestsDeeperThan(value: unknown, limit: number): boolean {
|
|
62
|
+
const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }]
|
|
63
|
+
for (let next = pending.pop(); next; next = pending.pop()) {
|
|
64
|
+
if (typeof next.value !== 'object' || next.value === null) continue
|
|
65
|
+
if (next.depth >= limit) return true
|
|
66
|
+
const depth = next.depth + 1
|
|
67
|
+
for (const child of Object.values(next.value)) pending.push({ value: child, depth })
|
|
68
|
+
}
|
|
69
|
+
return false
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface Budget {
|
|
73
|
+
elements: number
|
|
74
|
+
truncated: boolean
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function keptAttributes(
|
|
78
|
+
attrs: Record<string, string>,
|
|
79
|
+
base: string | undefined
|
|
80
|
+
): Record<string, string> {
|
|
81
|
+
const kept: Record<string, string> = {}
|
|
82
|
+
for (const [name, value] of Object.entries(attrs)) {
|
|
83
|
+
if (!KEPT_ATTRIBUTES.has(name)) continue
|
|
84
|
+
if (name === 'href') {
|
|
85
|
+
const href = safeLinkURL(value, base)
|
|
86
|
+
if (href) kept.href = href
|
|
87
|
+
} else if (name === 'src') {
|
|
88
|
+
const src = safeImageSource(value, base)
|
|
89
|
+
if (src) kept.src = src
|
|
90
|
+
} else {
|
|
91
|
+
kept[name] = value
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return kept
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function keptStyle(style: Record<string, string>): Record<string, string> {
|
|
98
|
+
return Object.fromEntries(
|
|
99
|
+
Object.entries(style).filter(([property]) => isCapturedStyleProperty(property))
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeElement(
|
|
104
|
+
element: WebCaptureElement,
|
|
105
|
+
base: string | undefined,
|
|
106
|
+
depth: number,
|
|
107
|
+
budget: Budget
|
|
108
|
+
): WebCaptureElement {
|
|
109
|
+
const children: WebCaptureNode[] = []
|
|
110
|
+
for (const child of element.children) {
|
|
111
|
+
if (child.type === 'text') {
|
|
112
|
+
children.push(child)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
if (DROPPED_TAGS.has(child.tagName)) continue
|
|
116
|
+
if (depth + 1 > MAX_CAPTURE_DEPTH || budget.elements >= MAX_CAPTURE_ELEMENTS) {
|
|
117
|
+
budget.truncated = true
|
|
118
|
+
continue
|
|
119
|
+
}
|
|
120
|
+
budget.elements++
|
|
121
|
+
children.push(normalizeElement(child, base, depth + 1, budget))
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
type: 'element',
|
|
125
|
+
tagName: element.tagName,
|
|
126
|
+
attrs: keptAttributes(element.attrs, base),
|
|
127
|
+
computedStyle: keptStyle(element.computedStyle),
|
|
128
|
+
...(element.box ? { box: element.box } : {}),
|
|
129
|
+
children
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A capture as an import may use it: only the attributes and properties layers read, links
|
|
135
|
+
* limited to http, https, and mailto, images limited to raster data URLs and http(s) addresses,
|
|
136
|
+
* and at most `MAX_CAPTURE_ELEMENTS` elements. Captures come from any page, so every reader
|
|
137
|
+
* goes through this.
|
|
138
|
+
*/
|
|
139
|
+
export function normalizeWebCapture(capture: WebCapture): WebCapture {
|
|
140
|
+
const budget: Budget = { elements: 1, truncated: false }
|
|
141
|
+
const base = capture.source.url
|
|
142
|
+
const root = normalizeElement(capture.root, base, 0, budget)
|
|
143
|
+
return { ...capture, root, truncated: capture.truncated || budget.truncated }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Reads a capture that is already a value, such as one a capturer handed over. */
|
|
147
|
+
export function readWebCapture(value: unknown): WebCaptureReadResult {
|
|
148
|
+
if (nestsDeeperThan(value, MAX_JSON_NESTING)) return { ok: false, error: 'invalid' }
|
|
149
|
+
const header = v.safeParse(captureHeaderSchema, value)
|
|
150
|
+
if (!header.success) return { ok: false, error: 'invalid' }
|
|
151
|
+
if (header.output.version !== WEB_CAPTURE_VERSION) {
|
|
152
|
+
return { ok: false, error: 'unsupported-version' }
|
|
153
|
+
}
|
|
154
|
+
const parsed = v.safeParse(webCaptureSchema, value)
|
|
155
|
+
if (!parsed.success) return { ok: false, error: 'invalid' }
|
|
156
|
+
return { ok: true, capture: normalizeWebCapture(parsed.output) }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Reads a capture serialized as JSON, as files and clipboard payloads hold it. */
|
|
160
|
+
export function parseWebCapture(text: string): WebCaptureReadResult {
|
|
161
|
+
if (text.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }
|
|
162
|
+
const json = v.safeParse(v.pipe(v.string(), v.parseJson()), text)
|
|
163
|
+
if (!json.success) return { ok: false, error: 'invalid' }
|
|
164
|
+
return readWebCapture(json.output)
|
|
165
|
+
}
|
package/src/record.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The value a style or attribute record sets for `key`, or undefined when it sets none. Records
|
|
3
|
+
* are typed as setting every key, which they do not.
|
|
4
|
+
*/
|
|
5
|
+
export function ownValue(
|
|
6
|
+
record: Readonly<Record<string, string>>,
|
|
7
|
+
key: string
|
|
8
|
+
): string | undefined {
|
|
9
|
+
return Object.hasOwn(record, key) ? record[key] : undefined
|
|
10
|
+
}
|
package/src/sanitize.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { MAX_WEB_HTML_LENGTH } from './limits'
|
|
2
|
+
import { safeImageSource, safeLinkURL } from './urls'
|
|
3
|
+
|
|
4
|
+
/** Elements that run code, load other documents, or change how the rest is read. */
|
|
5
|
+
const REMOVED_TAGS = [
|
|
6
|
+
'script',
|
|
7
|
+
'iframe',
|
|
8
|
+
'frame',
|
|
9
|
+
'frameset',
|
|
10
|
+
'object',
|
|
11
|
+
'embed',
|
|
12
|
+
'applet',
|
|
13
|
+
'portal',
|
|
14
|
+
'base',
|
|
15
|
+
'link',
|
|
16
|
+
'meta',
|
|
17
|
+
'noscript',
|
|
18
|
+
'template',
|
|
19
|
+
'animate',
|
|
20
|
+
'animatemotion',
|
|
21
|
+
'animatetransform',
|
|
22
|
+
'set',
|
|
23
|
+
'foreignobject',
|
|
24
|
+
// MathML and its table-breaking leaves are where re-parsing turns style text into elements.
|
|
25
|
+
'math',
|
|
26
|
+
'mglyph',
|
|
27
|
+
'malignmark'
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
/** Attributes that name URLs; each keeps only what `safeLinkURL` or `safeImageSource` allow. */
|
|
31
|
+
const LINK_ATTRIBUTES = new Set(['href', 'xlink:href', 'action', 'formaction', 'cite'])
|
|
32
|
+
const IMAGE_ATTRIBUTES = new Set(['src', 'poster', 'background'])
|
|
33
|
+
/** Attributes dropped outright: inline documents, pings, and alternate image candidates. */
|
|
34
|
+
const REMOVED_ATTRIBUTES = new Set(['srcdoc', 'ping', 'srcset', 'http-equiv', 'imagesrcset'])
|
|
35
|
+
|
|
36
|
+
const CSS_IMPORT = /@import[^;]*;?/gi
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Parses of the output a sanitize may take. Serialized HTML can parse into a different tree
|
|
40
|
+
* (mutation XSS), so each pass reads the previous output; HTML that has not settled by the last
|
|
41
|
+
* pass is refused.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_SANITIZE_PASSES = 4
|
|
44
|
+
|
|
45
|
+
export interface SanitizeWebHTMLOptions {
|
|
46
|
+
/** The parser to read the HTML with; the global `DOMParser` by default. */
|
|
47
|
+
parser?: Pick<DOMParser, 'parseFromString'>
|
|
48
|
+
/** The address relative links and images resolve against. */
|
|
49
|
+
baseURL?: string
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Sets an attribute to a cleaned value, or removes it; true when that changed it. */
|
|
53
|
+
function replaceAttribute(element: Element, name: string, value: string, url: string | null) {
|
|
54
|
+
if (url === value) return false
|
|
55
|
+
if (url) element.setAttribute(name, url)
|
|
56
|
+
else element.removeAttribute(name)
|
|
57
|
+
return true
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Cleans an element's attributes; true when any was removed or rewritten. */
|
|
61
|
+
function cleanAttributes(element: Element, baseURL: string | undefined): boolean {
|
|
62
|
+
let changed = false
|
|
63
|
+
// A copy, since removing attributes changes the live list.
|
|
64
|
+
for (const { name, value } of Array.from(element.attributes)) {
|
|
65
|
+
const lower = name.toLowerCase()
|
|
66
|
+
if (lower.startsWith('on') || REMOVED_ATTRIBUTES.has(lower)) {
|
|
67
|
+
element.removeAttribute(name)
|
|
68
|
+
changed = true
|
|
69
|
+
} else if (LINK_ATTRIBUTES.has(lower)) {
|
|
70
|
+
changed = replaceAttribute(element, name, value, safeLinkURL(value, baseURL)) || changed
|
|
71
|
+
} else if (IMAGE_ATTRIBUTES.has(lower)) {
|
|
72
|
+
changed = replaceAttribute(element, name, value, safeImageSource(value, baseURL)) || changed
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return changed
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One parse of the HTML, cleaned and serialized, and whether cleaning changed anything. */
|
|
79
|
+
function sanitizePass(
|
|
80
|
+
html: string,
|
|
81
|
+
parser: Pick<DOMParser, 'parseFromString'>,
|
|
82
|
+
baseURL: string | undefined
|
|
83
|
+
): { html: string; changed: boolean } {
|
|
84
|
+
const document = parser.parseFromString(html, 'text/html')
|
|
85
|
+
const removed = [...document.querySelectorAll(REMOVED_TAGS.join(','))]
|
|
86
|
+
for (const element of removed) element.remove()
|
|
87
|
+
let changed = removed.length > 0
|
|
88
|
+
for (const element of document.querySelectorAll('*')) {
|
|
89
|
+
changed = cleanAttributes(element, baseURL) || changed
|
|
90
|
+
}
|
|
91
|
+
const styles = [...document.querySelectorAll('style')].map((style) => {
|
|
92
|
+
const css = style.textContent.replaceAll(CSS_IMPORT, '')
|
|
93
|
+
if (css !== style.textContent) {
|
|
94
|
+
style.textContent = css
|
|
95
|
+
changed = true
|
|
96
|
+
}
|
|
97
|
+
// Styles in the head would be lost with it; the importer reads them from the body.
|
|
98
|
+
return document.body.contains(style) ? '' : style.outerHTML
|
|
99
|
+
})
|
|
100
|
+
return { html: `${styles.join('')}${document.body.innerHTML}`, changed }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* HTML from outside, such as a web page's clipboard fragment, made safe to style in the app's
|
|
105
|
+
* own document: no scripts, event handlers, frames, MathML, or script URLs, and no stylesheets
|
|
106
|
+
* loaded from elsewhere. The parser builds an inert document, so nothing runs while it is
|
|
107
|
+
* cleaned. The result is a fixed point: parsing it again finds nothing to clean and serializes
|
|
108
|
+
* to the same HTML, so a later parse cannot grow elements the cleaning never saw. Returns an
|
|
109
|
+
* empty string for HTML above `MAX_WEB_HTML_LENGTH`, HTML that never settles, or without a
|
|
110
|
+
* parser.
|
|
111
|
+
*/
|
|
112
|
+
export function sanitizeWebHTML(html: string, options: SanitizeWebHTMLOptions = {}): string {
|
|
113
|
+
if (html.length > MAX_WEB_HTML_LENGTH) return ''
|
|
114
|
+
const parser = options.parser ?? (typeof DOMParser === 'undefined' ? undefined : new DOMParser())
|
|
115
|
+
if (!parser) return ''
|
|
116
|
+
let current = html
|
|
117
|
+
for (let pass = 0; pass < MAX_SANITIZE_PASSES; pass++) {
|
|
118
|
+
const next = sanitizePass(current, parser, options.baseURL)
|
|
119
|
+
if (!next.changed && next.html === current) return current
|
|
120
|
+
current = next.html
|
|
121
|
+
}
|
|
122
|
+
return ''
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Whether HTML draws anything: text other than whitespace, or an image. */
|
|
126
|
+
export function hasWebContent(html: string, options: Pick<SanitizeWebHTMLOptions, 'parser'> = {}) {
|
|
127
|
+
const parser = options.parser ?? (typeof DOMParser === 'undefined' ? undefined : new DOMParser())
|
|
128
|
+
if (!parser) return false
|
|
129
|
+
const document = parser.parseFromString(html, 'text/html')
|
|
130
|
+
return (
|
|
131
|
+
document.body.textContent.trim().length > 0 ||
|
|
132
|
+
document.body.querySelector('img, svg, picture, video, canvas') !== null
|
|
133
|
+
)
|
|
134
|
+
}
|
package/src/schema.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import * as v from 'valibot'
|
|
2
|
+
|
|
3
|
+
import { MAX_CAPTURE_JSON_LENGTH, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from './limits'
|
|
4
|
+
import type { WebCaptureElement, WebCaptureNode } from './types'
|
|
5
|
+
|
|
6
|
+
const finiteSchema = v.pipe(v.number(), v.finite())
|
|
7
|
+
const sizeSchema = v.pipe(v.number(), v.finite(), v.minValue(0))
|
|
8
|
+
const shortStringSchema = v.pipe(v.string(), v.maxLength(4096))
|
|
9
|
+
|
|
10
|
+
const webCaptureBoxSchema = v.object({
|
|
11
|
+
x: finiteSchema,
|
|
12
|
+
y: finiteSchema,
|
|
13
|
+
width: sizeSchema,
|
|
14
|
+
height: sizeSchema
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
const webCaptureTextSchema = v.object({
|
|
18
|
+
type: v.literal('text'),
|
|
19
|
+
text: v.pipe(v.string(), v.maxLength(1_000_000))
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
/** HTML and SVG tag names, lowercase as a capturer writes them. */
|
|
23
|
+
const tagNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]{0,63}$/))
|
|
24
|
+
/** Attribute names; which of them an import keeps is decided when a capture is read. */
|
|
25
|
+
const attributeNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9:_-]{0,63}$/))
|
|
26
|
+
/** Attribute values hold inlined images as data URLs, so they may be large. */
|
|
27
|
+
const attributeValueSchema = v.pipe(v.string(), v.maxLength(MAX_CAPTURE_JSON_LENGTH))
|
|
28
|
+
const propertyNameSchema = v.pipe(v.string(), v.regex(/^-?[a-z][a-z-]{0,63}$/))
|
|
29
|
+
|
|
30
|
+
const webCaptureElementSchema: v.GenericSchema<unknown, WebCaptureElement> = v.object({
|
|
31
|
+
type: v.literal('element'),
|
|
32
|
+
tagName: tagNameSchema,
|
|
33
|
+
attrs: v.record(attributeNameSchema, attributeValueSchema),
|
|
34
|
+
computedStyle: v.record(propertyNameSchema, shortStringSchema),
|
|
35
|
+
box: v.optional(webCaptureBoxSchema),
|
|
36
|
+
children: v.array(v.lazy(() => webCaptureNodeSchema))
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
const webCaptureNodeSchema: v.GenericSchema<unknown, WebCaptureNode> = v.union([
|
|
40
|
+
webCaptureTextSchema,
|
|
41
|
+
webCaptureElementSchema
|
|
42
|
+
])
|
|
43
|
+
|
|
44
|
+
export const webCaptureFontSchema = v.object({
|
|
45
|
+
family: shortStringSchema,
|
|
46
|
+
weight: shortStringSchema,
|
|
47
|
+
style: shortStringSchema
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
export const webCaptureViewportSchema = v.object({
|
|
51
|
+
width: sizeSchema,
|
|
52
|
+
height: sizeSchema,
|
|
53
|
+
devicePixelRatio: v.pipe(v.number(), v.finite(), v.minValue(0))
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const webCaptureSourceSchema = v.object({
|
|
57
|
+
url: v.optional(shortStringSchema),
|
|
58
|
+
title: v.optional(shortStringSchema)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
/** A page or element captured with the styles the browser computed for it. */
|
|
62
|
+
export const webCaptureSchema = v.object({
|
|
63
|
+
format: v.literal(WEB_CAPTURE_FORMAT),
|
|
64
|
+
version: v.literal(WEB_CAPTURE_VERSION),
|
|
65
|
+
/** Whether a whole page or one element of it was captured. */
|
|
66
|
+
scope: v.picklist(['page', 'element']),
|
|
67
|
+
source: webCaptureSourceSchema,
|
|
68
|
+
/** When the capture was made, as an ISO 8601 timestamp. */
|
|
69
|
+
capturedAt: shortStringSchema,
|
|
70
|
+
viewport: webCaptureViewportSchema,
|
|
71
|
+
root: webCaptureElementSchema,
|
|
72
|
+
fonts: v.array(webCaptureFontSchema),
|
|
73
|
+
/** Whether the capturer stopped at its element limit, leaving later content out. */
|
|
74
|
+
truncated: v.boolean()
|
|
75
|
+
})
|
package/src/styles.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { ownValue } from './record'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The computed properties a capture keeps for each element: those `@pairdraw/dom-css` builds
|
|
5
|
+
* layers from, plus margins, which a capture turns into spacing when it is imported.
|
|
6
|
+
*/
|
|
7
|
+
export const CAPTURED_STYLE_PROPERTIES = [
|
|
8
|
+
'align-items',
|
|
9
|
+
'align-self',
|
|
10
|
+
'aspect-ratio',
|
|
11
|
+
'background-color',
|
|
12
|
+
'border-bottom-color',
|
|
13
|
+
'border-bottom-left-radius',
|
|
14
|
+
'border-bottom-right-radius',
|
|
15
|
+
'border-bottom-style',
|
|
16
|
+
'border-bottom-width',
|
|
17
|
+
'border-left-color',
|
|
18
|
+
'border-left-style',
|
|
19
|
+
'border-left-width',
|
|
20
|
+
'border-right-color',
|
|
21
|
+
'border-right-style',
|
|
22
|
+
'border-right-width',
|
|
23
|
+
'border-top-color',
|
|
24
|
+
'border-top-left-radius',
|
|
25
|
+
'border-top-right-radius',
|
|
26
|
+
'border-top-style',
|
|
27
|
+
'border-top-width',
|
|
28
|
+
'bottom',
|
|
29
|
+
'box-shadow',
|
|
30
|
+
'box-sizing',
|
|
31
|
+
'color',
|
|
32
|
+
'column-gap',
|
|
33
|
+
'display',
|
|
34
|
+
'flex-direction',
|
|
35
|
+
'flex-wrap',
|
|
36
|
+
'font-family',
|
|
37
|
+
'font-size',
|
|
38
|
+
'font-style',
|
|
39
|
+
'font-weight',
|
|
40
|
+
'gap',
|
|
41
|
+
'height',
|
|
42
|
+
'justify-content',
|
|
43
|
+
'left',
|
|
44
|
+
'letter-spacing',
|
|
45
|
+
'line-height',
|
|
46
|
+
'margin-bottom',
|
|
47
|
+
'margin-left',
|
|
48
|
+
'margin-right',
|
|
49
|
+
'margin-top',
|
|
50
|
+
'max-height',
|
|
51
|
+
'max-width',
|
|
52
|
+
'min-height',
|
|
53
|
+
'min-width',
|
|
54
|
+
'object-fit',
|
|
55
|
+
'opacity',
|
|
56
|
+
'overflow',
|
|
57
|
+
'padding-bottom',
|
|
58
|
+
'padding-left',
|
|
59
|
+
'padding-right',
|
|
60
|
+
'padding-top',
|
|
61
|
+
'position',
|
|
62
|
+
'right',
|
|
63
|
+
'row-gap',
|
|
64
|
+
'text-align',
|
|
65
|
+
'text-decoration-color',
|
|
66
|
+
'text-decoration-line',
|
|
67
|
+
'text-decoration-style',
|
|
68
|
+
'text-decoration-thickness',
|
|
69
|
+
'text-indent',
|
|
70
|
+
'text-shadow',
|
|
71
|
+
'text-transform',
|
|
72
|
+
'text-underline-offset',
|
|
73
|
+
'top',
|
|
74
|
+
'white-space',
|
|
75
|
+
'width'
|
|
76
|
+
] as const
|
|
77
|
+
|
|
78
|
+
export type CapturedStyleProperty = (typeof CAPTURED_STYLE_PROPERTIES)[number]
|
|
79
|
+
|
|
80
|
+
const CAPTURED = new Set<string>(CAPTURED_STYLE_PROPERTIES)
|
|
81
|
+
|
|
82
|
+
/** Whether a capture keeps this property; others are dropped when a capture is read. */
|
|
83
|
+
export function isCapturedStyleProperty(property: string): property is CapturedStyleProperty {
|
|
84
|
+
return CAPTURED.has(property)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const SIDES = ['top', 'right', 'bottom', 'left'] as const
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Values the importer reads exactly as it reads a missing property, so leaving them out only
|
|
91
|
+
* makes the capture smaller. Inherited text properties are always kept: a nested run reads
|
|
92
|
+
* a missing one from its parent, which differs from the value the page computed.
|
|
93
|
+
*/
|
|
94
|
+
const IMPLIED_VALUES: Partial<Record<CapturedStyleProperty, readonly string[]>> = {
|
|
95
|
+
'align-items': ['normal'],
|
|
96
|
+
'align-self': ['auto'],
|
|
97
|
+
'aspect-ratio': ['auto'],
|
|
98
|
+
'background-color': ['rgba(0, 0, 0, 0)', 'transparent'],
|
|
99
|
+
'box-shadow': ['none'],
|
|
100
|
+
'column-gap': ['normal'],
|
|
101
|
+
'flex-direction': ['row'],
|
|
102
|
+
'flex-wrap': ['nowrap'],
|
|
103
|
+
gap: ['normal'],
|
|
104
|
+
height: ['auto'],
|
|
105
|
+
'justify-content': ['normal'],
|
|
106
|
+
'max-height': ['none'],
|
|
107
|
+
'max-width': ['none'],
|
|
108
|
+
'min-height': ['auto', '0px'],
|
|
109
|
+
'min-width': ['auto', '0px'],
|
|
110
|
+
'object-fit': ['fill'],
|
|
111
|
+
opacity: ['1'],
|
|
112
|
+
overflow: ['visible'],
|
|
113
|
+
'row-gap': ['normal'],
|
|
114
|
+
'text-indent': ['0px'],
|
|
115
|
+
width: ['auto']
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const ZERO_LENGTH_PROPERTIES = [
|
|
119
|
+
'border-bottom-left-radius',
|
|
120
|
+
'border-bottom-right-radius',
|
|
121
|
+
'border-top-left-radius',
|
|
122
|
+
'border-top-right-radius',
|
|
123
|
+
...SIDES.map((side) => `padding-${side}` as const),
|
|
124
|
+
...SIDES.map((side) => `margin-${side}` as const)
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
const TEXT_DECORATION_DETAILS = [
|
|
128
|
+
'text-decoration-color',
|
|
129
|
+
'text-decoration-style',
|
|
130
|
+
'text-decoration-thickness',
|
|
131
|
+
'text-underline-offset'
|
|
132
|
+
]
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The style without values that change nothing on import: defaults, borders without a style,
|
|
136
|
+
* offsets of boxes in normal flow, and decoration details of undecorated text.
|
|
137
|
+
*/
|
|
138
|
+
export function withoutImpliedValues(style: Record<string, string>): Record<string, string> {
|
|
139
|
+
const dropped = new Set<string>()
|
|
140
|
+
for (const [property, values] of Object.entries(IMPLIED_VALUES)) {
|
|
141
|
+
if (values.includes(ownValue(style, property) ?? '')) dropped.add(property)
|
|
142
|
+
}
|
|
143
|
+
for (const property of ZERO_LENGTH_PROPERTIES) {
|
|
144
|
+
if (style[property] === '0px') dropped.add(property)
|
|
145
|
+
}
|
|
146
|
+
for (const side of SIDES) {
|
|
147
|
+
const borderStyle = ownValue(style, `border-${side}-style`)
|
|
148
|
+
if (borderStyle !== undefined && borderStyle !== 'none' && borderStyle !== 'hidden') continue
|
|
149
|
+
for (const part of ['style', 'width', 'color']) dropped.add(`border-${side}-${part}`)
|
|
150
|
+
}
|
|
151
|
+
// Sticky boxes sit in normal flow until the page scrolls, which a still capture never does.
|
|
152
|
+
const position = ownValue(style, 'position')
|
|
153
|
+
const inFlow = position === undefined || position === 'static' || position === 'sticky'
|
|
154
|
+
if (inFlow) dropped.add('position')
|
|
155
|
+
for (const side of SIDES) {
|
|
156
|
+
if (inFlow || style[side] === 'auto') dropped.add(side)
|
|
157
|
+
}
|
|
158
|
+
const decoration = ownValue(style, 'text-decoration-line')
|
|
159
|
+
if (decoration === undefined || decoration === 'none') {
|
|
160
|
+
for (const property of TEXT_DECORATION_DETAILS) dropped.add(property)
|
|
161
|
+
}
|
|
162
|
+
return Object.fromEntries(Object.entries(style).filter(([property]) => !dropped.has(property)))
|
|
163
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Where an element sat on the page, in CSS pixels from the top left of the captured root. */
|
|
2
|
+
export interface WebCaptureBox {
|
|
3
|
+
x: number
|
|
4
|
+
y: number
|
|
5
|
+
width: number
|
|
6
|
+
height: number
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A run of text as the page held it; the importer collapses whitespace as CSS does. */
|
|
10
|
+
export interface WebCaptureText {
|
|
11
|
+
type: 'text'
|
|
12
|
+
text: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* An element with the styles the page computed for it. The shape is the styled DOM that
|
|
17
|
+
* `@pairdraw/dom-css` builds layers from, so a capture needs no CSS runtime to import.
|
|
18
|
+
*/
|
|
19
|
+
export interface WebCaptureElement {
|
|
20
|
+
type: 'element'
|
|
21
|
+
tagName: string
|
|
22
|
+
attrs: Record<string, string>
|
|
23
|
+
computedStyle: Record<string, string>
|
|
24
|
+
box?: WebCaptureBox
|
|
25
|
+
children: WebCaptureNode[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type WebCaptureNode = WebCaptureElement | WebCaptureText
|
package/src/urls.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])
|
|
2
|
+
const IMAGE_PROTOCOLS = new Set(['http:', 'https:'])
|
|
3
|
+
/** Raster images the canvas decodes; SVG is rasterized by the capturer instead. */
|
|
4
|
+
const DATA_IMAGE =
|
|
5
|
+
/^data:image\/(?:png|jpeg|gif|webp|avif|bmp|x-icon|vnd\.microsoft\.icon);base64,/i
|
|
6
|
+
|
|
7
|
+
function resolve(value: string, base: string | undefined): URL | null {
|
|
8
|
+
try {
|
|
9
|
+
return new URL(value.trim(), base)
|
|
10
|
+
} catch {
|
|
11
|
+
return null
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A link a layer may keep: http, https, or mailto, resolved against the page; never script. */
|
|
16
|
+
export function safeLinkURL(value: string, base?: string): string | null {
|
|
17
|
+
const url = resolve(value, base)
|
|
18
|
+
return url && LINK_PROTOCOLS.has(url.protocol) ? url.href : null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** An image source a layer may keep: an inlined raster image, or an http(s) address. */
|
|
22
|
+
export function safeImageSource(value: string, base?: string): string | null {
|
|
23
|
+
const trimmed = value.trim()
|
|
24
|
+
if (DATA_IMAGE.test(trimmed)) return trimmed
|
|
25
|
+
const url = resolve(trimmed, base)
|
|
26
|
+
return url && IMAGE_PROTOCOLS.has(url.protocol) ? url.href : null
|
|
27
|
+
}
|