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/README.md +172 -2
- package/bin/extract-refdoc.ts +134 -0
- package/dist/refdoc.css +3727 -0
- package/dist/refdoc.js +162 -0
- package/package.json +83 -3
- package/src/ai.ts +268 -0
- package/src/finish.ts +105 -0
- package/src/highlight.ts +125 -0
- package/src/html-to-paper.ts +400 -0
- package/src/html.ts +172 -0
- package/src/index.ts +78 -0
- package/src/markdown.ts +192 -0
- package/src/mdx.ts +182 -0
- package/src/pipeline.ts +61 -0
- package/src/reader-runtime.ts +166 -0
- package/src/refdoc-read.ts +96 -0
- package/src/refdoc.ts +250 -0
- package/src/server.ts +218 -0
- package/src/source.ts +156 -0
- package/src/types.ts +59 -0
- package/src/widget/PaperReader.tsx +41 -0
- package/src/widget/PaperToWeb.tsx +129 -0
- package/src/widget/index.ts +6 -0
package/src/markdown.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The small slice of markdown the paper format uses, both ways.
|
|
3
|
+
*
|
|
4
|
+
* - `htmlInlineToMarkdown` turns an extracted element's inline content into
|
|
5
|
+
* MDX-safe markdown: bold, italics, links, inline code, and `==text==` for
|
|
6
|
+
* anything the source already underlined or highlighted (`<u>`, `<mark>`).
|
|
7
|
+
* - `markdownInlineToHtml` renders that same slice back to HTML for the
|
|
8
|
+
* reader widget and the standalone HTML export, with `==text==` becoming
|
|
9
|
+
* `<mark>` exactly as help-docs' `remark-debate-highlight` does.
|
|
10
|
+
*
|
|
11
|
+
* MDX parses `{`, `}` and `<` as code, so text is escaped on the way out.
|
|
12
|
+
*
|
|
13
|
+
* @module markdown
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Escape text for MDX: braces and angle brackets would start JSX. */
|
|
17
|
+
export function escapeMdxText(text: string): string {
|
|
18
|
+
return text
|
|
19
|
+
.replace(/\\/g, "\\\\")
|
|
20
|
+
.replace(/[{}]/g, (c) => `\\${c}`)
|
|
21
|
+
.replace(/</g, "<")
|
|
22
|
+
.replace(/>/g, ">")
|
|
23
|
+
// A literal `==` in the source would read as a highlight marker.
|
|
24
|
+
.replace(/==/g, "=â=")
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** True for a `### ` subheading kept inside a section's paragraphs. */
|
|
28
|
+
export function isSubheading(markdown: string): boolean {
|
|
29
|
+
return markdown.startsWith("### ")
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Letters and digits only, after folding math alphanumerics (đł â z) and dropping TeX commands. */
|
|
33
|
+
function comparable(text: string): string {
|
|
34
|
+
return text
|
|
35
|
+
.normalize("NFKC")
|
|
36
|
+
.replace(/\\[a-zA-Z]+/g, "")
|
|
37
|
+
.replace(/[^\p{L}\p{N}]/gu, "")
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function balanced(text: string): boolean {
|
|
41
|
+
let depth = 0
|
|
42
|
+
for (const c of text) {
|
|
43
|
+
if (c === "(" || c === "[") depth++
|
|
44
|
+
else if (c === ")" || c === "]") depth--
|
|
45
|
+
if (depth < 0) return false
|
|
46
|
+
}
|
|
47
|
+
return depth === 0
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Extracted MathML often reads as its rendered text followed by its TeX
|
|
52
|
+
* source ("hth_{t}", "đł\\mathbf{z}") or simply twice ("N=6N=6"). Keep the
|
|
53
|
+
* rendered half.
|
|
54
|
+
*/
|
|
55
|
+
export function cleanMathText(text: string): string {
|
|
56
|
+
const trimmed = text.trim()
|
|
57
|
+
// Longest rendered half first, so closing brackets stay with it; prefer a
|
|
58
|
+
// split that leaves the rendered half's brackets balanced.
|
|
59
|
+
let fallback: string | null = null
|
|
60
|
+
for (let i = trimmed.length - 1; i >= 1; i--) {
|
|
61
|
+
const head = trimmed.slice(0, i)
|
|
62
|
+
const tail = trimmed.slice(i)
|
|
63
|
+
if (/[\\{}]/.test(head)) continue
|
|
64
|
+
const key = comparable(head)
|
|
65
|
+
if (!key || key !== comparable(tail) || !(tail === head || /[_^\\{}]/.test(tail))) continue
|
|
66
|
+
if (balanced(head)) return head.trim()
|
|
67
|
+
fallback ??= head.trim()
|
|
68
|
+
}
|
|
69
|
+
if (fallback) return fallback
|
|
70
|
+
return trimmed
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Collapse runs of whitespace (PDF and HTML line breaks) to single spaces. */
|
|
74
|
+
export function collapseWhitespace(text: string): string {
|
|
75
|
+
return text.replace(/\s+/g, " ")
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type InlineNode = {
|
|
79
|
+
nodeType: number
|
|
80
|
+
nodeValue?: string | null
|
|
81
|
+
tagName?: string
|
|
82
|
+
childNodes?: ArrayLike<InlineNode>
|
|
83
|
+
getAttribute?: (name: string) => string | null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const TEXT_NODE = 3
|
|
87
|
+
const ELEMENT_NODE = 1
|
|
88
|
+
|
|
89
|
+
function collectText(node: InlineNode): string {
|
|
90
|
+
if (node.nodeType === TEXT_NODE) return node.nodeValue ?? ""
|
|
91
|
+
const tag = (node.tagName ?? "").toUpperCase()
|
|
92
|
+
if (tag === "ANNOTATION" || tag === "ANNOTATION-XML") return ""
|
|
93
|
+
return Array.from(node.childNodes ?? []).map(collectText).join("")
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Wrap `inner` in a marker pair, keeping surrounding spaces outside it. */
|
|
97
|
+
function wrap(inner: string, open: string, close = open): string {
|
|
98
|
+
const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(inner)
|
|
99
|
+
if (!match || !match[2]) return inner
|
|
100
|
+
return `${match[1]}${open}${match[2]}${close}${match[3]}`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Inline content of `node` as MDX-safe markdown (see the module doc). */
|
|
104
|
+
export function htmlInlineToMarkdown(node: InlineNode, insideMark = false): string {
|
|
105
|
+
if (node.nodeType === TEXT_NODE) return escapeMdxText(collapseWhitespace(node.nodeValue ?? ""))
|
|
106
|
+
if (node.nodeType !== ELEMENT_NODE) return ""
|
|
107
|
+
const tag = (node.tagName ?? "").toUpperCase()
|
|
108
|
+
if (["SCRIPT", "STYLE", "NOSCRIPT", "IMG", "SVG", "FIGURE", "BUTTON"].includes(tag)) return ""
|
|
109
|
+
if (tag === "BR") return " "
|
|
110
|
+
if (tag === "ANNOTATION" || tag === "ANNOTATION-XML") return ""
|
|
111
|
+
if (tag === "MATH") {
|
|
112
|
+
const alt = node.getAttribute?.("alttext")
|
|
113
|
+
const text = alt ?? collectText(node)
|
|
114
|
+
return escapeMdxText(alt ? alt : cleanMathText(text))
|
|
115
|
+
}
|
|
116
|
+
const isMark = tag === "MARK" || tag === "U"
|
|
117
|
+
const children = Array.from(node.childNodes ?? [])
|
|
118
|
+
.map((child) => htmlInlineToMarkdown(child, insideMark || isMark))
|
|
119
|
+
.join("")
|
|
120
|
+
switch (tag) {
|
|
121
|
+
case "STRONG":
|
|
122
|
+
case "B":
|
|
123
|
+
return wrap(children, "**")
|
|
124
|
+
case "EM":
|
|
125
|
+
case "I":
|
|
126
|
+
case "CITE":
|
|
127
|
+
return wrap(children, "*")
|
|
128
|
+
case "CODE":
|
|
129
|
+
return wrap(children.replace(/`/g, "'"), "`")
|
|
130
|
+
case "MARK":
|
|
131
|
+
case "U":
|
|
132
|
+
return insideMark ? children : wrap(children, "==")
|
|
133
|
+
case "A": {
|
|
134
|
+
const href = node.getAttribute?.("href") ?? ""
|
|
135
|
+
// In-page anchors (citation and footnote jumps) mean nothing out of context.
|
|
136
|
+
if (!/^https?:\/\//i.test(href) || !children.trim() || /#./.test(href)) return children
|
|
137
|
+
return `[${children.trim()}](${href.replace(/[()\s]/g, encodeURIComponent)})`
|
|
138
|
+
}
|
|
139
|
+
default:
|
|
140
|
+
return children
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Escape text for HTML. */
|
|
145
|
+
export function escapeHtml(text: string): string {
|
|
146
|
+
return text
|
|
147
|
+
.replace(/&(?!(?:[a-z]+|#\d+|#x[\da-f]+);)/gi, "&")
|
|
148
|
+
.replace(/</g, "<")
|
|
149
|
+
.replace(/>/g, ">")
|
|
150
|
+
.replace(/"/g, """)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Undo `escapeMdxText`'s backslash escapes for display. */
|
|
154
|
+
function unescapeMdx(text: string): string {
|
|
155
|
+
return text.replace(/\\([\\{}*_[\]()#`>-])/g, "$1").replace(/=â=/g, "==")
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Render the inline markdown slice (see the module doc) to HTML. */
|
|
159
|
+
export function markdownInlineToHtml(markdown: string): string {
|
|
160
|
+
// Images and links first, so their URLs are not touched by emphasis rules.
|
|
161
|
+
const tokens: string[] = []
|
|
162
|
+
const stash = (html: string) => `\u0000${tokens.push(html) - 1}\u0000`
|
|
163
|
+
let text = markdown
|
|
164
|
+
.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_, alt: string, src: string) =>
|
|
165
|
+
stash(`<img src="${escapeHtml(src)}" alt="${escapeHtml(unescapeMdx(alt))}" loading="lazy" />`),
|
|
166
|
+
)
|
|
167
|
+
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, (_, label: string, href: string) =>
|
|
168
|
+
stash(`<a href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer">${markdownInlineToHtml(label)}</a>`),
|
|
169
|
+
)
|
|
170
|
+
.replace(/`([^`]+)`/g, (_, code: string) => stash(`<code>${escapeHtml(code)}</code>`))
|
|
171
|
+
text = escapeHtml(unescapeMdx(text))
|
|
172
|
+
.replace(/==([^=\n](?:[^\n]*?[^=\n])?)==/g, '<mark class="debate-hl">$1</mark>')
|
|
173
|
+
.replace(/\*\*([^*\n]+?)\*\*/g, "<strong>$1</strong>")
|
|
174
|
+
.replace(/(^|[^*\w])\*([^*\n]+?)\*(?!\w)/g, "$1<em>$2</em>")
|
|
175
|
+
// eslint-disable-next-line no-control-regex
|
|
176
|
+
return text.replace(/\u0000(\d+)\u0000/g, (_, index: string) => tokens[Number(index)] ?? "")
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Plain text of an inline markdown string: markers and link syntax removed. */
|
|
180
|
+
export function markdownToPlainText(markdown: string): string {
|
|
181
|
+
return unescapeMdx(
|
|
182
|
+
markdown
|
|
183
|
+
.replace(/!\[[^\]]*\]\([^)]*\)/g, "")
|
|
184
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
|
185
|
+
.replace(/==|\*\*|`/g, "")
|
|
186
|
+
.replace(/(^|[^*\w])\*([^*\n]+?)\*(?!\w)/g, "$1$2")
|
|
187
|
+
.replace(/</g, "<")
|
|
188
|
+
.replace(/>/g, ">"),
|
|
189
|
+
)
|
|
190
|
+
.replace(/\s+/g, " ")
|
|
191
|
+
.trim()
|
|
192
|
+
}
|
package/src/mdx.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview `Paper` â the Synergy Slayer docs layout, file for file:
|
|
3
|
+
*
|
|
4
|
+
* ```
|
|
5
|
+
* index.mdx title, figure, byline, **Abstract.**, ***Keywords***
|
|
6
|
+
* 01-<slug>.mdx "1. Title" frontmatter, figure + *Figure N:* caption,
|
|
7
|
+
* Section Summary accordion, numbered ==underlined== paragraphs
|
|
8
|
+
* âŚ
|
|
9
|
+
* references.mdx the reference list
|
|
10
|
+
* meta.json sidebar order, with "---Part---" separators
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Dropped into a Fumadocs content folder (as help-docs does for
|
|
14
|
+
* `learn/critiques/synergy-slayer-critiques/`) the pages render with the
|
|
15
|
+
* same accordion. With `accordion: "details"` the summary is a plain
|
|
16
|
+
* `<details>` so the MDX needs no Fumadocs components at all.
|
|
17
|
+
*
|
|
18
|
+
* @module mdx
|
|
19
|
+
*/
|
|
20
|
+
import { escapeMdxText, isSubheading, markdownToPlainText } from "./markdown"
|
|
21
|
+
import type { Paper, PaperFigure, PaperSection } from "./types"
|
|
22
|
+
|
|
23
|
+
export interface MdxOptions {
|
|
24
|
+
/** "fumadocs" (default) imports Fumadocs' Accordion like the Synergy Slayer pages; "details" uses a plain `<details>`. */
|
|
25
|
+
accordion?: "fumadocs" | "details"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** URL-safe slug from a title, at most six words. */
|
|
29
|
+
export function slugify(title: string): string {
|
|
30
|
+
return (
|
|
31
|
+
title
|
|
32
|
+
.normalize("NFKD")
|
|
33
|
+
.replace(/[Ě-ÍŻ]/g, "")
|
|
34
|
+
.toLowerCase()
|
|
35
|
+
.replace(/['â]/g, "")
|
|
36
|
+
.replace(/[^a-z0-9]+/g, " ")
|
|
37
|
+
.trim()
|
|
38
|
+
.split(/\s+/)
|
|
39
|
+
.slice(0, 6)
|
|
40
|
+
.join("-") || "section"
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** File stem for section `index` (0-based): "01-original-sin". */
|
|
45
|
+
export function sectionSlug(section: PaperSection, index: number): string {
|
|
46
|
+
return `${String(index + 1).padStart(2, "0")}-${slugify(section.title)}`
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A YAML double-quoted scalar (JSON strings are valid YAML). */
|
|
50
|
+
function yamlString(text: string): string {
|
|
51
|
+
return JSON.stringify(text.replace(/\s+/g, " ").trim())
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function frontmatter(title: string, description?: string): string {
|
|
55
|
+
const lines = ["---", `title: ${yamlString(title)}`]
|
|
56
|
+
// Frontmatter is YAML, not MDX: write the description as plain text.
|
|
57
|
+
if (description) lines.push(`description: ${yamlString(markdownToPlainText(description))}`)
|
|
58
|
+
lines.push("---")
|
|
59
|
+
return lines.join("\n")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Alt text and caption are prose, so strip characters markdown would read as syntax. */
|
|
63
|
+
function plainCaption(text: string): string {
|
|
64
|
+
return text.replace(/[[\]*_`<>{}]/g, "").replace(/\s+/g, " ").trim()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function figureMarkdown(figure: PaperFigure, number: number): string {
|
|
68
|
+
const caption = plainCaption(figure.caption)
|
|
69
|
+
if (!caption) return ``
|
|
70
|
+
return `\n\n*Figure ${number}: ${caption}*`
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function summaryMarkdown(section: PaperSection, options: MdxOptions): string {
|
|
74
|
+
if (section.summary.length === 0) return ""
|
|
75
|
+
const points = section.summary.map((point, i) => `${i + 1}. **${point.label.replace(/\*/g, "")}:** ${point.text}`).join("\n")
|
|
76
|
+
if (options.accordion === "details") {
|
|
77
|
+
return `<details open>\n<summary>Section Summary</summary>\n\n${points}\n\n</details>`
|
|
78
|
+
}
|
|
79
|
+
return [
|
|
80
|
+
"import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';",
|
|
81
|
+
"",
|
|
82
|
+
'<Accordions type="single" defaultValue="Section Summary">',
|
|
83
|
+
'<Accordion title="Section Summary">',
|
|
84
|
+
"",
|
|
85
|
+
points,
|
|
86
|
+
"",
|
|
87
|
+
"</Accordion>",
|
|
88
|
+
"</Accordions>",
|
|
89
|
+
].join("\n")
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Numbered paragraphs: "1. âŚ\n\n2. âŚ", one item per paragraph, each kept on
|
|
94
|
+
* one line. `### ` subheadings sit between them; numbering continues across.
|
|
95
|
+
*/
|
|
96
|
+
function paragraphsMarkdown(paragraphs: string[]): string {
|
|
97
|
+
let n = 0
|
|
98
|
+
return paragraphs
|
|
99
|
+
.map((p) => (isSubheading(p) ? p : `${++n}. ${p.replace(/\s*\n\s*/g, " ")}`))
|
|
100
|
+
.join("\n\n")
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One section page. `figureNumber` is the figure's number in the whole paper. */
|
|
104
|
+
export function sectionToMdx(section: PaperSection, index: number, figureNumber: number, options: MdxOptions = {}): string {
|
|
105
|
+
const parts = [frontmatter(`${index + 1}. ${section.title}`, section.description)]
|
|
106
|
+
if (section.figure) parts.push(figureMarkdown(section.figure, figureNumber))
|
|
107
|
+
const summary = summaryMarkdown(section, options)
|
|
108
|
+
if (summary) parts.push(summary)
|
|
109
|
+
if (section.paragraphs.length > 0) parts.push(paragraphsMarkdown(section.paragraphs))
|
|
110
|
+
return `${parts.join("\n\n")}\n`
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The index page: title, figure, byline and abstract. */
|
|
114
|
+
export function indexToMdx(paper: Paper): string {
|
|
115
|
+
const parts = [frontmatter(paper.title, paper.description)]
|
|
116
|
+
if (paper.figure) parts.push(figureMarkdown(paper.figure, 1))
|
|
117
|
+
const byline: string[] = []
|
|
118
|
+
if (paper.author) byline.push(`**${escapeMdxText(paper.author)}**`)
|
|
119
|
+
if (paper.sourceUrl) byline.push(`**Source: [${paper.sourceUrl.replace(/^https?:\/\//, "")}](${paper.sourceUrl})**`)
|
|
120
|
+
if (paper.date) byline.push(`**Published: ${escapeMdxText(paper.date)}**`)
|
|
121
|
+
if (byline.length > 0) parts.push(byline.join("\n\n"))
|
|
122
|
+
if (paper.cite) parts.push(`*${escapeMdxText(paper.cite.replace(/\*/g, ""))}*`)
|
|
123
|
+
if (paper.abstract) parts.push(`**Abstract.** ${paper.abstract}`)
|
|
124
|
+
if (paper.keywords && paper.keywords.length > 0) parts.push(`***Keywords**: ${paper.keywords.join(", ")}*`)
|
|
125
|
+
return `${parts.join("\n\n")}\n`
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The references page. */
|
|
129
|
+
export function referencesToMdx(paper: Paper): string {
|
|
130
|
+
return `${frontmatter("References")}\n\n${paper.references.map((ref, i) => `${i + 1}. ${ref}`).join("\n")}\n`
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Fumadocs `meta.json`: page order, with a "---Part---" separator before each section that opens a part. */
|
|
134
|
+
export function paperMeta(paper: Paper): { title: string; root: boolean; pages: string[] } {
|
|
135
|
+
const pages = ["index"]
|
|
136
|
+
paper.sections.forEach((section, i) => {
|
|
137
|
+
if (section.part) pages.push(`---${section.part}---`)
|
|
138
|
+
pages.push(sectionSlug(section, i))
|
|
139
|
+
})
|
|
140
|
+
if (paper.references.length > 0) pages.push("references")
|
|
141
|
+
return { title: paper.title, root: true, pages }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Every file of the docs folder, by file name (see the module doc). */
|
|
145
|
+
export function paperToMdxFiles(paper: Paper, options: MdxOptions = {}): Record<string, string> {
|
|
146
|
+
const files: Record<string, string> = { "index.mdx": indexToMdx(paper) }
|
|
147
|
+
let figureNumber = paper.figure ? 1 : 0
|
|
148
|
+
paper.sections.forEach((section, i) => {
|
|
149
|
+
if (section.figure) figureNumber += 1
|
|
150
|
+
files[`${sectionSlug(section, i)}.mdx`] = sectionToMdx(section, i, figureNumber, options)
|
|
151
|
+
})
|
|
152
|
+
if (paper.references.length > 0) files["references.mdx"] = referencesToMdx(paper)
|
|
153
|
+
files["meta.json"] = `${JSON.stringify(paperMeta(paper), null, 2)}\n`
|
|
154
|
+
return files
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The whole paper as one MDX page: the index content, then each section as
|
|
159
|
+
* `## N. Title` with its own summary and numbered paragraphs. Always uses
|
|
160
|
+
* `<details>` summaries so the page stands alone.
|
|
161
|
+
*/
|
|
162
|
+
export function paperToSingleMdx(paper: Paper): string {
|
|
163
|
+
const parts = [indexToMdx(paper).trimEnd()]
|
|
164
|
+
let figureNumber = paper.figure ? 1 : 0
|
|
165
|
+
paper.sections.forEach((section, i) => {
|
|
166
|
+
if (section.part) parts.push(`# ${escapeMdxText(section.part)}`)
|
|
167
|
+
const block = [`## ${i + 1}. ${escapeMdxText(section.title)}`]
|
|
168
|
+
if (section.description) block.push(`*${section.description.replace(/\*/g, "")}*`)
|
|
169
|
+
if (section.figure) {
|
|
170
|
+
figureNumber += 1
|
|
171
|
+
block.push(figureMarkdown(section.figure, figureNumber))
|
|
172
|
+
}
|
|
173
|
+
const summary = summaryMarkdown(section, { accordion: "details" })
|
|
174
|
+
if (summary) block.push(summary)
|
|
175
|
+
if (section.paragraphs.length > 0) block.push(paragraphsMarkdown(section.paragraphs))
|
|
176
|
+
parts.push(block.join("\n\n"))
|
|
177
|
+
})
|
|
178
|
+
if (paper.references.length > 0) {
|
|
179
|
+
parts.push(`## References\n\n${paper.references.map((ref, i) => `${i + 1}. ${ref}`).join("\n")}`)
|
|
180
|
+
}
|
|
181
|
+
return `${parts.join("\n\n")}\n`
|
|
182
|
+
}
|
package/src/pipeline.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The one call the CLI, the server and the widget share:
|
|
3
|
+
* input â `Paper`, in either mode.
|
|
4
|
+
*
|
|
5
|
+
* - `"paper"`: extract the source and lay it out in the paper format, with
|
|
6
|
+
* summaries and underlining from the AI pass when a model is given, else
|
|
7
|
+
* from the offline pass.
|
|
8
|
+
* - `"outline"`: with a model, write a fresh outline in the paper format
|
|
9
|
+
* from the source (or from a bare topic); without one, cut the extracted
|
|
10
|
+
* paper down to its Section Summaries and underlined words.
|
|
11
|
+
*
|
|
12
|
+
* @module pipeline
|
|
13
|
+
*/
|
|
14
|
+
import { enhancePaperWithAi, generateOutline, type TextGenerator } from "./ai"
|
|
15
|
+
import { finishPaper, readOnlyUnderlined } from "./finish"
|
|
16
|
+
import { loadPaper, isLinkInput, type Extractor } from "./source"
|
|
17
|
+
import type { Paper } from "./types"
|
|
18
|
+
|
|
19
|
+
export type ConvertMode = "paper" | "outline"
|
|
20
|
+
|
|
21
|
+
export interface ConvertOptions {
|
|
22
|
+
mode?: ConvertMode
|
|
23
|
+
/** A model for summaries, underlining and outlines. Offline heuristics without one. */
|
|
24
|
+
generate?: TextGenerator
|
|
25
|
+
/** File name of a binary input. */
|
|
26
|
+
fileName?: string
|
|
27
|
+
/** Replace the extractor. */
|
|
28
|
+
extract?: Extractor
|
|
29
|
+
/** Outline focus (an angle, resolution or side). */
|
|
30
|
+
focus?: string
|
|
31
|
+
onProgress?: (message: string) => void
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Convert any input (see the module doc). */
|
|
35
|
+
export async function convertToPaper(input: string | Uint8Array, options: ConvertOptions = {}): Promise<Paper> {
|
|
36
|
+
const { mode = "paper", generate, onProgress } = options
|
|
37
|
+
const isText = typeof input === "string" && !isLinkInput(input)
|
|
38
|
+
|
|
39
|
+
if (mode === "outline" && generate && isText) {
|
|
40
|
+
onProgress?.("Writing the outlineâŚ")
|
|
41
|
+
return generateOutline(input as string, generate, { focus: options.focus })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
onProgress?.(isText ? "Reading the textâŚ" : "Extracting the paperâŚ")
|
|
45
|
+
const loaded = await loadPaper(input, { extract: options.extract, fileName: options.fileName })
|
|
46
|
+
|
|
47
|
+
if (mode === "outline") {
|
|
48
|
+
if (generate) {
|
|
49
|
+
onProgress?.("Writing the outlineâŚ")
|
|
50
|
+
return generateOutline(loaded, generate, { focus: options.focus })
|
|
51
|
+
}
|
|
52
|
+
return readOnlyUnderlined(finishPaper(loaded))
|
|
53
|
+
}
|
|
54
|
+
if (generate) {
|
|
55
|
+
onProgress?.(`Summarizing and underlining ${loaded.sections.length} sectionsâŚ`)
|
|
56
|
+
return enhancePaperWithAi(loaded, generate, {
|
|
57
|
+
onProgress: (done, total) => onProgress?.(`Summarized ${done} of ${total} sections`),
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
return finishPaper(loaded)
|
|
61
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The reader controls, as one dependency-free browser script:
|
|
3
|
+
*
|
|
4
|
+
* - **Reader mode** â a narrow serif reading column with the contents hidden.
|
|
5
|
+
* - **Underlining on/off** â shows or hides the `==text==` card underlining
|
|
6
|
+
* (`<mark class="debate-hl">`), like help-docs' `highlight-toggle.tsx`.
|
|
7
|
+
* - **Voice** â reads the paper aloud top to bottom, one block at a time,
|
|
8
|
+
* scrolling to and outlining the passage being read. With Underlining on it
|
|
9
|
+
* reads only the underlined words, the way a debater reads a card; off, it
|
|
10
|
+
* reads everything. Figures and `Figure N:` captions are skipped, and
|
|
11
|
+
* collapsed Section Summaries are read too â the same rules as help-docs'
|
|
12
|
+
* `voice-read-text.ts`. Pressing Voice again or Escape stops it.
|
|
13
|
+
*
|
|
14
|
+
* The script is kept as source text (`READER_RUNTIME_SOURCE`) so the
|
|
15
|
+
* standalone HTML export can inline it verbatim, and `mountPaperReader`
|
|
16
|
+
* evaluates that same text for the React widget â one implementation, no
|
|
17
|
+
* bundler-dependent `Function#toString`.
|
|
18
|
+
*
|
|
19
|
+
* Voice uses the browser's own speech synthesis. A host with a better voice
|
|
20
|
+
* (Kokoro, Cloudflare TTS) passes `speak(text, rate)` returning a promise
|
|
21
|
+
* that settles when the clip ends.
|
|
22
|
+
*
|
|
23
|
+
* @module reader-runtime
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** Options for `mountPaperReader`. */
|
|
27
|
+
export interface PaperReaderRuntimeOptions {
|
|
28
|
+
/** Speak one passage; resolve when it finishes. Defaults to `speechSynthesis`. */
|
|
29
|
+
speak?: (text: string, rate: number) => Promise<void>
|
|
30
|
+
/** Stop whatever `speak` is playing. */
|
|
31
|
+
cancelSpeech?: () => void
|
|
32
|
+
/** localStorage key prefix for the toggles (default "refdoc"). */
|
|
33
|
+
storageKey?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The script text. Plain ES2017, no imports, no outer references. */
|
|
37
|
+
export const READER_RUNTIME_SOURCE = String.raw`function mountPaperReader(root, options) {
|
|
38
|
+
options = options || {};
|
|
39
|
+
var key = options.storageKey || "refdoc";
|
|
40
|
+
var doc = root.ownerDocument;
|
|
41
|
+
var win = doc.defaultView;
|
|
42
|
+
var BLOCK = "p, li, h1, h2, h3, h4, h5, h6, blockquote, td, th, dt, dd, summary, pre, div";
|
|
43
|
+
var SKIP = 'figure, figcaption, img, picture, svg, video, audio, canvas, script, style, noscript, button, select, [aria-hidden="true"], [data-voice-skip]';
|
|
44
|
+
var CAPTION = /^(figure|fig\.)\s*\d+[a-z]?\s*[:.ââ-]/i;
|
|
45
|
+
var cleanups = [];
|
|
46
|
+
function read(name, fallback) {
|
|
47
|
+
try { var v = win.localStorage.getItem(key + "-" + name); return v === null ? fallback : v; } catch (e) { return fallback; }
|
|
48
|
+
}
|
|
49
|
+
function write(name, value) {
|
|
50
|
+
try { win.localStorage.setItem(key + "-" + name, value); } catch (e) {}
|
|
51
|
+
}
|
|
52
|
+
function control(name) { return root.querySelector('[data-ptw="' + name + '"]'); }
|
|
53
|
+
function on(el, type, fn) { if (!el) return; el.addEventListener(type, fn); cleanups.push(function () { el.removeEventListener(type, fn); }); }
|
|
54
|
+
|
|
55
|
+
function setToggle(name, attr, value, labelOn, labelOff) {
|
|
56
|
+
root.setAttribute(attr, value ? "on" : "off");
|
|
57
|
+
write(name, value ? "on" : "off");
|
|
58
|
+
var button = control(name);
|
|
59
|
+
if (button) {
|
|
60
|
+
button.setAttribute("aria-pressed", value ? "true" : "false");
|
|
61
|
+
var label = button.querySelector("[data-ptw-label]") || button;
|
|
62
|
+
label.textContent = value ? labelOn : labelOff;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
var underline = read("underline", "on") !== "off";
|
|
66
|
+
var reader = read("reader", "off") === "on";
|
|
67
|
+
setToggle("underline", "data-underline", underline, "Underlining on", "Underlining off");
|
|
68
|
+
setToggle("reader", "data-reader", reader, "Reader mode on", "Reader mode off");
|
|
69
|
+
on(control("underline"), "click", function () { underline = !underline; setToggle("underline", "data-underline", underline, "Underlining on", "Underlining off"); });
|
|
70
|
+
on(control("reader"), "click", function () { reader = !reader; setToggle("reader", "data-reader", reader, "Reader mode on", "Reader mode off"); });
|
|
71
|
+
|
|
72
|
+
function collectBlocks(content, highlightedOnly) {
|
|
73
|
+
var walker = doc.createTreeWalker(content, 4);
|
|
74
|
+
var blocks = [];
|
|
75
|
+
var current = null, parts = [], lastMark = null;
|
|
76
|
+
function flush() {
|
|
77
|
+
var text = parts.join("").replace(/\s+/g, " ").trim();
|
|
78
|
+
if (current && text && /[0-9A-Za-zĂ-ďżż]/.test(text) && !CAPTION.test(text)) blocks.push({ element: current, text: text });
|
|
79
|
+
current = null; parts = [];
|
|
80
|
+
}
|
|
81
|
+
for (var node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
82
|
+
var parent = node.parentElement;
|
|
83
|
+
if (!parent || parent.closest(SKIP)) continue;
|
|
84
|
+
var mark = highlightedOnly ? parent.closest("mark") : null;
|
|
85
|
+
if (highlightedOnly && !mark) continue;
|
|
86
|
+
var block = parent.closest(BLOCK) || content;
|
|
87
|
+
var element = content.contains(block) ? block : content;
|
|
88
|
+
if (current !== element) { flush(); current = element; lastMark = null; }
|
|
89
|
+
if (mark && lastMark && mark !== lastMark) parts.push(" ");
|
|
90
|
+
lastMark = mark;
|
|
91
|
+
parts.push(node.nodeValue || "");
|
|
92
|
+
}
|
|
93
|
+
flush();
|
|
94
|
+
return blocks;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
var synth = win.speechSynthesis;
|
|
98
|
+
var speak = options.speak || function (text, rate) {
|
|
99
|
+
return new Promise(function (resolve) {
|
|
100
|
+
if (!synth || !win.SpeechSynthesisUtterance) { resolve(); return; }
|
|
101
|
+
var utterance = new win.SpeechSynthesisUtterance(text);
|
|
102
|
+
utterance.rate = rate;
|
|
103
|
+
utterance.onend = function () { resolve(); };
|
|
104
|
+
utterance.onerror = function () { resolve(); };
|
|
105
|
+
synth.speak(utterance);
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
var cancel = options.cancelSpeech || function () { if (synth) synth.cancel(); };
|
|
109
|
+
var run = 0;
|
|
110
|
+
var reading = null;
|
|
111
|
+
function setVoiceState(active) {
|
|
112
|
+
var button = control("voice");
|
|
113
|
+
if (!button) return;
|
|
114
|
+
button.setAttribute("aria-pressed", active ? "true" : "false");
|
|
115
|
+
var label = button.querySelector("[data-ptw-label]") || button;
|
|
116
|
+
label.textContent = active ? "Stop" : "Voice";
|
|
117
|
+
}
|
|
118
|
+
function clearReading() { if (reading) reading.removeAttribute("data-voice-reading"); reading = null; }
|
|
119
|
+
function stop() { run += 1; cancel(); clearReading(); setVoiceState(false); }
|
|
120
|
+
function rate() { var select = control("rate"); var value = Number(select && select.value); return value > 0 ? value : 1.2; }
|
|
121
|
+
function start() {
|
|
122
|
+
var content = root.querySelector(".ptw-content") || root;
|
|
123
|
+
var blocks = collectBlocks(content, underline);
|
|
124
|
+
if (blocks.length === 0) return;
|
|
125
|
+
var mine = ++run;
|
|
126
|
+
setVoiceState(true);
|
|
127
|
+
var i = 0;
|
|
128
|
+
(function next() {
|
|
129
|
+
if (mine !== run) return;
|
|
130
|
+
if (i >= blocks.length) { clearReading(); setVoiceState(false); return; }
|
|
131
|
+
var block = blocks[i++];
|
|
132
|
+
clearReading();
|
|
133
|
+
reading = block.element;
|
|
134
|
+
reading.setAttribute("data-voice-reading", "");
|
|
135
|
+
if (reading.scrollIntoView) reading.scrollIntoView({ block: "center", behavior: "smooth" });
|
|
136
|
+
speak(block.text, rate()).then(next, next);
|
|
137
|
+
})();
|
|
138
|
+
}
|
|
139
|
+
on(control("voice"), "click", function () { var button = control("voice"); if (button && button.getAttribute("aria-pressed") === "true") stop(); else start(); });
|
|
140
|
+
on(doc, "keydown", function (event) { if (event.key === "Escape") stop(); });
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
collectBlocks: function (highlightedOnly) { return collectBlocks(root.querySelector(".ptw-content") || root, highlightedOnly); },
|
|
144
|
+
stop: stop,
|
|
145
|
+
destroy: function () { stop(); cleanups.forEach(function (fn) { fn(); }); cleanups = []; },
|
|
146
|
+
};
|
|
147
|
+
}`
|
|
148
|
+
|
|
149
|
+
/** What `mountPaperReader` returns. */
|
|
150
|
+
export interface PaperReaderHandle {
|
|
151
|
+
/** The passages Voice would read, for tests and custom players. */
|
|
152
|
+
collectBlocks(highlightedOnly: boolean): Array<{ element: Element; text: string }>
|
|
153
|
+
stop(): void
|
|
154
|
+
destroy(): void
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
type Mount = (root: Element, options?: PaperReaderRuntimeOptions) => PaperReaderHandle
|
|
158
|
+
|
|
159
|
+
let compiled: Mount | null = null
|
|
160
|
+
|
|
161
|
+
/** Wire the reader controls inside `root` (see the module doc). */
|
|
162
|
+
export function mountPaperReader(root: Element, options: PaperReaderRuntimeOptions = {}): PaperReaderHandle {
|
|
163
|
+
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
164
|
+
compiled ??= new Function(`return (${READER_RUNTIME_SOURCE})`)() as Mount
|
|
165
|
+
return compiled(root, options)
|
|
166
|
+
}
|