extract-refdoc 0.0.0-stage → 0.2.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/src/source.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * @fileoverview Getting a paper's text from wherever it lives, with the
3
+ * `extract-webpage` pipeline (the same extractor the browser extension's
4
+ * reading mode is ported from): web articles through its Readability /
5
+ * Mercury reading-mode extraction, PDFs through `extract-pdf`, `.docx`
6
+ * buffers, plus pasted text or markdown.
7
+ *
8
+ * Links are normalized first so the extractor gets the most structured copy:
9
+ * - arXiv `abs/` and `pdf/` links → the arXiv HTML render, which keeps the
10
+ * section headings (falls back to the PDF if arXiv has no HTML build);
11
+ * - bare DOIs → `https://doi.org/…`;
12
+ * - archive.org `details/` pages are passed through (the extractor reads
13
+ * the item page), and `web.archive.org` snapshots work as ordinary pages.
14
+ *
15
+ * The extractor is loaded lazily, so importing this package for the MDX or
16
+ * widget halves never pulls in the scraping stack.
17
+ *
18
+ * @module source
19
+ */
20
+ import { htmlToPaper, textToPaper, type PaperMeta } from "./html-to-paper"
21
+ import type { Paper } from "./types"
22
+
23
+ /** What an extractor returns: reading-mode HTML plus citation fields. */
24
+ export interface ExtractedSource {
25
+ html?: string
26
+ title?: string
27
+ author?: string
28
+ date?: string
29
+ cite?: string
30
+ url?: string
31
+ error?: string | number
32
+ }
33
+
34
+ /** Fetches and extracts one URL or binary file. Swappable for tests and other hosts. */
35
+ export type Extractor = (input: string | Uint8Array, options: { isPdf?: boolean }) => Promise<ExtractedSource>
36
+
37
+ const DOI = /^(?:doi:\s*)?(10\.\d{4,9}\/\S+)$/i
38
+
39
+ /** The URL the extractor should read for `input` (see the module doc), plus fallbacks to try in order. */
40
+ export function normalizeSourceUrl(input: string): string[] {
41
+ const trimmed = input.trim()
42
+ const doi = DOI.exec(trimmed)
43
+ if (doi) return [`https://doi.org/${doi[1]}`]
44
+ let url: URL
45
+ try {
46
+ url = new URL(/^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`)
47
+ } catch {
48
+ return [trimmed]
49
+ }
50
+ if (/(^|\.)arxiv\.org$/i.test(url.hostname)) {
51
+ const id = /^\/(?:abs|pdf|html)\/([^?#]+?)(?:\.pdf)?\/?$/.exec(url.pathname)?.[1]
52
+ if (id) return [`https://arxiv.org/html/${id}`, `https://arxiv.org/pdf/${id}`]
53
+ }
54
+ return [url.toString()]
55
+ }
56
+
57
+ /** True when `input` looks like a link or DOI rather than pasted text. */
58
+ export function isLinkInput(input: string): boolean {
59
+ const trimmed = input.trim()
60
+ if (/\s/.test(trimmed)) return false
61
+ return /^https?:\/\//i.test(trimmed) || DOI.test(trimmed) || /^[\w-]+(\.[\w-]+)+\/\S*$/.test(trimmed)
62
+ }
63
+
64
+ /** True when the bytes start with `%PDF-`. */
65
+ export function isPdfBuffer(bytes: Uint8Array): boolean {
66
+ return bytes.length > 4 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d
67
+ }
68
+
69
+ /** Run `fn` with the extractor's chatty console.log silenced. */
70
+ async function quietly<T>(fn: () => Promise<T>): Promise<T> {
71
+ const log = console.log
72
+ console.log = () => {}
73
+ try {
74
+ return await fn()
75
+ } finally {
76
+ console.log = log
77
+ }
78
+ }
79
+
80
+ /** The default extractor: `extract-webpage` for links and `.docx`, `extract-pdf` for PDF bytes. */
81
+ export const extractWithExtractWebpage: Extractor = async (input, { isPdf }) =>
82
+ quietly(async () => {
83
+ if (input instanceof Uint8Array && (isPdf || isPdfBuffer(input))) {
84
+ const { convertPDFToHTML } = await import("extract-pdf")
85
+ return (await convertPDFToHTML(input)) as ExtractedSource
86
+ }
87
+ const { extractContent } = await import("extract-webpage")
88
+ return (await extractContent(input, { images: true, links: true, formatting: true, timeout: 20 })) as ExtractedSource
89
+ })
90
+
91
+ export interface LoadOptions {
92
+ /** Replace the extractor (tests, or a host with its own scraping proxy). */
93
+ extract?: Extractor
94
+ /** File name of a binary input, used to tell PDFs from .docx and as a title fallback. */
95
+ fileName?: string
96
+ }
97
+
98
+ /** The extractor's citation as plain text, or nothing when it has no real words (". . . https://…"). */
99
+ function usableCite(cite: string | undefined): string | undefined {
100
+ const text = cite?.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim()
101
+ if (!text) return undefined
102
+ return (text.replace(/https?:\/\/\S+/g, "").match(/\p{L}{3,}/gu) ?? []).length >= 3 ? text : undefined
103
+ }
104
+
105
+ function metaFrom(extracted: ExtractedSource, sourceUrl?: string): PaperMeta {
106
+ return {
107
+ // PDFs with no Title field come back as "untitled"; let the file name or first heading win.
108
+ title: extracted.title?.trim().replace(/^untitled(\s+document)?$/i, "") || undefined,
109
+ author: extracted.author?.trim() || undefined,
110
+ date: extracted.date?.trim() || undefined,
111
+ cite: usableCite(extracted.cite),
112
+ sourceUrl: sourceUrl ?? extracted.url,
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Turn any input into a `Paper` (structure only; run `finishPaper` or the AI
118
+ * pass for summaries and underlining):
119
+ * - a URL, arXiv link, archive link or DOI → scraped and extracted;
120
+ * - `Uint8Array` bytes of a PDF or `.docx` → extracted;
121
+ * - text with an `.html` `fileName` → read as markup;
122
+ * - anything else → read as pasted text or markdown.
123
+ */
124
+ export async function loadPaper(input: string | Uint8Array, options: LoadOptions = {}): Promise<Paper> {
125
+ const extract = options.extract ?? extractWithExtractWebpage
126
+ if (input instanceof Uint8Array) {
127
+ const isPdf = isPdfBuffer(input) || /\.pdf$/i.test(options.fileName ?? "")
128
+ const extracted = await extract(input, { isPdf })
129
+ if (!extracted.html) throw new Error(`Could not extract ${options.fileName ?? "the file"}: ${extracted.error ?? "no text found"}`)
130
+ const meta = metaFrom(extracted)
131
+ if (!meta.title && options.fileName) meta.title = options.fileName.replace(/\.[^.]+$/, "")
132
+ return htmlToPaper(extracted.html, meta)
133
+ }
134
+
135
+ // A local .html file is already markup: lay it out like a scraped page.
136
+ if (/\.x?html?$/i.test(options.fileName ?? "")) {
137
+ const paper = htmlToPaper(input)
138
+ if (!paper.title) paper.title = options.fileName!.replace(/\.[^.]+$/, "")
139
+ return paper
140
+ }
141
+ if (!isLinkInput(input)) return textToPaper(input)
142
+
143
+ const errors: string[] = []
144
+ for (const url of normalizeSourceUrl(input)) {
145
+ try {
146
+ const extracted = await extract(url, { isPdf: /\.pdf$|\/pdf\//i.test(url) })
147
+ if (extracted.html && extracted.html.replace(/<[^>]+>/g, "").trim().length > 200) {
148
+ return htmlToPaper(extracted.html, metaFrom(extracted, input.trim().startsWith("http") ? input.trim() : url))
149
+ }
150
+ errors.push(`${url}: ${extracted.error ?? "no article text found"}`)
151
+ } catch (error) {
152
+ errors.push(`${url}: ${error instanceof Error ? error.message : String(error)}`)
153
+ }
154
+ }
155
+ throw new Error(`Could not extract a paper from ${input}. ${errors.join("; ")}`)
156
+ }
package/src/types.ts ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @fileoverview The shape every input becomes before it is written out. A
3
+ * `Paper` mirrors how the Synergy Slayer papers are laid out in help-docs
4
+ * (`content/docs/learn/critiques/synergy-slayer-critiques/`): an index page
5
+ * with the abstract, then one page per numbered section, each with an
6
+ * optional figure, a "Section Summary" accordion of bold-lead points, and
7
+ * numbered paragraphs whose card underlining is written as `==text==`.
8
+ *
9
+ * @module types
10
+ */
11
+
12
+ /** One figure: an image and its `*Figure N: …*` caption. */
13
+ export interface PaperFigure {
14
+ src: string
15
+ caption: string
16
+ }
17
+
18
+ /** One "Section Summary" point: `**label:** text`. */
19
+ export interface SummaryPoint {
20
+ label: string
21
+ text: string
22
+ }
23
+
24
+ /** One section page. */
25
+ export interface PaperSection {
26
+ /** Heading without the number, as plain text (not markdown), e.g. "Original Sin". */
27
+ title: string
28
+ /** One-line page description (frontmatter `description`). */
29
+ description?: string
30
+ /** Optional part heading this section opens (a `---Part---` separator in meta.json). */
31
+ part?: string
32
+ figure?: PaperFigure
33
+ summary: SummaryPoint[]
34
+ /**
35
+ * Body paragraphs in markdown. `==text==` marks the underlined words, the
36
+ * way a debater reads only the marked part of a card.
37
+ */
38
+ paragraphs: string[]
39
+ }
40
+
41
+ /** A whole paper (or an outline generated in the paper's format). */
42
+ export interface Paper {
43
+ /** Plain text, like section titles and parts. Everything else is markdown. */
44
+ title: string
45
+ /** Subtitle / one-line description. */
46
+ description?: string
47
+ author?: string
48
+ date?: string
49
+ /** Where it came from. */
50
+ sourceUrl?: string
51
+ /** A formatted citation, when the extractor found one. */
52
+ cite?: string
53
+ abstract?: string
54
+ keywords?: string[]
55
+ figure?: PaperFigure
56
+ sections: PaperSection[]
57
+ /** Reference list entries, as markdown. */
58
+ references: string[]
59
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @fileoverview `<PaperReader>`: a converted paper with the Reader mode,
3
+ * Underlining and Voice toolbar, as a React component. It renders the same
4
+ * markup as the standalone HTML export (`html.ts`) and wires it with the same
5
+ * runtime (`reader-runtime.ts`), so the widget and the exported page behave
6
+ * identically. Mount it anywhere; it carries its own scoped stylesheet.
7
+ *
8
+ * @module widget/PaperReader
9
+ */
10
+ import { useEffect, useMemo, useRef } from "react"
11
+ import { PAPER_READER_CSS, renderPaperReader } from "../html"
12
+ import { mountPaperReader, type PaperReaderRuntimeOptions } from "../reader-runtime"
13
+ import type { Paper } from "../types"
14
+
15
+ export interface PaperReaderProps {
16
+ paper: Paper
17
+ /** A better voice than the browser's (Kokoro, Cloudflare TTS…). */
18
+ speak?: PaperReaderRuntimeOptions["speak"]
19
+ cancelSpeech?: PaperReaderRuntimeOptions["cancelSpeech"]
20
+ className?: string
21
+ }
22
+
23
+ /** The reader (see the module doc). */
24
+ export function PaperReader({ paper, speak, cancelSpeech, className }: PaperReaderProps) {
25
+ const ref = useRef<HTMLDivElement>(null)
26
+ const markup = useMemo(() => renderPaperReader(paper), [paper])
27
+
28
+ useEffect(() => {
29
+ const root = ref.current?.querySelector(".ptw-paper")
30
+ if (!root) return
31
+ const handle = mountPaperReader(root, { speak, cancelSpeech })
32
+ return () => handle.destroy()
33
+ }, [markup, speak, cancelSpeech])
34
+
35
+ return (
36
+ <div className={className}>
37
+ <style>{PAPER_READER_CSS}</style>
38
+ <div ref={ref} dangerouslySetInnerHTML={{ __html: markup }} />
39
+ </div>
40
+ )
41
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * @fileoverview `<PaperToWeb>`: the converter as a self-contained React
3
+ * widget. Paste a link, DOI, topic or text (or pick a PDF / `.docx`), choose
4
+ * Paper sections or Outline, and read the result in `<PaperReader>` with
5
+ * downloads for the `.mdx`, `.html` and JSON.
6
+ *
7
+ * It talks to a `createPaperToWebHandler` endpoint (`server.ts`), because
8
+ * scraping arbitrary pages needs a server; pass `endpoint` to point it at
9
+ * one (default `/api/convert`).
10
+ *
11
+ * @module widget/PaperToWeb
12
+ */
13
+ import { useState, type FormEvent } from "react"
14
+ import type { ConvertResponse } from "../server"
15
+ import { PaperReader } from "./PaperReader"
16
+
17
+ export interface PaperToWebProps {
18
+ /** The convert endpoint (default "/api/convert"). */
19
+ endpoint?: string
20
+ /** Offer the "Use AI" box (the server needs a model configured). */
21
+ allowAi?: boolean
22
+ className?: string
23
+ }
24
+
25
+ function save(name: string, text: string, type: string) {
26
+ const url = URL.createObjectURL(new Blob([text], { type }))
27
+ const a = document.createElement("a")
28
+ a.href = url
29
+ a.download = name
30
+ document.body.appendChild(a)
31
+ a.click()
32
+ a.remove()
33
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
34
+ }
35
+
36
+ /** File-name stem from a title. */
37
+ export function fileStem(title: string): string {
38
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "paper"
39
+ }
40
+
41
+ /** The converter widget (see the module doc). */
42
+ export function PaperToWeb({ endpoint = "/api/convert", allowAi = true, className }: PaperToWebProps) {
43
+ const [result, setResult] = useState<ConvertResponse | null>(null)
44
+ const [status, setStatus] = useState("")
45
+ const [error, setError] = useState("")
46
+ const [busy, setBusy] = useState(false)
47
+
48
+ const submit = async (event: FormEvent<HTMLFormElement>) => {
49
+ event.preventDefault()
50
+ setBusy(true)
51
+ setError("")
52
+ setStatus("Converting… scraping and extracting can take a minute.")
53
+ try {
54
+ const response = await fetch(endpoint, { method: "POST", body: new FormData(event.currentTarget) })
55
+ const body = (await response.json()) as ConvertResponse & { error?: string }
56
+ if (!response.ok || body.error) throw new Error(body.error ?? `HTTP ${response.status}`)
57
+ setResult(body)
58
+ setStatus(`${body.paper.sections.length} sections`)
59
+ } catch (err) {
60
+ setError(err instanceof Error ? err.message : String(err))
61
+ setStatus("")
62
+ } finally {
63
+ setBusy(false)
64
+ }
65
+ }
66
+
67
+ const stem = result ? fileStem(result.paper.title) : "paper"
68
+ return (
69
+ <div className={className}>
70
+ <form onSubmit={submit} style={{ display: "grid", gap: "0.75rem" }}>
71
+ <textarea
72
+ name="input"
73
+ rows={4}
74
+ placeholder="Paste a link (arXiv, DOI, archive.org, any article or PDF URL), a topic, or the text itself"
75
+ style={{ width: "100%", boxSizing: "border-box", font: "inherit", padding: "0.6rem" }}
76
+ />
77
+ <label>
78
+ or a file <input type="file" name="file" accept=".pdf,.docx,.md,.txt,.html" />
79
+ </label>
80
+ <div style={{ display: "flex", flexWrap: "wrap", gap: "0.75rem", alignItems: "center" }}>
81
+ <label>
82
+ <input type="radio" name="mode" value="paper" defaultChecked /> Paper sections
83
+ </label>
84
+ <label>
85
+ <input type="radio" name="mode" value="outline" /> Outline
86
+ </label>
87
+ {allowAi && (
88
+ <label>
89
+ <input type="checkbox" name="ai" value="on" /> Use AI
90
+ </label>
91
+ )}
92
+ <input type="text" name="focus" placeholder="Outline focus (optional)" style={{ flex: 1, minWidth: "12rem", font: "inherit" }} />
93
+ <button type="submit" disabled={busy}>
94
+ {busy ? "Converting…" : "Convert"}
95
+ </button>
96
+ </div>
97
+ <div role="status" style={{ color: error ? "#dc2626" : undefined }}>
98
+ {error || status}
99
+ </div>
100
+ </form>
101
+ {result && (
102
+ <>
103
+ <div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem", margin: "1rem 0" }}>
104
+ {result.refdoc && (
105
+ <button type="button" onClick={() => save(`${stem}.refdoc.html`, result.refdoc!, "text/html")}>
106
+ Download .refdoc.html
107
+ </button>
108
+ )}
109
+ <button type="button" onClick={() => save(`${stem}.mdx`, result.mdx, "text/markdown")}>
110
+ Download .mdx
111
+ </button>
112
+ <button type="button" onClick={() => save(`${stem}.html`, result.html, "text/html")}>
113
+ Download .html
114
+ </button>
115
+ <button type="button" onClick={() => save(`${stem}.json`, JSON.stringify(result.paper, null, 2), "application/json")}>
116
+ Download .json
117
+ </button>
118
+ {Object.entries(result.files).map(([name, text]) => (
119
+ <button key={name} type="button" onClick={() => save(name, text, "text/plain")}>
120
+ {name}
121
+ </button>
122
+ ))}
123
+ </div>
124
+ <PaperReader paper={result.paper} />
125
+ </>
126
+ )}
127
+ </div>
128
+ )
129
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @fileoverview React entry: `extract-refdoc/widget`.
3
+ * @module widget
4
+ */
5
+ export { PaperReader, type PaperReaderProps } from "./PaperReader"
6
+ export { PaperToWeb, fileStem, type PaperToWebProps } from "./PaperToWeb"