@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,313 @@
|
|
|
1
|
+
import { resolveCellText } from '../pipeline/cell-text.ts';
|
|
2
|
+
import {
|
|
3
|
+
CONTAINER_TAGS,
|
|
4
|
+
describeSelector,
|
|
5
|
+
groupChildrenByShape,
|
|
6
|
+
stripLandmarkChrome,
|
|
7
|
+
} from './sibling-scan.ts';
|
|
8
|
+
|
|
9
|
+
export interface GridRow {
|
|
10
|
+
readonly cells: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type GridConfidence = 'high' | 'low' | 'medium';
|
|
14
|
+
|
|
15
|
+
export interface GridDetectionResult {
|
|
16
|
+
readonly colCount: number;
|
|
17
|
+
readonly confidence: GridConfidence;
|
|
18
|
+
readonly containerSelector: string;
|
|
19
|
+
readonly detected: boolean;
|
|
20
|
+
readonly note: string;
|
|
21
|
+
readonly rowCount: number;
|
|
22
|
+
readonly rows: readonly GridRow[];
|
|
23
|
+
readonly rowTag: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface DetectGridOptions {
|
|
27
|
+
readonly cellSelector?: string;
|
|
28
|
+
readonly minRows?: number;
|
|
29
|
+
readonly rowSelector?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const MIN_ROWS = 3;
|
|
33
|
+
const HIGH_CONF_ROWS = 6;
|
|
34
|
+
const MIN_CELLS_PER_ROW = 2;
|
|
35
|
+
|
|
36
|
+
function rowCells(row: Element): string[] {
|
|
37
|
+
return Array.from(row.children).map(resolveCellText);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function notDetected(note: string): GridDetectionResult {
|
|
41
|
+
return {
|
|
42
|
+
confidence: 'low',
|
|
43
|
+
containerSelector: '',
|
|
44
|
+
detected: false,
|
|
45
|
+
rowCount: 0,
|
|
46
|
+
colCount: 0,
|
|
47
|
+
rows: [],
|
|
48
|
+
rowTag: '',
|
|
49
|
+
note,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Confidence tracks the detected cluster (the data-row count), not any header
|
|
54
|
+
// row inferred on top of it — a recovered header is inference, not evidence, so
|
|
55
|
+
// it must not push a grid past HIGH_CONF_ROWS. Both detection modes gate on
|
|
56
|
+
// minRows before reaching buildResult, so this is only ever called with a
|
|
57
|
+
// data-row count >= minRows; `low` comes solely from notDetected().
|
|
58
|
+
function confidenceFor(dataRowCount: number): GridConfidence {
|
|
59
|
+
return dataRowCount >= HIGH_CONF_ROWS ? 'high' : 'medium';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface GridCandidate {
|
|
63
|
+
readonly container: Element;
|
|
64
|
+
readonly containerSelector: string;
|
|
65
|
+
readonly memberCount: number;
|
|
66
|
+
readonly members: readonly Element[];
|
|
67
|
+
readonly rows: readonly string[][];
|
|
68
|
+
readonly rowTag: string;
|
|
69
|
+
readonly totalCellText: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Pad ragged rows to the max cell width so the matrix is rectangular — the
|
|
73
|
+
// GFM/CSV/JSON renderers in pipeline/tables.ts assume a dense grid (the
|
|
74
|
+
// delimiter row is derived from row-0 width, so a short row would mis-align
|
|
75
|
+
// every column). Mirrors parseTableMatrix's dense-pad step.
|
|
76
|
+
// `evidence` separates the detected cluster from the emitted matrix: rowCount
|
|
77
|
+
// counts every emitted row (data plus any recovered header), but confidence and
|
|
78
|
+
// the "detected N" note track the data-row cluster alone, since the header is
|
|
79
|
+
// inferred rather than detected. Omitted in selector mode and when auto-detect
|
|
80
|
+
// recovers no header, where the two counts coincide.
|
|
81
|
+
function buildResult(
|
|
82
|
+
raggedRows: readonly string[][],
|
|
83
|
+
rowTag: string,
|
|
84
|
+
containerSelector: string,
|
|
85
|
+
selectorHint?: string,
|
|
86
|
+
evidence?: { readonly dataRowCount: number; readonly headerCount: number },
|
|
87
|
+
): GridDetectionResult {
|
|
88
|
+
let maxCols = 0;
|
|
89
|
+
for (const row of raggedRows) {
|
|
90
|
+
if (row.length > maxCols) {
|
|
91
|
+
maxCols = row.length;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (maxCols === 0) {
|
|
95
|
+
return notDetected(
|
|
96
|
+
selectorHint
|
|
97
|
+
? `not a grid: rows matched ${selectorHint} but no cells were found`
|
|
98
|
+
: 'not a grid: rows matched but no cells were found',
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
const rowCount = raggedRows.length;
|
|
102
|
+
const dataRowCount = evidence?.dataRowCount ?? rowCount;
|
|
103
|
+
const headerCount = evidence?.headerCount ?? 0;
|
|
104
|
+
const rows: GridRow[] = raggedRows.map(row => ({
|
|
105
|
+
cells: Array.from({ length: maxCols }, (_, i) => row[i] ?? ''),
|
|
106
|
+
}));
|
|
107
|
+
const where = containerSelector || selectorHint || 'document';
|
|
108
|
+
const descriptor =
|
|
109
|
+
headerCount > 0
|
|
110
|
+
? `detected ${dataRowCount} ${rowTag} data rows plus ${headerCount} header row${headerCount > 1 ? 's' : ''} (${maxCols} cols) in ${where}`
|
|
111
|
+
: `detected ${dataRowCount} ${rowTag} rows (${maxCols} cols) in ${where}`;
|
|
112
|
+
return {
|
|
113
|
+
confidence: confidenceFor(dataRowCount),
|
|
114
|
+
containerSelector,
|
|
115
|
+
detected: true,
|
|
116
|
+
rowCount,
|
|
117
|
+
colCount: maxCols,
|
|
118
|
+
rows,
|
|
119
|
+
rowTag,
|
|
120
|
+
note: descriptor,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function detectSelectorMode(
|
|
125
|
+
document: Document,
|
|
126
|
+
rowSelector: string,
|
|
127
|
+
cellSelector: string,
|
|
128
|
+
minRows: number,
|
|
129
|
+
): GridDetectionResult {
|
|
130
|
+
const rowEls = Array.from(document.querySelectorAll(rowSelector));
|
|
131
|
+
if (rowEls.length < minRows) {
|
|
132
|
+
return notDetected(
|
|
133
|
+
`not a grid: rowSelector "${rowSelector}" matched ${rowEls.length} row(s) (min ${minRows})`,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
const rows = rowEls.map(row =>
|
|
137
|
+
Array.from(row.querySelectorAll(cellSelector)).map(resolveCellText),
|
|
138
|
+
);
|
|
139
|
+
return buildResult(rows, rowEls[0].tagName, '', rowSelector);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function modalWidth(members: readonly Element[]): number {
|
|
143
|
+
const counts = new Map<number, number>();
|
|
144
|
+
for (const member of members) {
|
|
145
|
+
const width = member.children.length;
|
|
146
|
+
counts.set(width, (counts.get(width) ?? 0) + 1);
|
|
147
|
+
}
|
|
148
|
+
let best = members[0].children.length;
|
|
149
|
+
let bestCount = 0;
|
|
150
|
+
for (const [width, count] of counts) {
|
|
151
|
+
if (count > bestCount) {
|
|
152
|
+
best = width;
|
|
153
|
+
bestCount = count;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return best;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function classTokens(el: Element): Set<string> {
|
|
160
|
+
const cls = el.getAttribute('class');
|
|
161
|
+
return cls ? new Set(cls.trim().split(/\s+/)) : new Set();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// A div-grid header has no <th>, so recovery leans on two signals, strongest
|
|
165
|
+
// first. (1) An ARIA grid header — role="row" with a columnheader child — is a
|
|
166
|
+
// semantic role and reliable on its own. (2) Class kinship with the data
|
|
167
|
+
// cluster: a real header is the data rows' own class plus a discriminator
|
|
168
|
+
// ("est-header"), so it carries every data class token. Chrome such as
|
|
169
|
+
// "card-header" / "page-header" shares no class with the data rows and must not
|
|
170
|
+
// be promoted — which is why we match token ownership, never the "header"
|
|
171
|
+
// substring. Substring matching is what split the header into its own shape
|
|
172
|
+
// group to begin with, and it over-fires on any chrome whose class merely
|
|
173
|
+
// contains the word.
|
|
174
|
+
function looksLikeHeader(
|
|
175
|
+
child: Element,
|
|
176
|
+
rowTag: string,
|
|
177
|
+
dataClass: Set<string>,
|
|
178
|
+
dataWidth: number,
|
|
179
|
+
): boolean {
|
|
180
|
+
if (child.tagName !== rowTag || child.children.length !== dataWidth) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
if (
|
|
184
|
+
child.getAttribute('role') === 'row' &&
|
|
185
|
+
Array.from(child.children).some(
|
|
186
|
+
c => c.getAttribute('role') === 'columnheader',
|
|
187
|
+
)
|
|
188
|
+
) {
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
const childClass = classTokens(child);
|
|
192
|
+
return (
|
|
193
|
+
dataClass.size > 0 && [...dataClass].every(token => childClass.has(token))
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// A header row often carries an extra class token (e.g. "est-header") that
|
|
198
|
+
// splits it into its own 1-member shape group, below the minRows cutoff, so the
|
|
199
|
+
// data-row cluster wins on its own and the header is dropped — leaving the
|
|
200
|
+
// first data row mis-read as the header and the real header lost. Recover it:
|
|
201
|
+
// scan the winning container's children that precede the first data row and
|
|
202
|
+
// prepend any sibling that looks like a header for this cluster. Children after
|
|
203
|
+
// the first data row (totals/footer) are left alone.
|
|
204
|
+
function collectHeaderRows(
|
|
205
|
+
container: Element,
|
|
206
|
+
members: readonly Element[],
|
|
207
|
+
): string[][] {
|
|
208
|
+
const memberSet = new Set<Element>(members);
|
|
209
|
+
const rowTag = members[0].tagName;
|
|
210
|
+
const dataWidth = modalWidth(members);
|
|
211
|
+
// shapeKey freezes tag + class signature, so every member shares one class
|
|
212
|
+
// set and members[0] represents it; child count is not part of shapeKey, so
|
|
213
|
+
// widths can vary within the group (hence modalWidth above).
|
|
214
|
+
const dataClass = classTokens(members[0]);
|
|
215
|
+
const headers: string[][] = [];
|
|
216
|
+
for (const child of Array.from(container.children)) {
|
|
217
|
+
if (memberSet.has(child)) {
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
if (looksLikeHeader(child, rowTag, dataClass, dataWidth)) {
|
|
221
|
+
headers.push(rowCells(child));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return headers;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function detectAuto(document: Document, minRows: number): GridDetectionResult {
|
|
228
|
+
stripLandmarkChrome(document);
|
|
229
|
+
|
|
230
|
+
const candidates: GridCandidate[] = [];
|
|
231
|
+
for (const container of document.querySelectorAll('*')) {
|
|
232
|
+
if (!CONTAINER_TAGS.has(container.tagName)) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const groups = groupChildrenByShape(container);
|
|
236
|
+
for (const members of groups.values()) {
|
|
237
|
+
if (members.length < minRows) {
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
// A row needs at least two cells to be a row; a group of single-child
|
|
241
|
+
// wrappers is a list of links/labels, not a data grid.
|
|
242
|
+
if (!members.every(m => m.children.length >= MIN_CELLS_PER_ROW)) {
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
const rows = members.map(rowCells);
|
|
246
|
+
const totalCellText = rows.reduce(
|
|
247
|
+
(sum, row) => sum + row.reduce((s, c) => s + c.length, 0),
|
|
248
|
+
0,
|
|
249
|
+
);
|
|
250
|
+
candidates.push({
|
|
251
|
+
container,
|
|
252
|
+
containerSelector: describeSelector(container),
|
|
253
|
+
members,
|
|
254
|
+
rows,
|
|
255
|
+
rowTag: members[0].tagName,
|
|
256
|
+
memberCount: members.length,
|
|
257
|
+
totalCellText,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (candidates.length === 0) {
|
|
263
|
+
return notDetected(
|
|
264
|
+
'not a grid: no repeating row structure (≥3 same-shape siblings each with ≥2 direct element-children, outside nav/header/footer/aside)',
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Most rows wins; ties break on total cell text so a sparse 6-row grid beats
|
|
269
|
+
// a dense 6-row one only when it carries more substance, and a longer
|
|
270
|
+
// analyst-estimates table beats a stub sidebar mini-grid on both axes.
|
|
271
|
+
let winner = candidates[0];
|
|
272
|
+
for (let i = 1; i < candidates.length; i++) {
|
|
273
|
+
const candidate = candidates[i];
|
|
274
|
+
if (
|
|
275
|
+
candidate.memberCount > winner.memberCount ||
|
|
276
|
+
(candidate.memberCount === winner.memberCount &&
|
|
277
|
+
candidate.totalCellText > winner.totalCellText)
|
|
278
|
+
) {
|
|
279
|
+
winner = candidate;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const headerRows = collectHeaderRows(winner.container, winner.members);
|
|
283
|
+
return buildResult(
|
|
284
|
+
[...headerRows, ...winner.rows],
|
|
285
|
+
winner.rowTag,
|
|
286
|
+
winner.containerSelector,
|
|
287
|
+
undefined,
|
|
288
|
+
{ dataRowCount: winner.memberCount, headerCount: headerRows.length },
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Detect a CSS-grid/div "table" — the div equivalent of extract_tables. In
|
|
293
|
+
// selector mode (both rowSelector and cellSelector given) the rows and cells
|
|
294
|
+
// are whatever the caller names. In auto mode, chrome is stripped first and
|
|
295
|
+
// the container whose direct children form the largest same-shape sibling
|
|
296
|
+
// group (each member a row of ≥2 direct element-children) wins. The resulting
|
|
297
|
+
// rows are padded to a dense rectangular matrix so the shared table renderer
|
|
298
|
+
// can serialize them as gfm/csv/json.
|
|
299
|
+
export function detectGrid(
|
|
300
|
+
document: Document,
|
|
301
|
+
opts?: DetectGridOptions,
|
|
302
|
+
): GridDetectionResult {
|
|
303
|
+
const minRows = opts?.minRows ?? MIN_ROWS;
|
|
304
|
+
if (opts?.rowSelector && opts.cellSelector) {
|
|
305
|
+
return detectSelectorMode(
|
|
306
|
+
document,
|
|
307
|
+
opts.rowSelector,
|
|
308
|
+
opts.cellSelector,
|
|
309
|
+
minRows,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
return detectAuto(document, minRows);
|
|
313
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Char-class transition scoring for CSS identifiers, after readweb's measured
|
|
2
|
+
// price table: a class like `css-1a2b3c` or `content_1tsiE` is priced per
|
|
3
|
+
// adjacent char-class transition and normalized by length, and a compound token
|
|
4
|
+
// also fails if any delimiter-separated segment does — a stable stem must not
|
|
5
|
+
// carry a volatile build hash (`BoxStyles_commercial__Wo6Z4`).
|
|
6
|
+
export type CharClass = 'Digit' | 'Lower' | 'Other' | 'Symbol' | 'Upper';
|
|
7
|
+
|
|
8
|
+
export const GIBBERISH_THRESHOLD = 0.3;
|
|
9
|
+
|
|
10
|
+
const PRICE_TABLE: Partial<Record<`${CharClass}:${CharClass}`, number>> = {
|
|
11
|
+
'Upper:Lower': 0.2,
|
|
12
|
+
'Lower:Upper': 0.5,
|
|
13
|
+
'Symbol:Upper': 0.4,
|
|
14
|
+
'Symbol:Lower': 0.3,
|
|
15
|
+
'Symbol:Digit': 0.9,
|
|
16
|
+
'Upper:Digit': 1.4,
|
|
17
|
+
'Lower:Digit': 1.3,
|
|
18
|
+
'Digit:Upper': 1.4,
|
|
19
|
+
'Digit:Lower': 1.5,
|
|
20
|
+
'Digit:Symbol': 1.2,
|
|
21
|
+
'Upper:Symbol': 0.2,
|
|
22
|
+
'Lower:Symbol': 0.2,
|
|
23
|
+
'Digit:Digit': 1.2,
|
|
24
|
+
'Symbol:Symbol': 0.3,
|
|
25
|
+
'Upper:Upper': 0.1,
|
|
26
|
+
'Lower:Lower': 0.1,
|
|
27
|
+
'Other:Other': 0.0,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function classifyChar(ch: string): CharClass {
|
|
31
|
+
if (/[A-Z]/.test(ch)) {
|
|
32
|
+
return 'Upper';
|
|
33
|
+
}
|
|
34
|
+
if (/[a-z]/.test(ch)) {
|
|
35
|
+
return 'Lower';
|
|
36
|
+
}
|
|
37
|
+
if (/[0-9]/.test(ch)) {
|
|
38
|
+
return 'Digit';
|
|
39
|
+
}
|
|
40
|
+
if (/[-_]/.test(ch)) {
|
|
41
|
+
return 'Symbol';
|
|
42
|
+
}
|
|
43
|
+
return 'Other';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function transitionPrice(from: CharClass, to: CharClass): number {
|
|
47
|
+
return PRICE_TABLE[`${from}:${to}`] ?? 1.0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function gibberishScore(value: string): number {
|
|
51
|
+
if (value.length < 2) {
|
|
52
|
+
return 0;
|
|
53
|
+
}
|
|
54
|
+
let absolute = 0;
|
|
55
|
+
let previous: CharClass | null = null;
|
|
56
|
+
for (const ch of value) {
|
|
57
|
+
const current = classifyChar(ch);
|
|
58
|
+
if (previous !== null) {
|
|
59
|
+
absolute += transitionPrice(previous, current);
|
|
60
|
+
}
|
|
61
|
+
previous = current;
|
|
62
|
+
}
|
|
63
|
+
return absolute / Math.max(1, value.length - 1);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function exceedsThreshold(value: string): boolean {
|
|
67
|
+
return value.length >= 4 && gibberishScore(value) >= GIBBERISH_THRESHOLD;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function isGeneratedIdentifier(value: string): boolean {
|
|
71
|
+
if (exceedsThreshold(value)) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
return value.split(/[-_]/).some(segment => exceedsThreshold(segment));
|
|
75
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { isPlaceholderSrc } from '../pipeline/normalize.ts';
|
|
2
|
+
import { absolutize } from '../pipeline/urls.ts';
|
|
3
|
+
|
|
4
|
+
export interface ImageEntry {
|
|
5
|
+
readonly alt: string;
|
|
6
|
+
readonly caption: string;
|
|
7
|
+
readonly height?: number;
|
|
8
|
+
readonly src: string;
|
|
9
|
+
readonly width?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function positiveInt(value: null | string): number | undefined {
|
|
13
|
+
if (value === null) {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
const n = Number.parseInt(value, 10);
|
|
17
|
+
return Number.isInteger(n) && n > 0 ? n : undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// resolveLazyImages has already mutated placeholder srcs to real ones in the
|
|
21
|
+
// article HTML by the time this runs — reading `src` here gets the resolved
|
|
22
|
+
// value, so this walker does NOT re-run source resolution. isPlaceholderSrc
|
|
23
|
+
// skips any remaining data:/placeholder srcs the lazy resolver left alone.
|
|
24
|
+
export function collectImageInventory(
|
|
25
|
+
html: string,
|
|
26
|
+
window: Window,
|
|
27
|
+
baseUrl?: string,
|
|
28
|
+
): ImageEntry[] {
|
|
29
|
+
if (!html) {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
const probe = window.document.createElement('div');
|
|
33
|
+
probe.innerHTML = html;
|
|
34
|
+
|
|
35
|
+
const entries: ImageEntry[] = [];
|
|
36
|
+
for (const img of probe.querySelectorAll('img')) {
|
|
37
|
+
const rawSrc = img.getAttribute('src') ?? '';
|
|
38
|
+
if (isPlaceholderSrc(rawSrc)) {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const src = absolutize(rawSrc, baseUrl);
|
|
42
|
+
if (!src) {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const alt = img.getAttribute('alt') ?? '';
|
|
46
|
+
const width = positiveInt(img.getAttribute('width'));
|
|
47
|
+
const height = positiveInt(img.getAttribute('height'));
|
|
48
|
+
// <figcaption> may precede OR follow the <img> inside the <figure>, so
|
|
49
|
+
// closest('figure') + querySelector('figcaption') covers both orderings.
|
|
50
|
+
const figure = img.closest('figure');
|
|
51
|
+
const figcaption = figure?.querySelector('figcaption');
|
|
52
|
+
const caption = figcaption
|
|
53
|
+
? figcaption.textContent.replace(/\s+/g, ' ').trim()
|
|
54
|
+
: alt;
|
|
55
|
+
entries.push({
|
|
56
|
+
src,
|
|
57
|
+
alt,
|
|
58
|
+
...(width !== undefined ? { width } : {}),
|
|
59
|
+
...(height !== undefined ? { height } : {}),
|
|
60
|
+
caption,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return entries;
|
|
64
|
+
}
|