@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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/dist/capturer.d.ts +56 -0
  4. package/dist/capturer.d.ts.map +1 -0
  5. package/dist/capturer.js +3 -0
  6. package/dist/chunks/capturer/clipboard.js +575 -0
  7. package/dist/chunks/capturer/clipboard.js.map +1 -0
  8. package/dist/chunks/capturer/fonts.js +25 -0
  9. package/dist/chunks/capturer/fonts.js.map +1 -0
  10. package/dist/chunks/capturer/images.js +113 -0
  11. package/dist/chunks/capturer/images.js.map +1 -0
  12. package/dist/chunks/capturer/index.js +445 -0
  13. package/dist/chunks/capturer/index.js.map +1 -0
  14. package/dist/chunks/design-document.js +251 -0
  15. package/dist/chunks/design-document.js.map +1 -0
  16. package/dist/chunks/index.js +125 -0
  17. package/dist/chunks/index.js.map +1 -0
  18. package/dist/clipboard.d.ts +106 -0
  19. package/dist/clipboard.d.ts.map +1 -0
  20. package/dist/index.d.ts +110 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +4 -0
  23. package/package.json +43 -4
  24. package/src/capturer/clipboard.ts +59 -0
  25. package/src/capturer/fonts.ts +30 -0
  26. package/src/capturer/images.ts +153 -0
  27. package/src/capturer/index.ts +170 -0
  28. package/src/capturer/page.ts +51 -0
  29. package/src/capturer/svg.ts +79 -0
  30. package/src/capturer/walk.ts +283 -0
  31. package/src/clipboard.ts +85 -0
  32. package/src/design-document.ts +267 -0
  33. package/src/format.ts +17 -0
  34. package/src/html.ts +44 -0
  35. package/src/index.ts +41 -0
  36. package/src/limits.ts +23 -0
  37. package/src/parse.ts +165 -0
  38. package/src/record.ts +10 -0
  39. package/src/sanitize.ts +134 -0
  40. package/src/schema.ts +75 -0
  41. package/src/styles.ts +163 -0
  42. package/src/types.ts +28 -0
  43. package/src/urls.ts +27 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clipboard.js","names":[],"sources":["../../../src/record.ts","../../../src/html.ts","../../../src/limits.ts","../../../src/schema.ts","../../../src/styles.ts","../../../src/urls.ts","../../../src/parse.ts","../../../src/clipboard.ts","../../../src/capturer/clipboard.ts"],"sourcesContent":["/**\n * The value a style or attribute record sets for `key`, or undefined when it sets none. Records\n * are typed as setting every key, which they do not.\n */\nexport function ownValue(\n record: Readonly<Record<string, string>>,\n key: string\n): string | undefined {\n return Object.hasOwn(record, key) ? record[key] : undefined\n}\n","import { escapeAttribute, escapeText } from 'entities'\n\nimport type { WebCapture } from './format'\nimport { ownValue } from './record'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\n\nconst VOID_TAGS = new Set(['area', 'br', 'col', 'hr', 'img', 'input', 'source', 'wbr'])\n\nexport interface WebCaptureHTMLOptions {\n /** Keep inlined images; without them an image keeps only its size and description. */\n images?: boolean\n}\n\nfunction styleAttribute(style: Record<string, string>): string {\n return Object.entries(style)\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction attributes(element: WebCaptureElement, options: WebCaptureHTMLOptions): string {\n const attrs: Record<string, string> = { ...element.attrs }\n if (options.images === false && ownValue(attrs, 'src')?.startsWith('data:')) delete attrs.src\n const style = styleAttribute(element.computedStyle)\n if (style) attrs.style = style\n return Object.entries(attrs)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n}\n\nfunction serialize(node: WebCaptureNode, options: WebCaptureHTMLOptions): string {\n if (node.type === 'text') return escapeText(node.text)\n const open = `<${node.tagName}${attributes(node, options)}>`\n if (VOID_TAGS.has(node.tagName)) return open\n const children = node.children.map((child) => serialize(child, options)).join('')\n return `${open}${children}</${node.tagName}>`\n}\n\n/**\n * The capture as static HTML whose elements carry their computed styles inline, for\n * applications that read clipboard HTML but not the capture itself.\n */\nexport function webCaptureToHTML(capture: WebCapture, options: WebCaptureHTMLOptions = {}): string {\n return serialize(capture.root, options)\n}\n","/** The capture format identifier that clipboard payloads and files carry. */\nexport const WEB_CAPTURE_FORMAT = 'pairdraw/web-capture'\n\n/** The capture format version this package writes and reads. */\nexport const WEB_CAPTURE_VERSION = 1\n\n/** Elements one capture holds at most; a capturer stops descending once it reaches this. */\nexport const MAX_CAPTURE_ELEMENTS = 20_000\n\n/** How deep a capture nests; deeper elements are left out, as browsers rarely draw them. */\nexport const MAX_CAPTURE_DEPTH = 256\n\n/** Bytes one inlined image may take; a larger image stays a link the importer records. */\nexport const MAX_CAPTURE_IMAGE_BYTES = 8 * 1024 * 1024\n\n/** Bytes all inlined images of a capture take together. */\nexport const MAX_CAPTURE_IMAGES_BYTES = 48 * 1024 * 1024\n\n/** Characters of serialized capture JSON a reader accepts, images included. */\nexport const MAX_CAPTURE_JSON_LENGTH = 96 * 1024 * 1024\n\n/** Characters of plain web HTML a paste styles; a larger fragment is refused. */\nexport const MAX_WEB_HTML_LENGTH = 8 * 1024 * 1024\n","import * as v from 'valibot'\n\nimport { MAX_CAPTURE_JSON_LENGTH, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from './limits'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\n\nconst finiteSchema = v.pipe(v.number(), v.finite())\nconst sizeSchema = v.pipe(v.number(), v.finite(), v.minValue(0))\nconst shortStringSchema = v.pipe(v.string(), v.maxLength(4096))\n\nconst webCaptureBoxSchema = v.object({\n x: finiteSchema,\n y: finiteSchema,\n width: sizeSchema,\n height: sizeSchema\n})\n\nconst webCaptureTextSchema = v.object({\n type: v.literal('text'),\n text: v.pipe(v.string(), v.maxLength(1_000_000))\n})\n\n/** HTML and SVG tag names, lowercase as a capturer writes them. */\nconst tagNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]{0,63}$/))\n/** Attribute names; which of them an import keeps is decided when a capture is read. */\nconst attributeNameSchema = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9:_-]{0,63}$/))\n/** Attribute values hold inlined images as data URLs, so they may be large. */\nconst attributeValueSchema = v.pipe(v.string(), v.maxLength(MAX_CAPTURE_JSON_LENGTH))\nconst propertyNameSchema = v.pipe(v.string(), v.regex(/^-?[a-z][a-z-]{0,63}$/))\n\nconst webCaptureElementSchema: v.GenericSchema<unknown, WebCaptureElement> = v.object({\n type: v.literal('element'),\n tagName: tagNameSchema,\n attrs: v.record(attributeNameSchema, attributeValueSchema),\n computedStyle: v.record(propertyNameSchema, shortStringSchema),\n box: v.optional(webCaptureBoxSchema),\n children: v.array(v.lazy(() => webCaptureNodeSchema))\n})\n\nconst webCaptureNodeSchema: v.GenericSchema<unknown, WebCaptureNode> = v.union([\n webCaptureTextSchema,\n webCaptureElementSchema\n])\n\nexport const webCaptureFontSchema = v.object({\n family: shortStringSchema,\n weight: shortStringSchema,\n style: shortStringSchema\n})\n\nexport const webCaptureViewportSchema = v.object({\n width: sizeSchema,\n height: sizeSchema,\n devicePixelRatio: v.pipe(v.number(), v.finite(), v.minValue(0))\n})\n\nconst webCaptureSourceSchema = v.object({\n url: v.optional(shortStringSchema),\n title: v.optional(shortStringSchema)\n})\n\n/** A page or element captured with the styles the browser computed for it. */\nexport const webCaptureSchema = v.object({\n format: v.literal(WEB_CAPTURE_FORMAT),\n version: v.literal(WEB_CAPTURE_VERSION),\n /** Whether a whole page or one element of it was captured. */\n scope: v.picklist(['page', 'element']),\n source: webCaptureSourceSchema,\n /** When the capture was made, as an ISO 8601 timestamp. */\n capturedAt: shortStringSchema,\n viewport: webCaptureViewportSchema,\n root: webCaptureElementSchema,\n fonts: v.array(webCaptureFontSchema),\n /** Whether the capturer stopped at its element limit, leaving later content out. */\n truncated: v.boolean()\n})\n","import { ownValue } from './record'\n\n/**\n * The computed properties a capture keeps for each element: those `@pairdraw/dom-css` builds\n * layers from, plus margins, which a capture turns into spacing when it is imported.\n */\nexport const CAPTURED_STYLE_PROPERTIES = [\n 'align-items',\n 'align-self',\n 'aspect-ratio',\n 'background-color',\n 'border-bottom-color',\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-bottom-style',\n 'border-bottom-width',\n 'border-left-color',\n 'border-left-style',\n 'border-left-width',\n 'border-right-color',\n 'border-right-style',\n 'border-right-width',\n 'border-top-color',\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-top-style',\n 'border-top-width',\n 'bottom',\n 'box-shadow',\n 'box-sizing',\n 'color',\n 'column-gap',\n 'display',\n 'flex-direction',\n 'flex-wrap',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'gap',\n 'height',\n 'justify-content',\n 'left',\n 'letter-spacing',\n 'line-height',\n 'margin-bottom',\n 'margin-left',\n 'margin-right',\n 'margin-top',\n 'max-height',\n 'max-width',\n 'min-height',\n 'min-width',\n 'object-fit',\n 'opacity',\n 'overflow',\n 'padding-bottom',\n 'padding-left',\n 'padding-right',\n 'padding-top',\n 'position',\n 'right',\n 'row-gap',\n 'text-align',\n 'text-decoration-color',\n 'text-decoration-line',\n 'text-decoration-style',\n 'text-decoration-thickness',\n 'text-indent',\n 'text-shadow',\n 'text-transform',\n 'text-underline-offset',\n 'top',\n 'white-space',\n 'width'\n] as const\n\nexport type CapturedStyleProperty = (typeof CAPTURED_STYLE_PROPERTIES)[number]\n\nconst CAPTURED = new Set<string>(CAPTURED_STYLE_PROPERTIES)\n\n/** Whether a capture keeps this property; others are dropped when a capture is read. */\nexport function isCapturedStyleProperty(property: string): property is CapturedStyleProperty {\n return CAPTURED.has(property)\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const\n\n/**\n * Values the importer reads exactly as it reads a missing property, so leaving them out only\n * makes the capture smaller. Inherited text properties are always kept: a nested run reads\n * a missing one from its parent, which differs from the value the page computed.\n */\nconst IMPLIED_VALUES: Partial<Record<CapturedStyleProperty, readonly string[]>> = {\n 'align-items': ['normal'],\n 'align-self': ['auto'],\n 'aspect-ratio': ['auto'],\n 'background-color': ['rgba(0, 0, 0, 0)', 'transparent'],\n 'box-shadow': ['none'],\n 'column-gap': ['normal'],\n 'flex-direction': ['row'],\n 'flex-wrap': ['nowrap'],\n gap: ['normal'],\n height: ['auto'],\n 'justify-content': ['normal'],\n 'max-height': ['none'],\n 'max-width': ['none'],\n 'min-height': ['auto', '0px'],\n 'min-width': ['auto', '0px'],\n 'object-fit': ['fill'],\n opacity: ['1'],\n overflow: ['visible'],\n 'row-gap': ['normal'],\n 'text-indent': ['0px'],\n width: ['auto']\n}\n\nconst ZERO_LENGTH_PROPERTIES = [\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-top-left-radius',\n 'border-top-right-radius',\n ...SIDES.map((side) => `padding-${side}` as const),\n ...SIDES.map((side) => `margin-${side}` as const)\n]\n\nconst TEXT_DECORATION_DETAILS = [\n 'text-decoration-color',\n 'text-decoration-style',\n 'text-decoration-thickness',\n 'text-underline-offset'\n]\n\n/**\n * The style without values that change nothing on import: defaults, borders without a style,\n * offsets of boxes in normal flow, and decoration details of undecorated text.\n */\nexport function withoutImpliedValues(style: Record<string, string>): Record<string, string> {\n const dropped = new Set<string>()\n for (const [property, values] of Object.entries(IMPLIED_VALUES)) {\n if (values.includes(ownValue(style, property) ?? '')) dropped.add(property)\n }\n for (const property of ZERO_LENGTH_PROPERTIES) {\n if (style[property] === '0px') dropped.add(property)\n }\n for (const side of SIDES) {\n const borderStyle = ownValue(style, `border-${side}-style`)\n if (borderStyle !== undefined && borderStyle !== 'none' && borderStyle !== 'hidden') continue\n for (const part of ['style', 'width', 'color']) dropped.add(`border-${side}-${part}`)\n }\n // Sticky boxes sit in normal flow until the page scrolls, which a still capture never does.\n const position = ownValue(style, 'position')\n const inFlow = position === undefined || position === 'static' || position === 'sticky'\n if (inFlow) dropped.add('position')\n for (const side of SIDES) {\n if (inFlow || style[side] === 'auto') dropped.add(side)\n }\n const decoration = ownValue(style, 'text-decoration-line')\n if (decoration === undefined || decoration === 'none') {\n for (const property of TEXT_DECORATION_DETAILS) dropped.add(property)\n }\n return Object.fromEntries(Object.entries(style).filter(([property]) => !dropped.has(property)))\n}\n","const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])\nconst IMAGE_PROTOCOLS = new Set(['http:', 'https:'])\n/** Raster images the canvas decodes; SVG is rasterized by the capturer instead. */\nconst DATA_IMAGE =\n /^data:image\\/(?:png|jpeg|gif|webp|avif|bmp|x-icon|vnd\\.microsoft\\.icon);base64,/i\n\nfunction resolve(value: string, base: string | undefined): URL | null {\n try {\n return new URL(value.trim(), base)\n } catch {\n return null\n }\n}\n\n/** A link a layer may keep: http, https, or mailto, resolved against the page; never script. */\nexport function safeLinkURL(value: string, base?: string): string | null {\n const url = resolve(value, base)\n return url && LINK_PROTOCOLS.has(url.protocol) ? url.href : null\n}\n\n/** An image source a layer may keep: an inlined raster image, or an http(s) address. */\nexport function safeImageSource(value: string, base?: string): string | null {\n const trimmed = value.trim()\n if (DATA_IMAGE.test(trimmed)) return trimmed\n const url = resolve(trimmed, base)\n return url && IMAGE_PROTOCOLS.has(url.protocol) ? url.href : null\n}\n","import * as v from 'valibot'\n\nimport type { WebCapture, WebCaptureReadResult } from './format'\nimport {\n MAX_CAPTURE_DEPTH,\n MAX_CAPTURE_ELEMENTS,\n MAX_CAPTURE_JSON_LENGTH,\n WEB_CAPTURE_FORMAT,\n WEB_CAPTURE_VERSION\n} from './limits'\nimport { webCaptureSchema } from './schema'\nimport { isCapturedStyleProperty } from './styles'\nimport type { WebCaptureElement, WebCaptureNode } from './types'\nimport { safeImageSource, safeLinkURL } from './urls'\n\n/** Read first, so a capture from a newer capturer is told apart from a damaged one. */\nconst captureHeaderSchema = v.looseObject({\n format: v.literal(WEB_CAPTURE_FORMAT),\n version: v.number()\n})\n\n/** Attributes a layer can use: names, links, images, and accessible labels. */\nconst KEPT_ATTRIBUTES = new Set([\n 'id',\n 'class',\n 'href',\n 'src',\n 'alt',\n 'title',\n 'role',\n 'aria-label',\n 'lang',\n 'dir'\n])\n\n/** Elements that never draw, whatever a capture claims. */\nconst DROPPED_TAGS = new Set([\n 'script',\n 'style',\n 'link',\n 'meta',\n 'head',\n 'title',\n 'template',\n 'noscript',\n 'iframe',\n 'frame',\n 'object',\n 'embed',\n 'base'\n])\n\n/**\n * JSON nesting a capture within `MAX_CAPTURE_DEPTH` takes: an object and a `children` array per\n * element, the capture around the root, and the records of the deepest element, with room to\n * spare. Deeper values are refused before validation, whose recursion they could overflow.\n */\nconst MAX_JSON_NESTING = 2 * MAX_CAPTURE_DEPTH + 16\n\n/** Whether a value nests deeper than `limit`, walked without recursion; a cycle counts as deep. */\nfunction nestsDeeperThan(value: unknown, limit: number): boolean {\n const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }]\n for (let next = pending.pop(); next; next = pending.pop()) {\n if (typeof next.value !== 'object' || next.value === null) continue\n if (next.depth >= limit) return true\n const depth = next.depth + 1\n for (const child of Object.values(next.value)) pending.push({ value: child, depth })\n }\n return false\n}\n\ninterface Budget {\n elements: number\n truncated: boolean\n}\n\nfunction keptAttributes(\n attrs: Record<string, string>,\n base: string | undefined\n): Record<string, string> {\n const kept: Record<string, string> = {}\n for (const [name, value] of Object.entries(attrs)) {\n if (!KEPT_ATTRIBUTES.has(name)) continue\n if (name === 'href') {\n const href = safeLinkURL(value, base)\n if (href) kept.href = href\n } else if (name === 'src') {\n const src = safeImageSource(value, base)\n if (src) kept.src = src\n } else {\n kept[name] = value\n }\n }\n return kept\n}\n\nfunction keptStyle(style: Record<string, string>): Record<string, string> {\n return Object.fromEntries(\n Object.entries(style).filter(([property]) => isCapturedStyleProperty(property))\n )\n}\n\nfunction normalizeElement(\n element: WebCaptureElement,\n base: string | undefined,\n depth: number,\n budget: Budget\n): WebCaptureElement {\n const children: WebCaptureNode[] = []\n for (const child of element.children) {\n if (child.type === 'text') {\n children.push(child)\n continue\n }\n if (DROPPED_TAGS.has(child.tagName)) continue\n if (depth + 1 > MAX_CAPTURE_DEPTH || budget.elements >= MAX_CAPTURE_ELEMENTS) {\n budget.truncated = true\n continue\n }\n budget.elements++\n children.push(normalizeElement(child, base, depth + 1, budget))\n }\n return {\n type: 'element',\n tagName: element.tagName,\n attrs: keptAttributes(element.attrs, base),\n computedStyle: keptStyle(element.computedStyle),\n ...(element.box ? { box: element.box } : {}),\n children\n }\n}\n\n/**\n * A capture as an import may use it: only the attributes and properties layers read, links\n * limited to http, https, and mailto, images limited to raster data URLs and http(s) addresses,\n * and at most `MAX_CAPTURE_ELEMENTS` elements. Captures come from any page, so every reader\n * goes through this.\n */\nexport function normalizeWebCapture(capture: WebCapture): WebCapture {\n const budget: Budget = { elements: 1, truncated: false }\n const base = capture.source.url\n const root = normalizeElement(capture.root, base, 0, budget)\n return { ...capture, root, truncated: capture.truncated || budget.truncated }\n}\n\n/** Reads a capture that is already a value, such as one a capturer handed over. */\nexport function readWebCapture(value: unknown): WebCaptureReadResult {\n if (nestsDeeperThan(value, MAX_JSON_NESTING)) return { ok: false, error: 'invalid' }\n const header = v.safeParse(captureHeaderSchema, value)\n if (!header.success) return { ok: false, error: 'invalid' }\n if (header.output.version !== WEB_CAPTURE_VERSION) {\n return { ok: false, error: 'unsupported-version' }\n }\n const parsed = v.safeParse(webCaptureSchema, value)\n if (!parsed.success) return { ok: false, error: 'invalid' }\n return { ok: true, capture: normalizeWebCapture(parsed.output) }\n}\n\n/** Reads a capture serialized as JSON, as files and clipboard payloads hold it. */\nexport function parseWebCapture(text: string): WebCaptureReadResult {\n if (text.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }\n const json = v.safeParse(v.pipe(v.string(), v.parseJson()), text)\n if (!json.success) return { ok: false, error: 'invalid' }\n return readWebCapture(json.output)\n}\n","import { compact } from 'es-toolkit'\nimport { Inflate, deflateSync, strToU8 } from 'fflate'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\n\nimport type { WebCapture, WebCaptureReadResult } from './format'\nimport { webCaptureToHTML } from './html'\nimport { MAX_CAPTURE_JSON_LENGTH } from './limits'\nimport { normalizeWebCapture, parseWebCapture } from './parse'\n\n/**\n * Clipboard HTML carries a capture between these markers, as Base64 of the DEFLATE-compressed\n * JSON, the way Figma and Pairdraw carry their layers in an HTML comment.\n */\nexport const WEB_CAPTURE_CLIPBOARD_START = '<!--(pairdraw-web-capture)'\nexport const WEB_CAPTURE_CLIPBOARD_END = '(/pairdraw-web-capture)-->'\n\n/** Compressed bytes inflated per step, so an oversized payload stops early. */\nconst INFLATE_STEP = 16 * 1024\n\nexport interface WebCaptureClipboardPayload {\n /** The capture in markers, followed by its content as styled HTML for other applications. */\n html: string\n /** The page's title and address, for applications that only read text. */\n text: string\n}\n\n/** What the clipboard holds after copying a capture: the capture itself and a readable copy. */\nexport function encodeWebCaptureClipboard(captured: WebCapture): WebCaptureClipboardPayload {\n const capture = normalizeWebCapture(captured)\n const compressed = deflateSync(strToU8(JSON.stringify(capture)), { level: 6 })\n const marker = `${WEB_CAPTURE_CLIPBOARD_START}${fromUint8Array(compressed)}${WEB_CAPTURE_CLIPBOARD_END}`\n const html = `<meta charset=\"utf-8\">${marker}${webCaptureToHTML(capture, { images: false })}`\n const text = compact([capture.source.title, capture.source.url]).join('\\n')\n return { html, text }\n}\n\nfunction markedPayload(html: string): string | null {\n const start = html.indexOf(WEB_CAPTURE_CLIPBOARD_START)\n if (start === -1) return null\n const from = start + WEB_CAPTURE_CLIPBOARD_START.length\n const end = html.indexOf(WEB_CAPTURE_CLIPBOARD_END, from)\n return end === -1 ? null : html.slice(from, end)\n}\n\n/** Whether clipboard HTML holds a complete capture marker. */\nexport function hasWebCaptureClipboardMarker(html: string): boolean {\n return markedPayload(html) !== null\n}\n\n/** Inflates at most `MAX_CAPTURE_JSON_LENGTH` bytes of text. */\nfunction inflateText(bytes: Uint8Array): { text: string } | 'invalid' | 'too-large' {\n const decoder = new TextDecoder()\n // An object, since the inflate callback changes it where control flow analysis cannot see.\n const state = { text: '', length: 0, overflow: false }\n const inflate = new Inflate((chunk) => {\n state.length += chunk.length\n if (state.length > MAX_CAPTURE_JSON_LENGTH) state.overflow = true\n else state.text += decoder.decode(chunk, { stream: true })\n })\n try {\n for (let offset = 0; offset < bytes.length; offset += INFLATE_STEP) {\n if (state.overflow) break\n const end = offset + INFLATE_STEP\n inflate.push(bytes.subarray(offset, end), end >= bytes.length)\n }\n } catch {\n return 'invalid'\n }\n return state.overflow ? 'too-large' : { text: state.text + decoder.decode() }\n}\n\n/**\n * The capture clipboard HTML holds, or null when it holds none. Clipboard HTML is writable by\n * any page, so the payload is size-limited, validated, and normalized before it is returned.\n */\nexport function readWebCaptureClipboard(html: string): WebCaptureReadResult | null {\n const payload = markedPayload(html)\n if (payload === null) return null\n const encoded = payload.trim()\n if (encoded.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }\n if (!isValid(encoded)) return { ok: false, error: 'invalid' }\n const inflated = inflateText(toUint8Array(encoded))\n if (typeof inflated === 'string') return { ok: false, error: inflated }\n return parseWebCapture(inflated.text)\n}\n","import { encodeWebCaptureClipboard, type WebCaptureClipboardPayload } from '#web-capture/clipboard'\nimport type { WebCapture } from '#web-capture/format'\n\n/** The part of the asynchronous clipboard a capture write uses. */\nexport type CaptureClipboard = Pick<Clipboard, 'write'>\n\nexport interface WriteCaptureClipboardOptions {\n /** The clipboard to write; the page's own by default. */\n clipboard?: CaptureClipboard\n /** Builds a clipboard item; the page's `ClipboardItem` by default. */\n createItem?: (items: Record<string, Promise<Blob>>) => ClipboardItem\n}\n\n/** Thrown when the page has no asynchronous clipboard, which only secure pages offer. */\nexport class CaptureClipboardUnavailableError extends Error {\n constructor() {\n super('Copying a capture needs a page served over HTTPS')\n this.name = 'CaptureClipboardUnavailableError'\n }\n}\n\nfunction isPayload(\n value: WebCapture | WebCaptureClipboardPayload\n): value is WebCaptureClipboardPayload {\n return 'html' in value && 'text' in value\n}\n\n/**\n * Copies a capture so it pastes into a Pairdraw canvas, as HTML for Pairdraw and other\n * applications and as the page's title and address for plain text. Pass the capture's promise\n * straight from the click that asked for it: the write starts inside that click and resolves\n * its data later, so a capture that takes a while still counts as the click's own.\n */\nexport async function writeWebCaptureClipboard(\n capture:\n | WebCapture\n | WebCaptureClipboardPayload\n | Promise<WebCapture | WebCaptureClipboardPayload>,\n options: WriteCaptureClipboardOptions = {}\n): Promise<void> {\n const clipboard =\n options.clipboard ?? (typeof navigator === 'undefined' ? undefined : navigator.clipboard)\n const createItem =\n options.createItem ??\n (typeof ClipboardItem === 'undefined'\n ? undefined\n : (items: Record<string, Promise<Blob>>) => new ClipboardItem(items))\n // `navigator.clipboard` is missing outside secure contexts.\n if (!clipboard || !createItem) throw new CaptureClipboardUnavailableError()\n const payload = Promise.resolve(capture).then((value) =>\n isPayload(value) ? value : encodeWebCaptureClipboard(value)\n )\n await clipboard.write([\n createItem({\n 'text/html': payload.then((value) => new Blob([value.html], { type: 'text/html' })),\n 'text/plain': payload.then((value) => new Blob([value.text], { type: 'text/plain' }))\n })\n ])\n}\n"],"mappings":";;;;;;;;;;AAIA,SAAgB,SACd,QACA,KACoB;CACpB,OAAO,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,KAAA;AACpD;;;ACHA,MAAM,4BAAY,IAAI,IAAI;CAAC;CAAQ;CAAM;CAAO;CAAM;CAAO;CAAS;CAAU;AAAK,CAAC;AAOtF,SAAS,eAAe,OAAuC;CAC7D,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,SAAS,WAAW,SAA4B,SAAwC;CACtF,MAAM,QAAgC,EAAE,GAAG,QAAQ,MAAM;CACzD,IAAI,QAAQ,WAAW,SAAS,SAAS,OAAO,KAAK,CAAC,EAAE,WAAW,OAAO,GAAG,OAAO,MAAM;CAC1F,MAAM,QAAQ,eAAe,QAAQ,aAAa;CAClD,IAAI,OAAO,MAAM,QAAQ;CACzB,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,KAAK,CAAC,MAAM,WAAW,IAAI,KAAK,IAAI,gBAAgB,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tC;;;;ACtEA,IAAa,mCAAb,cAAsD,MAAM;CAC1D,cAAc;EACZ,MAAM,kDAAkD;EACxD,KAAK,OAAO;CACd;AACF;AAEA,SAAS,UACP,OACqC;CACrC,OAAO,UAAU,SAAS,UAAU;AACtC;;;;;;;AAQA,eAAsB,yBACpB,SAIA,UAAwC,CAAC,GAC1B;CACf,MAAM,YACJ,QAAQ,cAAc,OAAO,cAAc,cAAc,KAAA,IAAY,UAAU;CACjF,MAAM,aACJ,QAAQ,eACP,OAAO,kBAAkB,cACtB,KAAA,KACC,UAAyC,IAAI,cAAc,KAAK;CAEvE,IAAI,CAAC,aAAa,CAAC,YAAY,MAAM,IAAI,iCAAiC;CAC1E,MAAM,UAAU,QAAQ,QAAQ,OAAO,CAAC,CAAC,MAAM,UAC7C,UAAU,KAAK,IAAI,QAAQ,0BAA0B,KAAK,CAC5D;CACA,MAAM,UAAU,MAAM,CACpB,WAAW;EACT,aAAa,QAAQ,MAAM,UAAU,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,EAAE,MAAM,YAAY,CAAC,CAAC;EAClF,cAAc,QAAQ,MAAM,UAAU,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,EAAE,MAAM,aAAa,CAAC,CAAC;CACtF,CAAC,CACH,CAAC;AACH"}
@@ -0,0 +1,25 @@
1
+ //#region src/capturer/fonts.ts
2
+ /** The family a browser tries first, without the quotes CSS may put around it. */
3
+ function primaryFontFamily(fontFamily) {
4
+ return (fontFamily.split(",")[0] ?? "").trim().replace(/^(['"])(.*)\1$/, "$2");
5
+ }
6
+ function createFontCollector() {
7
+ const fonts = /* @__PURE__ */ new Map();
8
+ return {
9
+ add(style) {
10
+ const family = primaryFontFamily(style.getPropertyValue("font-family"));
11
+ if (!family) return;
12
+ const font = {
13
+ family,
14
+ weight: style.getPropertyValue("font-weight") || "400",
15
+ style: style.getPropertyValue("font-style") || "normal"
16
+ };
17
+ fonts.set(`${font.family}|${font.weight}|${font.style}`, font);
18
+ },
19
+ list: () => [...fonts.values()]
20
+ };
21
+ }
22
+ //#endregion
23
+ export { createFontCollector };
24
+
25
+ //# sourceMappingURL=fonts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fonts.js","names":[],"sources":["../../../src/capturer/fonts.ts"],"sourcesContent":["import type { WebCaptureFont } from '#web-capture/format'\n\n/** The fonts a capture's text uses, so an importer knows which families to load. */\nexport interface FontCollector {\n add(style: CSSStyleDeclaration): void\n list(): WebCaptureFont[]\n}\n\n/** The family a browser tries first, without the quotes CSS may put around it. */\nfunction primaryFontFamily(fontFamily: string): string {\n const first = fontFamily.split(',')[0] ?? ''\n return first.trim().replace(/^(['\"])(.*)\\1$/, '$2')\n}\n\nexport function createFontCollector(): FontCollector {\n const fonts = new Map<string, WebCaptureFont>()\n return {\n add(style) {\n const family = primaryFontFamily(style.getPropertyValue('font-family'))\n if (!family) return\n const font = {\n family,\n weight: style.getPropertyValue('font-weight') || '400',\n style: style.getPropertyValue('font-style') || 'normal'\n }\n fonts.set(`${font.family}|${font.weight}|${font.style}`, font)\n },\n list: () => [...fonts.values()]\n }\n}\n"],"mappings":";;AASA,SAAS,kBAAkB,YAA4B;CAErD,QADc,WAAW,MAAM,GAAG,CAAC,CAAC,MAAM,GAAA,CAC7B,KAAK,CAAC,CAAC,QAAQ,kBAAkB,IAAI;AACpD;AAEA,SAAgB,sBAAqC;CACnD,MAAM,wBAAQ,IAAI,IAA4B;CAC9C,OAAO;EACL,IAAI,OAAO;GACT,MAAM,SAAS,kBAAkB,MAAM,iBAAiB,aAAa,CAAC;GACtE,IAAI,CAAC,QAAQ;GACb,MAAM,OAAO;IACX;IACA,QAAQ,MAAM,iBAAiB,aAAa,KAAK;IACjD,OAAO,MAAM,iBAAiB,YAAY,KAAK;GACjD;GACA,MAAM,IAAI,GAAG,KAAK,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK,SAAS,IAAI;EAC/D;EACA,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC;CAChC;AACF"}
@@ -0,0 +1,113 @@
1
+ import "./clipboard.js";
2
+ import { fromUint8Array } from "js-base64";
3
+ //#region src/capturer/images.ts
4
+ const RASTER_TYPES = /* @__PURE__ */ new Set([
5
+ "image/png",
6
+ "image/jpeg",
7
+ "image/gif",
8
+ "image/webp",
9
+ "image/avif",
10
+ "image/bmp",
11
+ "image/x-icon",
12
+ "image/vnd.microsoft.icon"
13
+ ]);
14
+ /** Larger scales add bytes but no detail a design layer can use. */
15
+ const MAX_RASTER_SCALE = 2;
16
+ /** Images fetched at once, so a long page does not flood the network. */
17
+ const CONCURRENT_FETCHES = 6;
18
+ function createLimiter(limit) {
19
+ let active = 0;
20
+ const waiting = [];
21
+ return async (task) => {
22
+ if (active >= limit) await new Promise((resolve) => {
23
+ waiting.push(resolve);
24
+ });
25
+ active++;
26
+ try {
27
+ return await task();
28
+ } finally {
29
+ active--;
30
+ waiting.shift()?.();
31
+ }
32
+ };
33
+ }
34
+ function createImageInliner(view, options = {}) {
35
+ const maxImageBytes = options.maxImageBytes ?? 8388608;
36
+ const maxTotalBytes = options.maxTotalBytes ?? 50331648;
37
+ const cache = /* @__PURE__ */ new Map();
38
+ const limit = createLimiter(CONCURRENT_FETCHES);
39
+ let totalBytes = 0;
40
+ /** Counts an image against the capture's budget; false when it does not fit. */
41
+ function reserve(bytes) {
42
+ if (bytes > maxImageBytes || totalBytes + bytes > maxTotalBytes) return false;
43
+ totalBytes += bytes;
44
+ return true;
45
+ }
46
+ function accept(dataURL) {
47
+ return reserve(Math.ceil(dataURL.length * 3 / 4)) ? dataURL : null;
48
+ }
49
+ async function rasterize(blob, size) {
50
+ const url = view.URL.createObjectURL(blob);
51
+ try {
52
+ const image = new view.Image();
53
+ image.src = url;
54
+ await image.decode();
55
+ const width = size?.width || image.naturalWidth;
56
+ const height = size?.height || image.naturalHeight;
57
+ if (!width || !height) return null;
58
+ const scale = Math.min(view.devicePixelRatio || 1, MAX_RASTER_SCALE);
59
+ const canvas = view.document.createElement("canvas");
60
+ canvas.width = Math.max(1, Math.round(width * scale));
61
+ canvas.height = Math.max(1, Math.round(height * scale));
62
+ const context = canvas.getContext("2d");
63
+ if (!context) return null;
64
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
65
+ return accept(canvas.toDataURL("image/png"));
66
+ } catch {
67
+ return null;
68
+ } finally {
69
+ view.URL.revokeObjectURL(url);
70
+ }
71
+ }
72
+ async function fromBlob(blob, size) {
73
+ if (blob.size > maxImageBytes) return null;
74
+ const type = blob.type.toLowerCase();
75
+ if (!RASTER_TYPES.has(type)) return rasterize(blob, size);
76
+ const bytes = new Uint8Array(await blob.arrayBuffer());
77
+ if (!reserve(bytes.length)) return null;
78
+ return `data:${type};base64,${fromUint8Array(bytes)}`;
79
+ }
80
+ async function fetchBlob(url) {
81
+ const response = await view.fetch(url, {
82
+ credentials: "same-origin",
83
+ signal: options.signal
84
+ }).catch(() => null);
85
+ if (response?.ok) return response.blob();
86
+ if (!options.fetchImage || url.startsWith("data:")) return null;
87
+ return options.fetchImage(url).catch(() => null);
88
+ }
89
+ function inline(url, size) {
90
+ const key = size ? `${url}#${size.width}x${size.height}` : url;
91
+ const cached = cache.get(key);
92
+ if (cached) return cached;
93
+ const task = limit(async () => {
94
+ options.signal?.throwIfAborted();
95
+ const blob = await fetchBlob(url);
96
+ return blob ? fromBlob(blob, size) : null;
97
+ }).catch(() => null);
98
+ cache.set(key, task);
99
+ return task;
100
+ }
101
+ function rasterizeSVG(markup, size) {
102
+ return rasterize(new view.Blob([markup], { type: "image/svg+xml" }), size);
103
+ }
104
+ return {
105
+ inline,
106
+ rasterizeSVG,
107
+ accept
108
+ };
109
+ }
110
+ //#endregion
111
+ export { createImageInliner };
112
+
113
+ //# sourceMappingURL=images.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.js","names":[],"sources":["../../../src/capturer/images.ts"],"sourcesContent":["import { MAX_CAPTURE_IMAGE_BYTES, MAX_CAPTURE_IMAGES_BYTES } from '#web-capture/limits'\nimport { fromUint8Array } from 'js-base64'\n\n/**\n * Fetches an image the page itself may not read, such as one from another site without CORS\n * headers. An extension passes one that fetches with its own host permission.\n */\nexport type CaptureImageFetcher = (url: string) => Promise<Blob | null>\n\n/** The page's window, whose constructors and network the capturer uses. */\nexport type CaptureWindow = Window & typeof globalThis\n\nexport interface ImageInlinerOptions {\n fetchImage?: CaptureImageFetcher\n maxImageBytes?: number\n maxTotalBytes?: number\n signal?: AbortSignal\n}\n\nexport interface ImageSize {\n width: number\n height: number\n}\n\n/** Turns page images into raster data URLs, the only images a capture carries inside it. */\nexport interface ImageInliner {\n /** The image at `url` as a raster data URL, or null when it cannot be read or is too large. */\n inline(url: string, size?: ImageSize): Promise<string | null>\n /** SVG markup drawn at `size`, as a PNG data URL. */\n rasterizeSVG(markup: string, size: ImageSize): Promise<string | null>\n /** A data URL a page already produced, such as a canvas's, if the budget still allows it. */\n accept(dataURL: string): string | null\n}\n\nconst RASTER_TYPES = new Set([\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/x-icon',\n 'image/vnd.microsoft.icon'\n])\n\n/** Larger scales add bytes but no detail a design layer can use. */\nconst MAX_RASTER_SCALE = 2\n/** Images fetched at once, so a long page does not flood the network. */\nconst CONCURRENT_FETCHES = 6\n\nfunction createLimiter(limit: number) {\n let active = 0\n const waiting: Array<() => void> = []\n return async <T>(task: () => Promise<T>): Promise<T> => {\n if (active >= limit) {\n await new Promise<void>((resolve) => {\n waiting.push(resolve)\n })\n }\n active++\n try {\n return await task()\n } finally {\n active--\n waiting.shift()?.()\n }\n }\n}\n\nexport function createImageInliner(\n view: CaptureWindow,\n options: ImageInlinerOptions = {}\n): ImageInliner {\n const maxImageBytes = options.maxImageBytes ?? MAX_CAPTURE_IMAGE_BYTES\n const maxTotalBytes = options.maxTotalBytes ?? MAX_CAPTURE_IMAGES_BYTES\n const cache = new Map<string, Promise<string | null>>()\n const limit = createLimiter(CONCURRENT_FETCHES)\n let totalBytes = 0\n\n /** Counts an image against the capture's budget; false when it does not fit. */\n function reserve(bytes: number): boolean {\n if (bytes > maxImageBytes || totalBytes + bytes > maxTotalBytes) return false\n totalBytes += bytes\n return true\n }\n\n function accept(dataURL: string): string | null {\n // Base64 holds three bytes in four characters.\n return reserve(Math.ceil((dataURL.length * 3) / 4)) ? dataURL : null\n }\n\n async function rasterize(blob: Blob, size?: ImageSize): Promise<string | null> {\n const url = view.URL.createObjectURL(blob)\n try {\n const image = new view.Image()\n image.src = url\n await image.decode()\n const width = size?.width || image.naturalWidth\n const height = size?.height || image.naturalHeight\n if (!width || !height) return null\n const scale = Math.min(view.devicePixelRatio || 1, MAX_RASTER_SCALE)\n const canvas = view.document.createElement('canvas')\n canvas.width = Math.max(1, Math.round(width * scale))\n canvas.height = Math.max(1, Math.round(height * scale))\n const context = canvas.getContext('2d')\n if (!context) return null\n context.drawImage(image, 0, 0, canvas.width, canvas.height)\n return accept(canvas.toDataURL('image/png'))\n } catch {\n return null\n } finally {\n view.URL.revokeObjectURL(url)\n }\n }\n\n async function fromBlob(blob: Blob, size?: ImageSize): Promise<string | null> {\n if (blob.size > maxImageBytes) return null\n const type = blob.type.toLowerCase()\n if (!RASTER_TYPES.has(type)) return rasterize(blob, size)\n const bytes = new Uint8Array(await blob.arrayBuffer())\n if (!reserve(bytes.length)) return null\n return `data:${type};base64,${fromUint8Array(bytes)}`\n }\n\n async function fetchBlob(url: string): Promise<Blob | null> {\n // Another site's image without CORS headers fails here; the injected fetcher may read it.\n const response = await view\n .fetch(url, { credentials: 'same-origin', signal: options.signal })\n .catch(() => null)\n if (response?.ok) return response.blob()\n if (!options.fetchImage || url.startsWith('data:')) return null\n return options.fetchImage(url).catch(() => null)\n }\n\n function inline(url: string, size?: ImageSize): Promise<string | null> {\n const key = size ? `${url}#${size.width}x${size.height}` : url\n const cached = cache.get(key)\n if (cached) return cached\n const task = limit(async () => {\n options.signal?.throwIfAborted()\n const blob = await fetchBlob(url)\n return blob ? fromBlob(blob, size) : null\n }).catch(() => null)\n cache.set(key, task)\n return task\n }\n\n function rasterizeSVG(markup: string, size: ImageSize): Promise<string | null> {\n return rasterize(new view.Blob([markup], { type: 'image/svg+xml' }), size)\n }\n\n return { inline, rasterizeSVG, accept }\n}\n"],"mappings":";;;AAkCA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,mBAAmB;;AAEzB,MAAM,qBAAqB;AAE3B,SAAS,cAAc,OAAe;CACpC,IAAI,SAAS;CACb,MAAM,UAA6B,CAAC;CACpC,OAAO,OAAU,SAAuC;EACtD,IAAI,UAAU,OACZ,MAAM,IAAI,SAAe,YAAY;GACnC,QAAQ,KAAK,OAAO;EACtB,CAAC;EAEH;EACA,IAAI;GACF,OAAO,MAAM,KAAK;EACpB,UAAU;GACR;GACA,QAAQ,MAAM,CAAC,GAAG;EACpB;CACF;AACF;AAEA,SAAgB,mBACd,MACA,UAA+B,CAAC,GAClB;CACd,MAAM,gBAAgB,QAAQ,iBAAA;CAC9B,MAAM,gBAAgB,QAAQ,iBAAA;CAC9B,MAAM,wBAAQ,IAAI,IAAoC;CACtD,MAAM,QAAQ,cAAc,kBAAkB;CAC9C,IAAI,aAAa;;CAGjB,SAAS,QAAQ,OAAwB;EACvC,IAAI,QAAQ,iBAAiB,aAAa,QAAQ,eAAe,OAAO;EACxE,cAAc;EACd,OAAO;CACT;CAEA,SAAS,OAAO,SAAgC;EAE9C,OAAO,QAAQ,KAAK,KAAM,QAAQ,SAAS,IAAK,CAAC,CAAC,IAAI,UAAU;CAClE;CAEA,eAAe,UAAU,MAAY,MAA0C;EAC7E,MAAM,MAAM,KAAK,IAAI,gBAAgB,IAAI;EACzC,IAAI;GACF,MAAM,QAAQ,IAAI,KAAK,MAAM;GAC7B,MAAM,MAAM;GACZ,MAAM,MAAM,OAAO;GACnB,MAAM,QAAQ,MAAM,SAAS,MAAM;GACnC,MAAM,SAAS,MAA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