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/package.json CHANGED
@@ -1,6 +1,86 @@
1
1
  {
2
2
  "name": "extract-refdoc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "extract-refdoc: turn any PDF, research paper, archive link or text into one shareable .refdoc.html file that opens as a full Fumadocs docs site (sidebar, contents, search, references, reader mode, voice) from a CDN-hosted runtime",
5
+ "type": "module",
6
+ "author": "vtempest",
7
+ "license": "rights.institute/prosper",
8
+ "homepage": "https://github.com/OpenSourceAGI/qwksearch-research-agent/tree/master/packages/extract-refdoc#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/OpenSourceAGI/qwksearch-research-agent.git",
12
+ "directory": "packages/extract-refdoc"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/OpenSourceAGI/qwksearch-research-agent/issues"
16
+ },
17
+ "main": "./src/index.ts",
18
+ "types": "./src/index.ts",
19
+ "exports": {
20
+ ".": "./src/index.ts",
21
+ "./widget": "./src/widget/index.ts",
22
+ "./server": "./src/server.ts",
23
+ "./runtime": "./dist/refdoc.js",
24
+ "./runtime.css": "./dist/refdoc.css",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "bin": {
28
+ "extract-refdoc": "./bin/extract-refdoc.ts"
29
+ },
30
+ "files": [
31
+ "src",
32
+ "bin",
33
+ "dist/refdoc.js",
34
+ "dist/refdoc.css",
35
+ "README.md"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "build": "bun ./scripts/build-runtime.ts",
42
+ "cli": "bun ./bin/extract-refdoc.ts",
43
+ "serve": "bun ./bin/extract-refdoc.ts serve",
44
+ "example": "bun ./scripts/build-runtime.ts && bun ./bin/extract-refdoc.ts test/fixtures/arxiv-like.html --runtime inline --out dist/example",
45
+ "typecheck": "tsc --noEmit",
46
+ "test": "vitest run",
47
+ "test:watch": "vitest",
48
+ "coverage": "vitest run --coverage"
49
+ },
50
+ "dependencies": {
51
+ "@anthropic-ai/sdk": "^1.4.0",
52
+ "extract-pdf": "^0.1.555",
53
+ "extract-webpage": "^1.2.427",
54
+ "linkedom": "^0.18.13"
55
+ },
56
+ "peerDependencies": {
57
+ "react": "^18.0.0 || ^19.0.0",
58
+ "react-dom": "^18.0.0 || ^19.0.0"
59
+ },
60
+ "devDependencies": {
61
+ "@mdx-js/mdx": "^3.1.1",
62
+ "@types/node": "^26.6.5",
63
+ "@types/react": "^19.3.0",
64
+ "@types/react-dom": "^19.3.0",
65
+ "@vitest/coverage-v8": "^5.0.5",
66
+ "fumadocs-core": "16.15.17",
67
+ "fumadocs-ui": "16.15.17",
68
+ "jsdom": "^30.1.3",
69
+ "lucide-react": "^1.66.0",
70
+ "react": "19.2.8",
71
+ "react-dom": "19.2.8",
72
+ "remark-gfm": "^4.0.1",
73
+ "typescript": "^7.0.2",
74
+ "vitest": "^5.0.5"
75
+ },
76
+ "keywords": [
77
+ "extract-refdoc",
78
+ "refdoc",
79
+ "pdf",
80
+ "paper",
81
+ "fumadocs",
82
+ "html",
83
+ "docs",
84
+ "reader"
85
+ ]
6
86
  }
package/src/ai.ts ADDED
@@ -0,0 +1,268 @@
1
+ /**
2
+ * @fileoverview The AI half: better summaries and underlining for an
3
+ * extracted paper, and outlines in the same paper format from anything.
4
+ *
5
+ * - `enhancePaperWithAi` asks the model, section by section, for a one-line
6
+ * description, a 2–4 point Section Summary, and which words of each
7
+ * paragraph to underline. Underlines come back as verbatim phrases and are
8
+ * applied with `applyUnderlines`, so the model can never change the prose;
9
+ * a phrase that isn't in the paragraph is dropped.
10
+ * - `generateOutline` turns any text, a loaded `Paper`, or just a topic into
11
+ * a new `Paper`: parts, numbered sections, summaries, argument paragraphs
12
+ * and their underlining — the Synergy Slayer shape, written fresh.
13
+ *
14
+ * The model sits behind `TextGenerator` (prompt in, text out), so any host
15
+ * can plug in its own. `createAnthropicGenerator` is the default, on the
16
+ * official Anthropic SDK.
17
+ *
18
+ * @module ai
19
+ */
20
+ import Anthropic from "@anthropic-ai/sdk"
21
+ import { finishPaper } from "./finish"
22
+ import { applyUnderlines, stripUnderlines } from "./highlight"
23
+ import { escapeMdxText, isSubheading, markdownToPlainText } from "./markdown"
24
+ import type { Paper, PaperSection, SummaryPoint } from "./types"
25
+
26
+ /** One prompt in, the model's text out. */
27
+ export type TextGenerator = (prompt: string, options?: { system?: string; signal?: AbortSignal }) => Promise<string>
28
+
29
+ /** Default model for both passes. */
30
+ export const DEFAULT_MODEL = "claude-opus-5-5"
31
+
32
+ export interface AnthropicGeneratorOptions {
33
+ /** Defaults to the SDK's own resolution (`ANTHROPIC_API_KEY`, an `ant auth login` profile, …). */
34
+ apiKey?: string
35
+ model?: string
36
+ /** Effort: outlines and underlining are judgment-heavy, so "high" by default. */
37
+ effort?: "low" | "medium" | "high" | "xhigh" | "max"
38
+ maxTokens?: number
39
+ }
40
+
41
+ /**
42
+ * Text generation on Claude via the Anthropic SDK. Streams (outputs can be
43
+ * long) and opts into server-side refusal fallbacks, so a declined request is
44
+ * retried on a fallback model inside the same call.
45
+ */
46
+ export function createAnthropicGenerator(options: AnthropicGeneratorOptions = {}): TextGenerator {
47
+ const client = new Anthropic(options.apiKey ? { apiKey: options.apiKey } : {})
48
+ const model = options.model ?? DEFAULT_MODEL
49
+ return async (prompt, { system, signal } = {}) => {
50
+ const message = await client.beta.messages
51
+ .stream(
52
+ {
53
+ model,
54
+ max_tokens: options.maxTokens ?? 64000,
55
+ betas: ["server-side-fallback-2026-07-01"],
56
+ fallbacks: "default",
57
+ output_config: { effort: options.effort ?? "high" },
58
+ ...(system ? { system } : {}),
59
+ messages: [{ role: "user", content: prompt }],
60
+ },
61
+ { signal },
62
+ )
63
+ .finalMessage()
64
+ if (message.stop_reason === "refusal") throw new Error("The model declined to process this document.")
65
+ return message.content
66
+ .map((block) => (block.type === "text" ? block.text : ""))
67
+ .join("")
68
+ .trim()
69
+ }
70
+ }
71
+
72
+ /** Pull the first JSON object out of a reply (models sometimes fence it). */
73
+ export function parseJsonReply<T>(reply: string): T {
74
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(reply)
75
+ const body = fenced ? fenced[1] : reply
76
+ const start = body.indexOf("{")
77
+ const end = body.lastIndexOf("}")
78
+ if (start < 0 || end <= start) throw new Error("The model reply held no JSON object.")
79
+ return JSON.parse(body.slice(start, end + 1)) as T
80
+ }
81
+
82
+ const STYLE_GUIDE = `Underlining works like a debate card: mark short verbatim runs of words so that, read alone in order, the marked words form complete grammatical sentences carrying the paragraph's argument. Usually 15-35% of the words, often just a few words per sentence.`
83
+
84
+ const SYSTEM = `You turn research papers and arguments into structured study pages for competitive debaters. Reply with one JSON object and nothing else.`
85
+
86
+ function asString(value: unknown): string {
87
+ return typeof value === "string" ? value.trim() : ""
88
+ }
89
+
90
+ function asSummary(value: unknown): SummaryPoint[] {
91
+ if (!Array.isArray(value)) return []
92
+ return value
93
+ .map((point) => ({ label: asString((point as SummaryPoint)?.label), text: asString((point as SummaryPoint)?.text) }))
94
+ .filter((point) => point.label && point.text)
95
+ .map((point) => ({ label: escapeMdxText(point.label.replace(/[:.]+$/, "")), text: escapeMdxText(point.text) }))
96
+ }
97
+
98
+ /** Plain text a section is sent to the model as: numbered paragraphs without marks. */
99
+ function sectionForPrompt(section: PaperSection): string {
100
+ return section.paragraphs.map((p, i) => `[${i + 1}] ${stripUnderlines(p)}`).join("\n\n")
101
+ }
102
+
103
+ interface SectionReply {
104
+ description?: string
105
+ summary?: Array<{ label: string; text: string }>
106
+ underlines?: string[][]
107
+ }
108
+
109
+ /** Description, Section Summary and underlining for one section (see the module doc). */
110
+ export async function enhanceSectionWithAi(section: PaperSection, generate: TextGenerator, paperTitle = ""): Promise<PaperSection> {
111
+ if (section.paragraphs.length === 0) return section
112
+ const prompt = `Paper: ${paperTitle}
113
+ Section: ${section.title}
114
+
115
+ ${sectionForPrompt(section)}
116
+
117
+ Return JSON:
118
+ {
119
+ "description": "one sentence stating this section's thesis",
120
+ "summary": [{"label": "2-5 word claim", "text": "1-2 sentences"}], // 2-4 points, in the section's order
121
+ "underlines": [["verbatim phrase", "..."], ...] // one array per numbered paragraph, same order
122
+ }
123
+ ${STYLE_GUIDE} Each phrase must be copied exactly from its paragraph, including punctuation and markdown characters. Use an empty array for a paragraph with nothing to mark.`
124
+ const reply = parseJsonReply<SectionReply>(await generate(prompt, { system: SYSTEM }))
125
+ const underlines = Array.isArray(reply.underlines) ? reply.underlines : []
126
+ return {
127
+ ...section,
128
+ description: asString(reply.description) ? escapeMdxText(asString(reply.description)) : section.description,
129
+ summary: asSummary(reply.summary).length > 0 ? asSummary(reply.summary) : section.summary,
130
+ paragraphs: section.paragraphs.map((paragraph, i) => {
131
+ if (isSubheading(paragraph)) return paragraph
132
+ const phrases = Array.isArray(underlines[i]) ? underlines[i].filter((p): p is string => typeof p === "string") : []
133
+ return phrases.length > 0 ? applyUnderlines(stripUnderlines(paragraph), phrases) : paragraph
134
+ }),
135
+ }
136
+ }
137
+
138
+ export interface EnhanceOptions {
139
+ /** Sections sent at once (default 3). */
140
+ concurrency?: number
141
+ /** Called after each section finishes. */
142
+ onProgress?: (done: number, total: number) => void
143
+ }
144
+
145
+ /** Run the AI pass over every section, then fill anything still missing offline. */
146
+ export async function enhancePaperWithAi(paper: Paper, generate: TextGenerator, options: EnhanceOptions = {}): Promise<Paper> {
147
+ const sections = [...paper.sections]
148
+ const concurrency = Math.max(1, options.concurrency ?? 3)
149
+ let next = 0
150
+ let done = 0
151
+ const worker = async () => {
152
+ while (next < sections.length) {
153
+ const index = next++
154
+ try {
155
+ sections[index] = await enhanceSectionWithAi(sections[index], generate, paper.title)
156
+ } catch {
157
+ // One bad reply leaves that section to the offline pass rather than failing the paper.
158
+ }
159
+ options.onProgress?.(++done, sections.length)
160
+ }
161
+ }
162
+ await Promise.all(Array.from({ length: Math.min(concurrency, sections.length) }, worker))
163
+ return finishPaper({ ...paper, sections })
164
+ }
165
+
166
+ interface OutlineReply {
167
+ title?: string
168
+ description?: string
169
+ abstract?: { text?: string; underlines?: string[] } | string
170
+ keywords?: string[]
171
+ sections?: Array<{
172
+ part?: string
173
+ title?: string
174
+ description?: string
175
+ summary?: Array<{ label: string; text: string }>
176
+ paragraphs?: Array<{ text?: string; underlines?: string[] } | string>
177
+ }>
178
+ references?: string[]
179
+ }
180
+
181
+ /** Largest source text sent in one request, in characters (about 250k tokens). */
182
+ export const MAX_OUTLINE_SOURCE_CHARS = 1_000_000
183
+
184
+ /** A paper's plain text, for the outline prompt. */
185
+ export function paperToPlainText(paper: Paper): string {
186
+ const parts = [paper.title, paper.abstract ? `Abstract. ${markdownToPlainText(paper.abstract)}` : ""]
187
+ for (const section of paper.sections) {
188
+ parts.push(`\n## ${section.title}`)
189
+ for (const paragraph of section.paragraphs) parts.push(markdownToPlainText(paragraph))
190
+ }
191
+ if (paper.references.length > 0) parts.push("\n## References", ...paper.references.map(markdownToPlainText))
192
+ return parts.filter(Boolean).join("\n\n")
193
+ }
194
+
195
+ export interface OutlineOptions {
196
+ /** Steer the outline: an angle, a resolution, a side to argue. */
197
+ focus?: string
198
+ /** Rough number of sections (default: the model decides, usually 4-10). */
199
+ sections?: number
200
+ }
201
+
202
+ /**
203
+ * An outline in the paper format from any input: a `Paper` you loaded, any
204
+ * pasted text, or just a topic (see the module doc).
205
+ */
206
+ export async function generateOutline(source: Paper | string, generate: TextGenerator, options: OutlineOptions = {}): Promise<Paper> {
207
+ const text = typeof source === "string" ? source.trim() : paperToPlainText(source)
208
+ if (!text) throw new Error("Nothing to outline.")
209
+ if (text.length > MAX_OUTLINE_SOURCE_CHARS) {
210
+ throw new Error(`The source is ${text.length.toLocaleString()} characters; outlines take up to ${MAX_OUTLINE_SOURCE_CHARS.toLocaleString()}. Split it and outline each part.`)
211
+ }
212
+ const isTopic = typeof source === "string" && text.split(/\s+/).length < 40
213
+ const prompt = `${isTopic ? `Topic: ${text}\n\nWrite an original argumentative outline on this topic.` : `Source:\n<source>\n${text}\n</source>\n\nOutline this source faithfully: keep its argument, its order and its evidence; do not invent citations.`}
214
+ ${options.focus ? `Focus: ${options.focus}\n` : ""}${options.sections ? `Aim for about ${options.sections} sections.\n` : ""}
215
+ Return JSON:
216
+ {
217
+ "title": "...",
218
+ "description": "one-line subtitle",
219
+ "abstract": {"text": "3-5 sentence abstract", "underlines": ["verbatim phrase", ...]},
220
+ "keywords": ["...", ...],
221
+ "sections": [
222
+ {
223
+ "part": "optional part heading this section opens, e.g. Part I. The Standard",
224
+ "title": "section title, no number",
225
+ "description": "one sentence thesis",
226
+ "summary": [{"label": "2-5 word claim", "text": "1-2 sentences"}],
227
+ "paragraphs": [{"text": "a full argument paragraph, 80-200 words, plain prose", "underlines": ["verbatim phrase", ...]}]
228
+ }
229
+ ],
230
+ "references": ["Chicago-style reference", ...]
231
+ }
232
+ Each section gets 2-4 summary points and 2-5 paragraphs. Write plain prose: no markdown, no HTML. ${STYLE_GUIDE} Underline phrases must be copied exactly from their own paragraph. Only list references that appear in the source${isTopic ? " (for a topic, an empty list)" : ""}.`
233
+ const reply = parseJsonReply<OutlineReply>(await generate(prompt, { system: SYSTEM }))
234
+
235
+ const underlined = (value: { text?: string; underlines?: string[] } | string | undefined): string => {
236
+ if (!value) return ""
237
+ if (typeof value === "string") return escapeMdxText(value.trim())
238
+ const body = escapeMdxText(asString(value.text))
239
+ const phrases = (Array.isArray(value.underlines) ? value.underlines : []).filter((p): p is string => typeof p === "string").map(escapeMdxText)
240
+ return body ? applyUnderlines(body, phrases) : ""
241
+ }
242
+
243
+ const sections: PaperSection[] = (Array.isArray(reply.sections) ? reply.sections : [])
244
+ .map((section) => ({
245
+ title: asString(section.title),
246
+ part: asString(section.part) || undefined,
247
+ description: asString(section.description) ? escapeMdxText(asString(section.description)) : undefined,
248
+ summary: asSummary(section.summary),
249
+ paragraphs: (Array.isArray(section.paragraphs) ? section.paragraphs : []).map(underlined).filter(Boolean),
250
+ }))
251
+ .filter((section) => section.title && (section.paragraphs.length > 0 || section.summary.length > 0))
252
+ if (sections.length === 0) throw new Error("The model returned an outline with no sections.")
253
+
254
+ const base = typeof source === "string" ? null : source
255
+ return finishPaper({
256
+ title: asString(reply.title) || base?.title || "Outline",
257
+ description: asString(reply.description) ? escapeMdxText(asString(reply.description)) : undefined,
258
+ author: base?.author,
259
+ date: base?.date,
260
+ sourceUrl: base?.sourceUrl,
261
+ cite: base?.cite,
262
+ abstract: underlined(reply.abstract) || undefined,
263
+ keywords: Array.isArray(reply.keywords) ? reply.keywords.filter((k): k is string => typeof k === "string").map(escapeMdxText) : undefined,
264
+ figure: base?.figure,
265
+ sections,
266
+ references: Array.isArray(reply.references) ? reply.references.filter((r): r is string => typeof r === "string").map(escapeMdxText) : base?.references ?? [],
267
+ })
268
+ }
package/src/finish.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @fileoverview The offline pass that fills in what the extractor can't give:
3
+ * card underlining on every paragraph, a one-line description per section,
4
+ * and a "Section Summary" of bold-lead points drawn from each section's
5
+ * underlined text. The AI pass (`ai.ts`) writes better versions of all three;
6
+ * this one runs with no model and no network.
7
+ *
8
+ * @module finish
9
+ */
10
+ import { autoUnderline, splitSentences, stripUnderlines, underlinedRuns } from "./highlight"
11
+ import { escapeMdxText, isSubheading, markdownToPlainText } from "./markdown"
12
+ import type { Paper, PaperSection, SummaryPoint } from "./types"
13
+
14
+ /** Most points a Section Summary gets. */
15
+ const MAX_SUMMARY_POINTS = 4
16
+
17
+ /** Longest description, in characters (frontmatter `description`). */
18
+ const MAX_DESCRIPTION = 200
19
+
20
+ /** Trim to a word boundary, adding an ellipsis when cut. */
21
+ export function clip(text: string, max: number): string {
22
+ if (text.length <= max) return text
23
+ const cut = text.slice(0, max).replace(/\s+\S*$/, "")
24
+ return `${cut.replace(/[,;:\s]+$/, "")}…`
25
+ }
26
+
27
+ /** Capitalize the first letter. */
28
+ function capitalize(text: string): string {
29
+ return text.charAt(0).toUpperCase() + text.slice(1)
30
+ }
31
+
32
+ /** One summary point per substantial paragraph: its first underlined run as the label, its first sentence as the text. */
33
+ export function summarizeSection(section: PaperSection): SummaryPoint[] {
34
+ const points: SummaryPoint[] = []
35
+ for (const paragraph of section.paragraphs) {
36
+ if (points.length >= MAX_SUMMARY_POINTS) break
37
+ if (isSubheading(paragraph)) continue
38
+ const plain = markdownToPlainText(stripUnderlines(paragraph))
39
+ if (plain.split(/\s+/).length < 12) continue
40
+ const runs = underlinedRuns(paragraph).map(markdownToPlainText)
41
+ const label = runs[0] ? clip(capitalize(runs[0].split(/\s+/).slice(0, 6).join(" ")), 60) : clip(plain.split(/\s+/).slice(0, 5).join(" "), 60)
42
+ const first = splitSentences(plain)[0] ?? plain
43
+ // Summaries are written back into MDX, so plain text is escaped again.
44
+ points.push({ label: escapeMdxText(label.replace(/[.,;:]+$/, "")), text: escapeMdxText(clip(first, 280)) })
45
+ }
46
+ return points
47
+ }
48
+
49
+ /** The section's first sentence, as its page description. */
50
+ export function describeSection(section: PaperSection): string | undefined {
51
+ const first = section.paragraphs.find((p) => !isSubheading(p) && markdownToPlainText(p).split(/\s+/).length >= 8)
52
+ if (!first) return undefined
53
+ const sentence = splitSentences(markdownToPlainText(stripUnderlines(first)))[0]
54
+ return sentence ? escapeMdxText(clip(sentence, MAX_DESCRIPTION)) : undefined
55
+ }
56
+
57
+ export interface FinishOptions {
58
+ /** Add `==` underlining where a paragraph has none (default true). */
59
+ underline?: boolean
60
+ }
61
+
62
+ /** Fill in underlining, descriptions and summaries a paper is missing (see the module doc). */
63
+ export function finishPaper(paper: Paper, options: FinishOptions = {}): Paper {
64
+ const { underline = true } = options
65
+ const sections = paper.sections.map((section) => {
66
+ const paragraphs = underline
67
+ ? section.paragraphs.map((p) => (isSubheading(p) ? p : autoUnderline(p)))
68
+ : section.paragraphs
69
+ const next = { ...section, paragraphs }
70
+ return {
71
+ ...next,
72
+ description: section.description ?? describeSection(next),
73
+ summary: section.summary.length > 0 ? section.summary : summarizeSection(next),
74
+ }
75
+ })
76
+ const description =
77
+ paper.description ??
78
+ (paper.abstract ? escapeMdxText(clip(splitSentences(markdownToPlainText(paper.abstract))[0] ?? "", MAX_DESCRIPTION)) : undefined)
79
+ return {
80
+ ...paper,
81
+ description: description || undefined,
82
+ abstract: paper.abstract && underline ? autoUnderline(paper.abstract) : paper.abstract,
83
+ sections,
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Extractive outline: the same paper reduced to what a debater would read
89
+ * aloud — each paragraph cut down to its underlined words, Section Summaries
90
+ * kept. Works offline on anything `finishPaper` has underlined.
91
+ */
92
+ export function readOnlyUnderlined(paper: Paper): Paper {
93
+ return {
94
+ ...paper,
95
+ sections: paper.sections.map((section) => ({
96
+ ...section,
97
+ paragraphs: section.paragraphs
98
+ .map((p) => (isSubheading(p) ? p : underlinedRuns(p).join(" … ")))
99
+ .filter(Boolean)
100
+ .map((text) => (isSubheading(text) ? text : `==${text}==`))
101
+ // A subheading with nothing under it before the next one is dropped.
102
+ .filter((p, i, all) => !isSubheading(p) || (all[i + 1] !== undefined && !isSubheading(all[i + 1]))),
103
+ })),
104
+ }
105
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * @fileoverview Card underlining: the `==text==` marks the Underlining toggle
3
+ * shows, written so the marked words read on their own as a sentence, the way
4
+ * a debater reads only the underlined part of a card.
5
+ *
6
+ * Two ways to get them:
7
+ * - `applyUnderlines` wraps phrases chosen elsewhere (the AI pass in
8
+ * `ai.ts`) — only phrases that occur verbatim in the paragraph are marked,
9
+ * so the prose itself is never changed.
10
+ * - `autoUnderline` is the offline fallback: it marks the core clause of the
11
+ * paragraph's topic sentence and of its strongest claim sentence.
12
+ *
13
+ * @module highlight
14
+ */
15
+
16
+ /** Remove every `==` marker, leaving the prose. */
17
+ export function stripUnderlines(markdown: string): string {
18
+ return markdown.replace(/==/g, "")
19
+ }
20
+
21
+ /** True when the paragraph already carries underlining. */
22
+ export function hasUnderlines(markdown: string): boolean {
23
+ return /==[^=]+==/.test(markdown)
24
+ }
25
+
26
+ /** The underlined runs of a paragraph, in order. */
27
+ export function underlinedRuns(markdown: string): string[] {
28
+ return Array.from(markdown.matchAll(/==([^=]+)==/g), (match) => match[1].trim()).filter(Boolean)
29
+ }
30
+
31
+ /**
32
+ * Wrap each phrase that occurs verbatim in `paragraph` with `==…==`. Phrases
33
+ * that are missing, overlap an earlier one, or would split a link or other
34
+ * markdown token are skipped. Existing marks are kept.
35
+ */
36
+ export function applyUnderlines(paragraph: string, phrases: string[]): string {
37
+ const ranges: Array<[number, number]> = []
38
+ // Positions already inside marks, links or images stay untouched.
39
+ const blocked: Array<[number, number]> = []
40
+ for (const match of paragraph.matchAll(/==[^=]+==|!?\[[^\]]*\]\([^)]*\)|`[^`]*`/g)) {
41
+ blocked.push([match.index ?? 0, (match.index ?? 0) + match[0].length])
42
+ }
43
+ const overlaps = (start: number, end: number, list: Array<[number, number]>) =>
44
+ list.some(([s, e]) => start < e && end > s)
45
+
46
+ for (const raw of phrases) {
47
+ const phrase = raw.trim().replace(/^==|==$/g, "")
48
+ if (phrase.length < 2) continue
49
+ let from = 0
50
+ while (from < paragraph.length) {
51
+ const start = paragraph.indexOf(phrase, from)
52
+ if (start < 0) break
53
+ const end = start + phrase.length
54
+ if (!overlaps(start, end, blocked) && !overlaps(start, end, ranges)) {
55
+ ranges.push([start, end])
56
+ break
57
+ }
58
+ from = start + 1
59
+ }
60
+ }
61
+ ranges.sort((a, b) => a[0] - b[0])
62
+ let out = ""
63
+ let cursor = 0
64
+ for (const [start, end] of ranges) {
65
+ out += `${paragraph.slice(cursor, start)}==${paragraph.slice(start, end)}==`
66
+ cursor = end
67
+ }
68
+ return out + paragraph.slice(cursor)
69
+ }
70
+
71
+ /** Split text into sentences, keeping common abbreviations together. */
72
+ export function splitSentences(text: string): string[] {
73
+ const parts = text.match(/[^.!?]+(?:[.!?]+["'”’)\]]*|$)/g) ?? []
74
+ const sentences: string[] = []
75
+ for (const part of parts) {
76
+ const previous = sentences[sentences.length - 1]
77
+ // "e.g." / "et al." / "U.S." / a single initial: glue to the previous fragment.
78
+ if (previous && /(?:\b(?:e\.g|i\.e|et al|vs|cf|Dr|Mr|Ms|Mrs|No|Fig|U\.S|[a-zA-Z]))\.$/.test(previous.trim())) {
79
+ sentences[sentences.length - 1] = previous + part
80
+ } else if (part.trim()) {
81
+ sentences.push(part)
82
+ }
83
+ }
84
+ return sentences.map((s) => s.trim()).filter(Boolean)
85
+ }
86
+
87
+ /** Words that signal the sentence carries the paragraph's claim. */
88
+ const CLAIM_SIGNAL =
89
+ /\b(therefore|thus|hence|so that|because|must|should|cannot|can't|shows?|proves?|means|we argue|this paper|in short|the point|key|critical|crucial|instead|rather than|outweighs?)\b/i
90
+
91
+ const TRAILING_FUNCTION_WORD = /^(of|the|a|an|to|in|and|or|but|for|with|by|on|at|from|as|that|which|who|is|are|was|were|be|its|their|this|these|than)$/i
92
+
93
+ /** The core clause of a sentence: up to its first clause break, else its first dozen words. */
94
+ export function coreClause(sentence: string): string {
95
+ const clean = sentence.replace(/==/g, "").trim()
96
+ const breakAt = clean.search(/[,;:—–(]|\s-\s/)
97
+ const head = breakAt > 0 ? clean.slice(0, breakAt) : clean
98
+ const words = head.split(/\s+/).filter(Boolean)
99
+ const picked = words.length >= 4 ? words.slice(0, 18) : clean.split(/\s+/).slice(0, 12)
100
+ // Don't end a marked run on a dangling function word ("…positions of").
101
+ while (picked.length > 4 && TRAILING_FUNCTION_WORD.test(picked[picked.length - 1])) picked.pop()
102
+ return picked
103
+ .join(" ")
104
+ .replace(/[\s.,;:!?"'“”‘’)\]]+$/, "")
105
+ .replace(/^[\s"'“”‘’([]+/, "")
106
+ }
107
+
108
+ /**
109
+ * Offline underlining: marks the core clause of the topic (first) sentence
110
+ * and of the strongest claim sentence after it. Paragraphs that already carry
111
+ * marks, or are too short to be a card, are returned unchanged.
112
+ */
113
+ export function autoUnderline(paragraph: string): string {
114
+ if (hasUnderlines(paragraph)) return paragraph
115
+ // Mark against the paragraph without link/image syntax in the way.
116
+ const sentences = splitSentences(paragraph.replace(/!?\[[^\]]*\]\([^)]*\)/g, " "))
117
+ if (sentences.length === 0 || paragraph.split(/\s+/).length < 12) return paragraph
118
+ const phrases = [coreClause(sentences[0])]
119
+ const claim = sentences.slice(1).find((sentence) => CLAIM_SIGNAL.test(sentence))
120
+ if (claim) phrases.push(coreClause(claim))
121
+ return applyUnderlines(
122
+ paragraph,
123
+ phrases.filter((phrase) => phrase.split(/\s+/).length >= 3 && !/[*`[\]]/.test(phrase)),
124
+ )
125
+ }