@v1nvn/readability 0.44.0 → 0.45.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 +3 -3
- package/package.json +7 -9
- package/src/cli.ts +134 -0
- package/src/config.ts +42 -0
- package/src/dev.ts +77 -0
- package/src/errors.ts +19 -0
- package/src/handler.ts +8 -0
- package/src/host-sampling.ts +86 -0
- package/src/index.ts +27 -0
- package/src/logger.ts +3 -0
- package/src/output/format.ts +132 -0
- package/src/pipeline/cell-text.ts +56 -0
- package/src/pipeline/context.ts +88 -0
- package/src/pipeline/dom.ts +23 -0
- package/src/pipeline/footnotes.ts +181 -0
- package/src/pipeline/math.ts +130 -0
- package/src/pipeline/normalize.ts +594 -0
- package/src/pipeline/readability.ts +36 -0
- package/src/pipeline/resolver.ts +143 -0
- package/src/pipeline/sanitize.ts +42 -0
- package/src/pipeline/tables.ts +286 -0
- package/src/pipeline/turndown.ts +191 -0
- package/src/pipeline/urls.ts +13 -0
- package/src/policy/chunk.ts +482 -0
- package/src/policy/diagnostics.ts +96 -0
- package/src/policy/explain.ts +182 -0
- package/src/policy/fallback.ts +110 -0
- package/src/policy/gating.ts +106 -0
- package/src/policy/grid-detector.ts +313 -0
- package/src/policy/identifiers.ts +75 -0
- package/src/policy/images.ts +64 -0
- package/src/policy/list-detector.ts +308 -0
- package/src/policy/lost-signal.ts +69 -0
- package/src/policy/markdown.ts +76 -0
- package/src/policy/metadata.ts +312 -0
- package/src/policy/outline-chains.ts +215 -0
- package/src/policy/outline.ts +89 -0
- package/src/policy/pagination.ts +104 -0
- package/src/policy/presets.ts +142 -0
- package/src/policy/section.ts +127 -0
- package/src/policy/selector-lint.ts +186 -0
- package/src/policy/sibling-scan.ts +99 -0
- package/src/policy/text.ts +36 -0
- package/src/policy/truncate.ts +59 -0
- package/src/preset-cache.ts +221 -0
- package/src/resources.ts +317 -0
- package/src/sampling.ts +74 -0
- package/src/server.ts +85 -0
- package/src/tools/chunk_text.ts +65 -0
- package/src/tools/explain.ts +299 -0
- package/src/tools/extract.ts +368 -0
- package/src/tools/extract_grid.ts +90 -0
- package/src/tools/extract_links.ts +138 -0
- package/src/tools/extract_list.ts +97 -0
- package/src/tools/extract_metadata.ts +102 -0
- package/src/tools/extract_section.ts +84 -0
- package/src/tools/extract_tables.ts +101 -0
- package/src/tools/html-source.ts +40 -0
- package/src/tools/html_to_markdown.ts +180 -0
- package/src/tools/outline.ts +77 -0
- package/src/tools/output-schema.ts +715 -0
- package/src/tools/schemas.ts +442 -0
- package/src/tools/suggest-preset.ts +708 -0
- package/src/types/jsdom.d.ts +15 -0
- package/src/types/turndown-plugin-gfm.d.ts +11 -0
- package/dist/assets/cli-Dfjg7dOQ.js +0 -76
- package/dist/assets/cli-Dfjg7dOQ.js.map +0 -1
- package/dist/assets/extract-CdDp-KwX.js +0 -2880
- package/dist/assets/extract-CdDp-KwX.js.map +0 -1
- package/dist/index.js +0 -2267
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { absolutize } from '../pipeline/urls.ts';
|
|
2
|
+
import {
|
|
3
|
+
CONTAINER_TAGS,
|
|
4
|
+
describeSelector,
|
|
5
|
+
groupChildrenByShape,
|
|
6
|
+
stripLandmarkChrome,
|
|
7
|
+
} from './sibling-scan.ts';
|
|
8
|
+
|
|
9
|
+
export interface ListItem {
|
|
10
|
+
readonly score: number;
|
|
11
|
+
readonly snippet: string;
|
|
12
|
+
readonly title: string;
|
|
13
|
+
readonly url: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type ListConfidence = 'high' | 'low' | 'medium';
|
|
17
|
+
|
|
18
|
+
export interface ListDetectionResult {
|
|
19
|
+
readonly confidence: ListConfidence;
|
|
20
|
+
readonly containerSelector: string;
|
|
21
|
+
readonly detected: boolean;
|
|
22
|
+
readonly itemCount: number;
|
|
23
|
+
readonly items: readonly ListItem[];
|
|
24
|
+
readonly itemTag: string;
|
|
25
|
+
readonly note: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Three siblings of the same shape (tag + class signature), each carrying a
|
|
29
|
+
// real navigation anchor, is the smallest cluster that is not accidentally a
|
|
30
|
+
// nav menu or a article's <ul> of inline links. Below this the detector
|
|
31
|
+
// refuses to claim the page is a list.
|
|
32
|
+
const MIN_ITEMS = 3;
|
|
33
|
+
|
|
34
|
+
// Six-or-more items with non-trivial body text per item is the empirical
|
|
35
|
+
// signature of a true index/search/blog-roll page (HN shows 30, Google ~10,
|
|
36
|
+
// WP indexes ~10). Used to separate `high` from `medium` confidence so a
|
|
37
|
+
// 3-item related-links block doesn't masquerade as a feed.
|
|
38
|
+
const HIGH_CONF_ITEMS = 6;
|
|
39
|
+
const HIGH_CONF_AVG_SCORE = 30;
|
|
40
|
+
|
|
41
|
+
const MAX_SNIPPET_CHARS = 200;
|
|
42
|
+
|
|
43
|
+
// href schemes that don't point at a list target. Excluding them keeps mailto:
|
|
44
|
+
// /tel:/javascript:/ anchors from satisfying the "every item has a link" bar.
|
|
45
|
+
function isNavigationHref(href: string): boolean {
|
|
46
|
+
if (!href || href === '#') {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
const lower = href.toLowerCase();
|
|
50
|
+
return (
|
|
51
|
+
!lower.startsWith('javascript:') &&
|
|
52
|
+
!lower.startsWith('mailto:') &&
|
|
53
|
+
!lower.startsWith('tel:')
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function anchorText(anchor: HTMLAnchorElement): string {
|
|
58
|
+
return anchor.textContent.replace(/\s+/g, ' ').trim();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Anchors with a navigation-worthy href AND visible text. Lives inside the
|
|
62
|
+
// candidate child so a single <a href="#"> footer link doesn't satisfy the
|
|
63
|
+
// "every item has a link" requirement.
|
|
64
|
+
function navigationAnchors(child: Element): HTMLAnchorElement[] {
|
|
65
|
+
const anchors: HTMLAnchorElement[] = [];
|
|
66
|
+
for (const el of child.querySelectorAll('a[href]')) {
|
|
67
|
+
const anchor = el as HTMLAnchorElement;
|
|
68
|
+
const href = anchor.getAttribute('href') ?? '';
|
|
69
|
+
if (!isNavigationHref(href)) {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (anchorText(anchor).length === 0) {
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
anchors.push(anchor);
|
|
76
|
+
}
|
|
77
|
+
return anchors;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function pickPrimaryAnchor(
|
|
81
|
+
anchors: readonly HTMLAnchorElement[],
|
|
82
|
+
): HTMLAnchorElement {
|
|
83
|
+
let primary = anchors[0];
|
|
84
|
+
let best = anchorText(primary).length;
|
|
85
|
+
for (let i = 1; i < anchors.length; i++) {
|
|
86
|
+
const len = anchorText(anchors[i]).length;
|
|
87
|
+
if (len > best) {
|
|
88
|
+
primary = anchors[i];
|
|
89
|
+
best = len;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return primary;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function clipSnippet(raw: string): string {
|
|
96
|
+
const collapsed = raw.replace(/\s+/g, ' ').trim();
|
|
97
|
+
if (collapsed.length <= MAX_SNIPPET_CHARS) {
|
|
98
|
+
return collapsed;
|
|
99
|
+
}
|
|
100
|
+
return `${collapsed.slice(0, MAX_SNIPPET_CHARS)}…`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Score = primary-anchor text length + non-link body text length. A pure
|
|
104
|
+
// link-density penalty (textLength * (1 - linkDensity)) ranks HN's subtext
|
|
105
|
+
// rows ABOVE the title rows because the title row is anchor-dominated (its
|
|
106
|
+
// title IS the link), so non-link body alone mis-ranks. Adding the primary
|
|
107
|
+
// anchor's text length rewards long titles (real feed items) over short nav
|
|
108
|
+
// labels ("Home", "Sign in"), which is the signal we actually want for both
|
|
109
|
+
// the candidate tiebreak and the high-confidence threshold.
|
|
110
|
+
function scoreItem(
|
|
111
|
+
textLength: number,
|
|
112
|
+
linkTextLength: number,
|
|
113
|
+
primaryAnchorTextLength: number,
|
|
114
|
+
): number {
|
|
115
|
+
if (textLength === 0) {
|
|
116
|
+
return 0;
|
|
117
|
+
}
|
|
118
|
+
const nonLinkBody = Math.max(0, textLength - linkTextLength);
|
|
119
|
+
return primaryAnchorTextLength + nonLinkBody;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function extractItem(
|
|
123
|
+
child: Element,
|
|
124
|
+
baseUrl: string | undefined,
|
|
125
|
+
): ListItem | null {
|
|
126
|
+
const anchors = navigationAnchors(child);
|
|
127
|
+
if (anchors.length === 0) {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
const primary = pickPrimaryAnchor(anchors);
|
|
131
|
+
const title = anchorText(primary);
|
|
132
|
+
if (!title) {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const href = primary.getAttribute('href') ?? '';
|
|
136
|
+
const url = absolutize(href, baseUrl);
|
|
137
|
+
if (!url) {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const fullText = child.textContent.replace(/\s+/g, ' ').trim();
|
|
142
|
+
// Snippet = body text with the title peeled off the front when present, so
|
|
143
|
+
// the title link doesn't echo into the excerpt.
|
|
144
|
+
const snippet =
|
|
145
|
+
fullText === title
|
|
146
|
+
? ''
|
|
147
|
+
: fullText.startsWith(title)
|
|
148
|
+
? clipSnippet(fullText.slice(title.length + 1))
|
|
149
|
+
: clipSnippet(fullText);
|
|
150
|
+
|
|
151
|
+
const linkTextLength = anchors.reduce(
|
|
152
|
+
(sum, anchor) => sum + anchorText(anchor).length,
|
|
153
|
+
0,
|
|
154
|
+
);
|
|
155
|
+
return {
|
|
156
|
+
score: scoreItem(fullText.length, linkTextLength, title.length),
|
|
157
|
+
snippet,
|
|
158
|
+
title,
|
|
159
|
+
url,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
interface Candidate {
|
|
164
|
+
readonly containerSelector: string;
|
|
165
|
+
readonly distinctPathnames: number;
|
|
166
|
+
readonly items: readonly ListItem[];
|
|
167
|
+
readonly itemTag: string;
|
|
168
|
+
readonly totalScore: number;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Count of distinct URL pathnames a candidate's items point at. This is the
|
|
172
|
+
// signal that separates a real feed from a metadata cluster: a feed's items
|
|
173
|
+
// each navigate to a distinct destination (HN title rows link to ~30 different
|
|
174
|
+
// external stories; a blog index links to /post-1../post-N; a search results
|
|
175
|
+
// page links to a heterogeneous set of sites), so distinctPathnames ≈ item
|
|
176
|
+
// count. A metadata cluster's items all navigate to the same internal route —
|
|
177
|
+
// HN's subtext rows are 31 anchors all pointing at news.ycombinator.com/item?id=…,
|
|
178
|
+
// collapsing to pathname=/item (distinctPathnames = 1). Counting items alone
|
|
179
|
+
// lets subtext win on HN (31 vs 30 title rows) because of the trailing "More"
|
|
180
|
+
// row; counting distinct destinations restores the title group as the winner.
|
|
181
|
+
function distinctPathnames(items: readonly ListItem[]): number {
|
|
182
|
+
const paths = new Set<string>();
|
|
183
|
+
for (const item of items) {
|
|
184
|
+
try {
|
|
185
|
+
paths.add(new URL(item.url).pathname);
|
|
186
|
+
} catch {
|
|
187
|
+
paths.add(item.url);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return paths.size;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function collectCandidates(document: Document, baseUrl: string | undefined) {
|
|
194
|
+
const candidates: Candidate[] = [];
|
|
195
|
+
for (const container of document.querySelectorAll('*')) {
|
|
196
|
+
if (!CONTAINER_TAGS.has(container.tagName)) {
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const groups = groupChildrenByShape(container);
|
|
200
|
+
for (const children of groups.values()) {
|
|
201
|
+
if (children.length < MIN_ITEMS) {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
// EVERY member must carry a real anchor — one linkless <li> breaks
|
|
205
|
+
// homogeneity and rejects the group, which is what keeps a <ul> of
|
|
206
|
+
// plain-text list items (e.g. recipe ingredients) from triggering.
|
|
207
|
+
if (!children.every(child => navigationAnchors(child).length > 0)) {
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const items: ListItem[] = [];
|
|
211
|
+
for (const child of children) {
|
|
212
|
+
const item = extractItem(child, baseUrl);
|
|
213
|
+
if (item) {
|
|
214
|
+
items.push(item);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (items.length < MIN_ITEMS) {
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
candidates.push({
|
|
221
|
+
containerSelector: describeSelector(container),
|
|
222
|
+
distinctPathnames: distinctPathnames(items),
|
|
223
|
+
itemTag: children[0].tagName,
|
|
224
|
+
items,
|
|
225
|
+
totalScore: items.reduce((sum, item) => sum + item.score, 0),
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return candidates;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function confidenceFor(items: readonly ListItem[]): ListConfidence {
|
|
233
|
+
if (items.length < MIN_ITEMS) {
|
|
234
|
+
return 'low';
|
|
235
|
+
}
|
|
236
|
+
if (items.length >= HIGH_CONF_ITEMS) {
|
|
237
|
+
const avg = items.reduce((sum, item) => sum + item.score, 0) / items.length;
|
|
238
|
+
return avg >= HIGH_CONF_AVG_SCORE ? 'high' : 'medium';
|
|
239
|
+
}
|
|
240
|
+
return 'medium';
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function notDetected(note: string): ListDetectionResult {
|
|
244
|
+
return {
|
|
245
|
+
confidence: 'low',
|
|
246
|
+
containerSelector: '',
|
|
247
|
+
detected: false,
|
|
248
|
+
itemCount: 0,
|
|
249
|
+
itemTag: '',
|
|
250
|
+
items: [],
|
|
251
|
+
note,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Detect a list/feed/index structure on a non-article page. Strips chrome
|
|
256
|
+
// (nav/header/footer/aside + ARIA roles) first so an article's menu doesn't
|
|
257
|
+
// look like a 4-item feed, then walks for containers whose direct children
|
|
258
|
+
// form a homogeneous sibling group of ≥3 elements each carrying a real anchor.
|
|
259
|
+
// Winner selection prefers the candidate whose items navigate to the most
|
|
260
|
+
// distinct destinations — the signature of a real feed — over a same-path
|
|
261
|
+
// metadata cluster (HN's subtext rows all link to /item?id=…). Item count is
|
|
262
|
+
// the second key (a 30-item feed beats a 4-item related-links block) and total
|
|
263
|
+
// per-item score breaks remaining ties.
|
|
264
|
+
export function detectList(
|
|
265
|
+
document: Document,
|
|
266
|
+
baseUrl?: string,
|
|
267
|
+
): ListDetectionResult {
|
|
268
|
+
stripLandmarkChrome(document);
|
|
269
|
+
|
|
270
|
+
const candidates = collectCandidates(document, baseUrl);
|
|
271
|
+
if (candidates.length === 0) {
|
|
272
|
+
return notDetected(
|
|
273
|
+
'not a list: no repeated item structure with links (≥3 same-shape siblings each carrying an anchor, outside nav/header/footer/aside)',
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
let winner = candidates[0];
|
|
278
|
+
for (let i = 1; i < candidates.length; i++) {
|
|
279
|
+
const candidate = candidates[i];
|
|
280
|
+
if (
|
|
281
|
+
candidate.distinctPathnames > winner.distinctPathnames ||
|
|
282
|
+
(candidate.distinctPathnames === winner.distinctPathnames &&
|
|
283
|
+
candidate.items.length > winner.items.length) ||
|
|
284
|
+
(candidate.distinctPathnames === winner.distinctPathnames &&
|
|
285
|
+
candidate.items.length === winner.items.length &&
|
|
286
|
+
candidate.totalScore > winner.totalScore)
|
|
287
|
+
) {
|
|
288
|
+
winner = candidate;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (winner.items.length < MIN_ITEMS) {
|
|
293
|
+
return notDetected(
|
|
294
|
+
'not a list: best candidate had fewer than 3 extracted items',
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const items = winner.items;
|
|
299
|
+
return {
|
|
300
|
+
confidence: confidenceFor(items),
|
|
301
|
+
containerSelector: winner.containerSelector,
|
|
302
|
+
detected: true,
|
|
303
|
+
itemCount: items.length,
|
|
304
|
+
itemTag: winner.itemTag,
|
|
305
|
+
items,
|
|
306
|
+
note: `detected ${items.length} ${winner.itemTag} items in ${winner.containerSelector}`,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { GatingSignal } from './gating.ts';
|
|
2
|
+
|
|
3
|
+
import { countWords } from './text.ts';
|
|
4
|
+
|
|
5
|
+
// Below this the extraction cannot be the article a reader came for. The
|
|
6
|
+
// measured corpus floor: the smallest healthy extract is gatwick at 435 words;
|
|
7
|
+
// the smallest known-lost one (WIRED's metered barrier) still carries 180.
|
|
8
|
+
export const NEAR_EMPTY_WORDS = 120;
|
|
9
|
+
|
|
10
|
+
// Curated junk signatures over the EXTRACTED text, not the page — gating's
|
|
11
|
+
// METERED_TEXT_RE reads the whole document, which is a different question.
|
|
12
|
+
// Each entry is measured on a real capture: the first two are the Daily Mail
|
|
13
|
+
// player controls that survive inside itemprop="articleBody" (dailymail-a66),
|
|
14
|
+
// the third is the metered barrier WIRED prints when the article itself was
|
|
15
|
+
// truncated server-side.
|
|
16
|
+
const DEBRIS_PROBES: readonly {
|
|
17
|
+
readonly label: string;
|
|
18
|
+
readonly pattern: RegExp;
|
|
19
|
+
}[] = [
|
|
20
|
+
{ label: 'player-controls', pattern: /Loaded:\s*\d+%/ },
|
|
21
|
+
{ label: 'player-controls', pattern: /Duration Time \d+:\d\d/ },
|
|
22
|
+
{
|
|
23
|
+
label: 'metered-barrier',
|
|
24
|
+
pattern: /read your last free article|subscribe to continue reading/i,
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
export interface LostEvidence {
|
|
29
|
+
readonly debrisProbes: readonly string[];
|
|
30
|
+
readonly fallbackUsed: boolean;
|
|
31
|
+
readonly gatedReason?: string;
|
|
32
|
+
readonly nearEmpty: boolean;
|
|
33
|
+
readonly reasons: readonly string[];
|
|
34
|
+
readonly wordCount: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// The verdict the suggest loop fires on. Gating alone never fires it — vendor
|
|
38
|
+
// SDK classes (paywall-ineligible feed badges, piano offer headers) report on
|
|
39
|
+
// free articles, and the pairing is enforced by construction: `gatedReason` is
|
|
40
|
+
// carried as evidence for the prompt and the report, and only
|
|
41
|
+
// fallback/near-empty/debris count as reasons.
|
|
42
|
+
export function assessLostSignal(input: {
|
|
43
|
+
contentText: string;
|
|
44
|
+
fallbackUsed: boolean;
|
|
45
|
+
gated?: GatingSignal;
|
|
46
|
+
}): LostEvidence {
|
|
47
|
+
const wordCount = countWords(input.contentText);
|
|
48
|
+
const nearEmpty = wordCount < NEAR_EMPTY_WORDS;
|
|
49
|
+
const debrisProbes = [
|
|
50
|
+
...new Set(
|
|
51
|
+
DEBRIS_PROBES.filter(probe => probe.pattern.test(input.contentText)).map(
|
|
52
|
+
probe => probe.label,
|
|
53
|
+
),
|
|
54
|
+
),
|
|
55
|
+
];
|
|
56
|
+
const reasons = [
|
|
57
|
+
...(input.fallbackUsed ? ['fallback-used'] : []),
|
|
58
|
+
...(nearEmpty ? ['near-empty'] : []),
|
|
59
|
+
...debrisProbes.map(label => `debris:${label}`),
|
|
60
|
+
];
|
|
61
|
+
return {
|
|
62
|
+
debrisProbes,
|
|
63
|
+
fallbackUsed: input.fallbackUsed,
|
|
64
|
+
gatedReason: input.gated?.likely ? input.gated.reason : undefined,
|
|
65
|
+
nearEmpty,
|
|
66
|
+
reasons,
|
|
67
|
+
wordCount,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import remarkGfm from 'remark-gfm';
|
|
2
|
+
import remarkParse from 'remark-parse';
|
|
3
|
+
import { unified } from 'unified';
|
|
4
|
+
|
|
5
|
+
export type MarkdownBlockKind = 'code' | 'heading' | 'other';
|
|
6
|
+
|
|
7
|
+
// A top-level CommonMark block located by source offset. remark is used as a
|
|
8
|
+
// boundary finder, never a serializer: callers slice the *original* string at
|
|
9
|
+
// these offsets so truncate/chunk return byte-for-byte slices of the Turndown
|
|
10
|
+
// output rather than a reflowed re-stringification.
|
|
11
|
+
export interface MarkdownBlock {
|
|
12
|
+
readonly depth: number;
|
|
13
|
+
readonly end: number;
|
|
14
|
+
readonly kind: MarkdownBlockKind;
|
|
15
|
+
readonly start: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const processor = unified().use(remarkParse).use(remarkGfm);
|
|
19
|
+
|
|
20
|
+
const HEADING_MARKERS = /^#{1,6}\s+/;
|
|
21
|
+
|
|
22
|
+
export function parseBlocks(source: string): MarkdownBlock[] {
|
|
23
|
+
const tree = processor.parse(source);
|
|
24
|
+
const blocks: MarkdownBlock[] = [];
|
|
25
|
+
for (const node of tree.children) {
|
|
26
|
+
const start = node.position?.start.offset;
|
|
27
|
+
const end = node.position?.end.offset;
|
|
28
|
+
if (start === undefined || end === undefined) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const kind: MarkdownBlockKind =
|
|
32
|
+
node.type === 'code'
|
|
33
|
+
? 'code'
|
|
34
|
+
: node.type === 'heading'
|
|
35
|
+
? 'heading'
|
|
36
|
+
: 'other';
|
|
37
|
+
const depth = node.type === 'heading' ? node.depth : 0;
|
|
38
|
+
blocks.push({ depth, end, kind, start });
|
|
39
|
+
}
|
|
40
|
+
return blocks;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function headingText(raw: string): string {
|
|
44
|
+
return raw.replace(HEADING_MARKERS, '').trim();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Hard-cap a run to <= maxChars pieces: pack whole lines, then hard-split any
|
|
48
|
+
// single line that alone exceeds the budget.
|
|
49
|
+
export function hardSplitLines(text: string, maxChars: number): string[] {
|
|
50
|
+
const pieces: string[] = [];
|
|
51
|
+
let buffer = '';
|
|
52
|
+
function flush(): void {
|
|
53
|
+
if (buffer) {
|
|
54
|
+
pieces.push(buffer);
|
|
55
|
+
buffer = '';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const line of text.split('\n')) {
|
|
59
|
+
if (line.length > maxChars) {
|
|
60
|
+
flush();
|
|
61
|
+
for (let i = 0; i < line.length; i += maxChars) {
|
|
62
|
+
pieces.push(line.slice(i, i + maxChars));
|
|
63
|
+
}
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const candidate = buffer ? `${buffer}\n${line}` : line;
|
|
67
|
+
if (candidate.length > maxChars) {
|
|
68
|
+
flush();
|
|
69
|
+
buffer = line;
|
|
70
|
+
} else {
|
|
71
|
+
buffer = candidate;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
flush();
|
|
75
|
+
return pieces;
|
|
76
|
+
}
|