@nitpicker/crawler 0.22.0 → 0.23.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/lib/archive/archive.d.ts +13 -5
- package/lib/archive/archive.js +13 -5
- package/lib/archive/cache/extract-archive-to-cache.d.ts +6 -1
- package/lib/archive/cache/extract-archive-to-cache.js +13 -6
- package/lib/archive/create-adjunct-tables.d.ts +0 -7
- package/lib/archive/create-adjunct-tables.js +0 -50
- package/lib/archive/create-template-tables.d.ts +30 -0
- package/lib/archive/create-template-tables.js +95 -0
- package/lib/archive/database.d.ts +1 -1
- package/lib/archive/database.js +1 -1
- package/lib/archive/db-ops/pages/read/get-crawling-state.d.ts +43 -3
- package/lib/archive/db-ops/pages/read/get-crawling-state.js +61 -6
- package/lib/archive/db-ops/pages/write/update-page.js +10 -2
- package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
- package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
- package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
- package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
- package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
- package/lib/archive/init-schema.d.ts +5 -1
- package/lib/archive/init-schema.js +13 -2
- package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
- package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
- package/lib/archive/transfer/attach-source-database.d.ts +31 -0
- package/lib/archive/transfer/attach-source-database.js +40 -0
- package/lib/archive/transfer/build-split-config.d.ts +30 -0
- package/lib/archive/transfer/build-split-config.js +42 -0
- package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
- package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
- package/lib/archive/transfer/concat-archives.d.ts +55 -0
- package/lib/archive/transfer/concat-archives.js +95 -0
- package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
- package/lib/archive/transfer/content-item-rank-sql.js +23 -0
- package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
- package/lib/archive/transfer/copy-analysis-violations.js +43 -0
- package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
- package/lib/archive/transfer/copy-anchor-edges.js +42 -0
- package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
- package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
- package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
- package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
- package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
- package/lib/archive/transfer/copy-header-set-children.js +51 -0
- package/lib/archive/transfer/copy-image-items.d.ts +21 -0
- package/lib/archive/transfer/copy-image-items.js +62 -0
- package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
- package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
- package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
- package/lib/archive/transfer/copy-journal-tables.js +56 -0
- package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
- package/lib/archive/transfer/copy-page-console-logs.js +27 -0
- package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
- package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
- package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
- package/lib/archive/transfer/copy-page-meta.js +68 -0
- package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
- package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
- package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
- package/lib/archive/transfer/copy-page-template-labels.js +88 -0
- package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
- package/lib/archive/transfer/copy-resource-items.js +89 -0
- package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
- package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
- package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
- package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
- package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
- package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
- package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
- package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
- package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
- package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
- package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
- package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
- package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
- package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
- package/lib/archive/transfer/insert-content-items.d.ts +35 -0
- package/lib/archive/transfer/insert-content-items.js +116 -0
- package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
- package/lib/archive/transfer/list-transfer-columns.js +45 -0
- package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
- package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
- package/lib/archive/transfer/merge-archive-configs.d.ts +48 -0
- package/lib/archive/transfer/merge-archive-configs.js +78 -0
- package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
- package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
- package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
- package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
- package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
- package/lib/archive/transfer/plan-resource-items.js +69 -0
- package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
- package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
- package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
- package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
- package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
- package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
- package/lib/archive/transfer/replace-content-items.d.ts +39 -0
- package/lib/archive/transfer/replace-content-items.js +83 -0
- package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
- package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
- package/lib/archive/transfer/split-archive.d.ts +55 -0
- package/lib/archive/transfer/split-archive.js +98 -0
- package/lib/archive/transfer/transfer-action.d.ts +34 -0
- package/lib/archive/transfer/transfer-action.js +32 -0
- package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
- package/lib/archive/transfer/transfer-archive-rows.js +158 -0
- package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
- package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
- package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
- package/lib/archive/transfer/transfer-source-alias.js +9 -0
- package/lib/archive/transfer/types.d.ts +111 -0
- package/lib/archive/transfer/types.js +35 -0
- package/lib/concat-source-transfer-phases.d.ts +10 -0
- package/lib/concat-source-transfer-phases.js +17 -0
- package/lib/crawler/build-scope-map.d.ts +21 -0
- package/lib/crawler/build-scope-map.js +32 -0
- package/lib/crawler-orchestrator.js +10 -16
- package/lib/crawler.d.ts +13 -1
- package/lib/crawler.js +22 -0
- package/lib/split-source-transfer-phases.d.ts +11 -0
- package/lib/split-source-transfer-phases.js +18 -0
- package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
- package/lib/template-classification/classify-archive-page-templates.js +79 -0
- package/lib/template-classification/classify-page-templates.d.ts +37 -0
- package/lib/template-classification/classify-page-templates.js +69 -0
- package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
- package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
- package/lib/template-classification/create-content-root-hint.d.ts +36 -0
- package/lib/template-classification/create-content-root-hint.js +47 -0
- package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
- package/lib/template-classification/create-page-cluster-factory.js +98 -0
- package/lib/template-classification/types.d.ts +108 -0
- package/lib/template-classification/types.js +1 -0
- package/lib/transfer-post-phases.d.ts +10 -0
- package/lib/transfer-post-phases.js +13 -0
- package/package.json +3 -2
- package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
- /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { AssignTemplateLabelsParams, TemplateLabel } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Assigns every cluster of a fresh template classification its
|
|
4
|
+
* {@link TemplateLabel}, carrying labels forward from the previous
|
|
5
|
+
* classification wherever the same template survived the re-run.
|
|
6
|
+
*
|
|
7
|
+
* ## Inheritance
|
|
8
|
+
*
|
|
9
|
+
* A new cluster inherits an old cluster's label when the two share a
|
|
10
|
+
* **mutual majority** of pages: the overlap is more than half of the new
|
|
11
|
+
* cluster *and* more than half of the old one. Mutual majority means at
|
|
12
|
+
* most one new cluster can claim a given old label, and a cluster that
|
|
13
|
+
* merely absorbed a few pages of a much larger old template does not steal
|
|
14
|
+
* its name. A split keeps the old label on the half that holds most of the
|
|
15
|
+
* old pages; the other half is named afresh.
|
|
16
|
+
*
|
|
17
|
+
* The old cluster's size counts only pages that are classified in the new
|
|
18
|
+
* run too. Pages the crawl has since dropped (`--recrawl` turned them into
|
|
19
|
+
* redirects, errors, …) are not evidence that the template changed, so
|
|
20
|
+
* they must not dilute the old half of the majority — otherwise an old
|
|
21
|
+
* 7-page cluster whose 4 missing pages left 3 unchanged ones would fail
|
|
22
|
+
* `3 > 7/2` and be renamed for no reason.
|
|
23
|
+
*
|
|
24
|
+
* Page ids are the identity used for overlap (not URLs) because they are
|
|
25
|
+
* what `page_templates` stores and they survive `--append` / `--recrawl`
|
|
26
|
+
* without renumbering.
|
|
27
|
+
*
|
|
28
|
+
* ## Fresh labels
|
|
29
|
+
*
|
|
30
|
+
* Clusters left without an inherited label are numbered in page-count
|
|
31
|
+
* order (largest first, template key as a tie-break) so a first run reads
|
|
32
|
+
* naturally: `A` is the section's biggest template. Each takes the next
|
|
33
|
+
* ordinal **after every ordinal in `previousLabels` for its section**, so a
|
|
34
|
+
* letter is never re-issued to a different template — which would silently
|
|
35
|
+
* change what "events template B" means between two people's archives.
|
|
36
|
+
* That guarantee is only as good as `previousLabels`: `replacePageTemplates`
|
|
37
|
+
* keeps the rows of clusters that disappeared (retired labels) precisely so
|
|
38
|
+
* they stay in this set across any number of later runs.
|
|
39
|
+
*
|
|
40
|
+
* ## Section
|
|
41
|
+
*
|
|
42
|
+
* A cluster's section is the first path segment every member URL shares
|
|
43
|
+
* (`events` for `/events/...`). Members spread over several segments, or
|
|
44
|
+
* all at the site root, yield `null`: such a cluster is numbered in the
|
|
45
|
+
* site-wide sequence. An inherited label keeps its old section even if the
|
|
46
|
+
* cluster's members have since drifted — stability of the name wins over
|
|
47
|
+
* keeping the section literally accurate.
|
|
48
|
+
* @param params - See {@link AssignTemplateLabelsParams}.
|
|
49
|
+
* @returns Template key → label, one entry per cluster in `params.clusters`.
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* const labels = assignTemplateLabels({
|
|
53
|
+
* clusters: new Map([['["path:events","cluster:0"]', { pageIds: [1, 2], urls: ['https://example.com/events/a', 'https://example.com/events/b'] }]]),
|
|
54
|
+
* previousMembership: new Map(),
|
|
55
|
+
* previousLabels: new Map(),
|
|
56
|
+
* });
|
|
57
|
+
* labels.get('["path:events","cluster:0"]'); // { section: 'events', ordinal: 1 }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export declare function assignTemplateLabels(params: AssignTemplateLabelsParams): Map<string, TemplateLabel>;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assigns every cluster of a fresh template classification its
|
|
3
|
+
* {@link TemplateLabel}, carrying labels forward from the previous
|
|
4
|
+
* classification wherever the same template survived the re-run.
|
|
5
|
+
*
|
|
6
|
+
* ## Inheritance
|
|
7
|
+
*
|
|
8
|
+
* A new cluster inherits an old cluster's label when the two share a
|
|
9
|
+
* **mutual majority** of pages: the overlap is more than half of the new
|
|
10
|
+
* cluster *and* more than half of the old one. Mutual majority means at
|
|
11
|
+
* most one new cluster can claim a given old label, and a cluster that
|
|
12
|
+
* merely absorbed a few pages of a much larger old template does not steal
|
|
13
|
+
* its name. A split keeps the old label on the half that holds most of the
|
|
14
|
+
* old pages; the other half is named afresh.
|
|
15
|
+
*
|
|
16
|
+
* The old cluster's size counts only pages that are classified in the new
|
|
17
|
+
* run too. Pages the crawl has since dropped (`--recrawl` turned them into
|
|
18
|
+
* redirects, errors, …) are not evidence that the template changed, so
|
|
19
|
+
* they must not dilute the old half of the majority — otherwise an old
|
|
20
|
+
* 7-page cluster whose 4 missing pages left 3 unchanged ones would fail
|
|
21
|
+
* `3 > 7/2` and be renamed for no reason.
|
|
22
|
+
*
|
|
23
|
+
* Page ids are the identity used for overlap (not URLs) because they are
|
|
24
|
+
* what `page_templates` stores and they survive `--append` / `--recrawl`
|
|
25
|
+
* without renumbering.
|
|
26
|
+
*
|
|
27
|
+
* ## Fresh labels
|
|
28
|
+
*
|
|
29
|
+
* Clusters left without an inherited label are numbered in page-count
|
|
30
|
+
* order (largest first, template key as a tie-break) so a first run reads
|
|
31
|
+
* naturally: `A` is the section's biggest template. Each takes the next
|
|
32
|
+
* ordinal **after every ordinal in `previousLabels` for its section**, so a
|
|
33
|
+
* letter is never re-issued to a different template — which would silently
|
|
34
|
+
* change what "events template B" means between two people's archives.
|
|
35
|
+
* That guarantee is only as good as `previousLabels`: `replacePageTemplates`
|
|
36
|
+
* keeps the rows of clusters that disappeared (retired labels) precisely so
|
|
37
|
+
* they stay in this set across any number of later runs.
|
|
38
|
+
*
|
|
39
|
+
* ## Section
|
|
40
|
+
*
|
|
41
|
+
* A cluster's section is the first path segment every member URL shares
|
|
42
|
+
* (`events` for `/events/...`). Members spread over several segments, or
|
|
43
|
+
* all at the site root, yield `null`: such a cluster is numbered in the
|
|
44
|
+
* site-wide sequence. An inherited label keeps its old section even if the
|
|
45
|
+
* cluster's members have since drifted — stability of the name wins over
|
|
46
|
+
* keeping the section literally accurate.
|
|
47
|
+
* @param params - See {@link AssignTemplateLabelsParams}.
|
|
48
|
+
* @returns Template key → label, one entry per cluster in `params.clusters`.
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* const labels = assignTemplateLabels({
|
|
52
|
+
* clusters: new Map([['["path:events","cluster:0"]', { pageIds: [1, 2], urls: ['https://example.com/events/a', 'https://example.com/events/b'] }]]),
|
|
53
|
+
* previousMembership: new Map(),
|
|
54
|
+
* previousLabels: new Map(),
|
|
55
|
+
* });
|
|
56
|
+
* labels.get('["path:events","cluster:0"]'); // { section: 'events', ordinal: 1 }
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export function assignTemplateLabels(params) {
|
|
60
|
+
const { clusters, previousMembership, previousLabels } = params;
|
|
61
|
+
const currentPageIds = new Set();
|
|
62
|
+
for (const cluster of clusters.values()) {
|
|
63
|
+
for (const pageId of cluster.pageIds) {
|
|
64
|
+
currentPageIds.add(pageId);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const previousKeyByPageId = new Map();
|
|
68
|
+
const previousSizeByKey = new Map();
|
|
69
|
+
for (const [key, pageIds] of previousMembership) {
|
|
70
|
+
let size = 0;
|
|
71
|
+
for (const pageId of pageIds) {
|
|
72
|
+
previousKeyByPageId.set(pageId, key);
|
|
73
|
+
if (currentPageIds.has(pageId)) {
|
|
74
|
+
size += 1;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
previousSizeByKey.set(key, size);
|
|
78
|
+
}
|
|
79
|
+
// Every ordinal ever issued per section, seeded from the previous run so
|
|
80
|
+
// a vanished cluster's letter is retired rather than re-issued.
|
|
81
|
+
const usedOrdinals = new Map();
|
|
82
|
+
const markUsed = (label) => {
|
|
83
|
+
let set = usedOrdinals.get(label.section);
|
|
84
|
+
if (!set) {
|
|
85
|
+
set = new Set();
|
|
86
|
+
usedOrdinals.set(label.section, set);
|
|
87
|
+
}
|
|
88
|
+
set.add(label.ordinal);
|
|
89
|
+
};
|
|
90
|
+
for (const label of previousLabels.values()) {
|
|
91
|
+
markUsed(label);
|
|
92
|
+
}
|
|
93
|
+
const ordered = [...clusters].toSorted(([keyA, a], [keyB, b]) => b.pageIds.length - a.pageIds.length || keyA.localeCompare(keyB));
|
|
94
|
+
const labels = new Map();
|
|
95
|
+
const claimedPreviousKeys = new Set();
|
|
96
|
+
const unlabeled = [];
|
|
97
|
+
for (const entry of ordered) {
|
|
98
|
+
const [key, cluster] = entry;
|
|
99
|
+
const inherited = findInheritedLabel(cluster.pageIds, {
|
|
100
|
+
previousKeyByPageId,
|
|
101
|
+
previousSizeByKey,
|
|
102
|
+
previousLabels,
|
|
103
|
+
claimedPreviousKeys,
|
|
104
|
+
});
|
|
105
|
+
if (inherited) {
|
|
106
|
+
claimedPreviousKeys.add(inherited.previousKey);
|
|
107
|
+
labels.set(key, inherited.label);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
unlabeled.push(entry);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
for (const [key, cluster] of unlabeled) {
|
|
114
|
+
const section = deriveSection(cluster.urls);
|
|
115
|
+
const used = usedOrdinals.get(section);
|
|
116
|
+
const ordinal = used ? Math.max(...used) + 1 : 1;
|
|
117
|
+
const label = { section, ordinal };
|
|
118
|
+
markUsed(label);
|
|
119
|
+
labels.set(key, label);
|
|
120
|
+
}
|
|
121
|
+
return labels;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Finds the previous cluster whose label the given members inherit, if any
|
|
125
|
+
* — the unclaimed, labeled previous cluster sharing a mutual majority of
|
|
126
|
+
* pages with them.
|
|
127
|
+
* @param pageIds - The new cluster's member page ids.
|
|
128
|
+
* @param context - Lookups built once by `assignTemplateLabels`.
|
|
129
|
+
* @param context.previousKeyByPageId - Page id → previous template key.
|
|
130
|
+
* @param context.previousSizeByKey - Previous template key → member count.
|
|
131
|
+
* @param context.previousLabels - Previous template key → label.
|
|
132
|
+
* @param context.claimedPreviousKeys - Previous keys already inherited by a larger new cluster.
|
|
133
|
+
* @returns The matched previous key and its label, or `null`.
|
|
134
|
+
*/
|
|
135
|
+
function findInheritedLabel(pageIds, context) {
|
|
136
|
+
const overlapByKey = new Map();
|
|
137
|
+
for (const pageId of pageIds) {
|
|
138
|
+
const previousKey = context.previousKeyByPageId.get(pageId);
|
|
139
|
+
if (previousKey != null) {
|
|
140
|
+
overlapByKey.set(previousKey, (overlapByKey.get(previousKey) ?? 0) + 1);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
let best = null;
|
|
144
|
+
for (const [previousKey, overlap] of overlapByKey) {
|
|
145
|
+
if (!best || overlap > best.overlap) {
|
|
146
|
+
best = { previousKey, overlap };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!best || context.claimedPreviousKeys.has(best.previousKey)) {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
const label = context.previousLabels.get(best.previousKey);
|
|
153
|
+
if (!label) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
const previousSize = context.previousSizeByKey.get(best.previousKey) ?? 0;
|
|
157
|
+
if (best.overlap * 2 <= pageIds.length || best.overlap * 2 <= previousSize) {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
return { previousKey: best.previousKey, label };
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* The first path segment shared by every URL, or `null` when they disagree
|
|
164
|
+
* or all sit at the site root. A URL that fails to parse counts as
|
|
165
|
+
* disagreeing — a cluster is not pinned to a section by guesswork.
|
|
166
|
+
* @param urls - The cluster's member page URLs.
|
|
167
|
+
* @returns The shared section name, or `null`.
|
|
168
|
+
*/
|
|
169
|
+
function deriveSection(urls) {
|
|
170
|
+
let section;
|
|
171
|
+
for (const url of urls) {
|
|
172
|
+
let segment;
|
|
173
|
+
try {
|
|
174
|
+
segment = new URL(url).pathname.split('/')[1] ?? '';
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
if (section === undefined) {
|
|
180
|
+
section = segment;
|
|
181
|
+
}
|
|
182
|
+
else if (section !== segment) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return section || null;
|
|
187
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { ReplacePageTemplatesParams } from './types.js';
|
|
2
2
|
import type { Knex } from 'knex';
|
|
3
3
|
/**
|
|
4
|
-
* Replaces the stored DOM-structure template classification
|
|
5
|
-
*
|
|
4
|
+
* Replaces the stored DOM-structure template classification with a freshly
|
|
5
|
+
* generated set.
|
|
6
6
|
*
|
|
7
7
|
* Every classified page is a full-archive, all-or-nothing recomputation
|
|
8
|
-
* (see
|
|
8
|
+
* (see `classifyPageTemplates`), so this always deletes
|
|
9
9
|
* every existing row before inserting the new set — there is no per-page
|
|
10
10
|
* incremental update path, matching `replaceAnalysisViolations`'s
|
|
11
11
|
* whole-table replace shape. Unlike violations, a page whose URL can't be
|
|
@@ -23,6 +23,22 @@ import type { Knex } from 'knex';
|
|
|
23
23
|
* in `templateKeysByUrl` after URL-resolution skips above — harmless
|
|
24
24
|
* (nothing joins `page_template_clusters` back to `page_templates` by FK;
|
|
25
25
|
* see the table's own JSDoc), and simpler than cross-filtering the two maps.
|
|
26
|
+
*
|
|
27
|
+
* `page_template_labels` is the one table that is **not** wholesale
|
|
28
|
+
* replaced: the human-facing label of each new cluster is carried forward
|
|
29
|
+
* from whichever previous cluster it shares most pages with
|
|
30
|
+
* (`assignTemplateLabels`), which is what lets "events template B" keep
|
|
31
|
+
* meaning the same template across re-runs, and the rows of clusters that
|
|
32
|
+
* disappeared are kept as *retired* labels so their letters are never
|
|
33
|
+
* re-issued to a different template on a later run (only the rows for the
|
|
34
|
+
* keys being written, and the old row of a label that moved to a new key,
|
|
35
|
+
* are removed). Readers look labels up by the keys
|
|
36
|
+
* currently in `page_templates`, so retired rows are invisible to them.
|
|
37
|
+
* The previous `page_templates` and `page_template_labels` rows are read
|
|
38
|
+
* inside the same transaction that writes — there is no window in which
|
|
39
|
+
* another writer could change what the labels were derived from. An empty
|
|
40
|
+
* `templateKeysByUrl` therefore clears the classification but leaves every
|
|
41
|
+
* label row in place.
|
|
26
42
|
* @param knex - Knex query builder connected to the archive DB.
|
|
27
43
|
* @param params - See {@link ReplacePageTemplatesParams}.
|
|
28
44
|
*/
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { eachSplitted } from '../../../utils/array/each-splitted.js';
|
|
2
|
+
import { compressPayload } from '../_shared/compress-payload.js';
|
|
3
|
+
import { assignTemplateLabels } from './assign-template-labels.js';
|
|
4
|
+
/**
|
|
5
|
+
* Replaces the stored DOM-structure template classification with a freshly
|
|
6
|
+
* generated set.
|
|
7
|
+
*
|
|
8
|
+
* Every classified page is a full-archive, all-or-nothing recomputation
|
|
9
|
+
* (see `classifyPageTemplates`), so this always deletes
|
|
10
|
+
* every existing row before inserting the new set — there is no per-page
|
|
11
|
+
* incremental update path, matching `replaceAnalysisViolations`'s
|
|
12
|
+
* whole-table replace shape. Unlike violations, a page whose URL can't be
|
|
13
|
+
* resolved back to a `content_items` row is silently skipped rather than
|
|
14
|
+
* treated as a hard failure: losing one page's template classification
|
|
15
|
+
* (e.g. a URL-normalization mismatch between the in-memory `Page.url.href`
|
|
16
|
+
* and the stored `url_refs.url`) should not discard the rest of a
|
|
17
|
+
* potentially multi-thousand-page classification run.
|
|
18
|
+
*
|
|
19
|
+
* `page_template_clusters` is always cleared alongside `page_templates`
|
|
20
|
+
* regardless of whether `clusterReasonsByTemplateKey` is passed — "no
|
|
21
|
+
* reason" must mean "not captured for this run", never "carry over the
|
|
22
|
+
* previous run's reason". Reason rows are inserted for every key in
|
|
23
|
+
* `clusterReasonsByTemplateKey` even if some have no surviving member page
|
|
24
|
+
* in `templateKeysByUrl` after URL-resolution skips above — harmless
|
|
25
|
+
* (nothing joins `page_template_clusters` back to `page_templates` by FK;
|
|
26
|
+
* see the table's own JSDoc), and simpler than cross-filtering the two maps.
|
|
27
|
+
*
|
|
28
|
+
* `page_template_labels` is the one table that is **not** wholesale
|
|
29
|
+
* replaced: the human-facing label of each new cluster is carried forward
|
|
30
|
+
* from whichever previous cluster it shares most pages with
|
|
31
|
+
* (`assignTemplateLabels`), which is what lets "events template B" keep
|
|
32
|
+
* meaning the same template across re-runs, and the rows of clusters that
|
|
33
|
+
* disappeared are kept as *retired* labels so their letters are never
|
|
34
|
+
* re-issued to a different template on a later run (only the rows for the
|
|
35
|
+
* keys being written, and the old row of a label that moved to a new key,
|
|
36
|
+
* are removed). Readers look labels up by the keys
|
|
37
|
+
* currently in `page_templates`, so retired rows are invisible to them.
|
|
38
|
+
* The previous `page_templates` and `page_template_labels` rows are read
|
|
39
|
+
* inside the same transaction that writes — there is no window in which
|
|
40
|
+
* another writer could change what the labels were derived from. An empty
|
|
41
|
+
* `templateKeysByUrl` therefore clears the classification but leaves every
|
|
42
|
+
* label row in place.
|
|
43
|
+
* @param knex - Knex query builder connected to the archive DB.
|
|
44
|
+
* @param params - See {@link ReplacePageTemplatesParams}.
|
|
45
|
+
*/
|
|
46
|
+
export async function replacePageTemplates(knex, params) {
|
|
47
|
+
const { templateKeysByUrl, clusterReasonsByTemplateKey } = params;
|
|
48
|
+
// Compressing every reason is pure CPU work independent of the DB — done
|
|
49
|
+
// before opening the transaction below so it doesn't extend how long the
|
|
50
|
+
// SQLite write-lock is held for.
|
|
51
|
+
const reasonRows = clusterReasonsByTemplateKey && clusterReasonsByTemplateKey.size > 0
|
|
52
|
+
? [...clusterReasonsByTemplateKey].map(([templateKey, reason]) => {
|
|
53
|
+
const { body, codec, sizeRaw, sizeStored } = compressPayload(Buffer.from(JSON.stringify(reason), 'utf8'));
|
|
54
|
+
return {
|
|
55
|
+
template_key: templateKey,
|
|
56
|
+
member_count: reason.memberCount,
|
|
57
|
+
reason_json: body,
|
|
58
|
+
codec,
|
|
59
|
+
size_raw: sizeRaw,
|
|
60
|
+
size_stored: sizeStored,
|
|
61
|
+
};
|
|
62
|
+
})
|
|
63
|
+
: [];
|
|
64
|
+
await knex.transaction(async (trx) => {
|
|
65
|
+
// Resolve the new membership and read the previous one *before* the
|
|
66
|
+
// deletes below — label inheritance needs both sides.
|
|
67
|
+
const urls = [...templateKeysByUrl.keys()];
|
|
68
|
+
const pageIdByUrl = new Map();
|
|
69
|
+
await eachSplitted(urls, 500, async (chunk) => {
|
|
70
|
+
const pageRows = await trx('content_items')
|
|
71
|
+
.join('url_refs', 'url_refs.id', 'content_items.url_id')
|
|
72
|
+
.select('content_items.id as id', 'url_refs.url as url')
|
|
73
|
+
.whereIn('url_refs.url', chunk);
|
|
74
|
+
for (const row of pageRows) {
|
|
75
|
+
pageIdByUrl.set(row.url, row.id);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
const rows = [];
|
|
79
|
+
const clusters = new Map();
|
|
80
|
+
for (const [url, templateKey] of templateKeysByUrl) {
|
|
81
|
+
const pageId = pageIdByUrl.get(url);
|
|
82
|
+
if (pageId == null) {
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
rows.push({ page_id: pageId, template_key: templateKey });
|
|
86
|
+
let cluster = clusters.get(templateKey);
|
|
87
|
+
if (!cluster) {
|
|
88
|
+
cluster = { pageIds: [], urls: [] };
|
|
89
|
+
clusters.set(templateKey, cluster);
|
|
90
|
+
}
|
|
91
|
+
cluster.pageIds.push(pageId);
|
|
92
|
+
cluster.urls.push(url);
|
|
93
|
+
}
|
|
94
|
+
const previousLabels = await loadPreviousLabels(trx);
|
|
95
|
+
const labels = assignTemplateLabels({
|
|
96
|
+
clusters,
|
|
97
|
+
previousMembership: await loadPreviousMembership(trx),
|
|
98
|
+
previousLabels,
|
|
99
|
+
});
|
|
100
|
+
// Rows to drop: the keys being (re)written, plus previous keys whose
|
|
101
|
+
// label was inherited by a new key — the label moved, so its old row
|
|
102
|
+
// would otherwise linger as a duplicate of the same name.
|
|
103
|
+
const writtenPairs = new Set([...labels.values()].map(labelPair));
|
|
104
|
+
const staleKeys = [...labels.keys()];
|
|
105
|
+
for (const [previousKey, label] of previousLabels) {
|
|
106
|
+
if (!labels.has(previousKey) && writtenPairs.has(labelPair(label))) {
|
|
107
|
+
staleKeys.push(previousKey);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
await trx('page_templates').delete();
|
|
111
|
+
await trx('page_template_clusters').delete();
|
|
112
|
+
await eachSplitted(staleKeys, 500, async (chunk) => {
|
|
113
|
+
await trx('page_template_labels').whereIn('template_key', chunk).delete();
|
|
114
|
+
});
|
|
115
|
+
if (reasonRows.length > 0) {
|
|
116
|
+
await eachSplitted(reasonRows, 100, async (chunk) => {
|
|
117
|
+
await trx('page_template_clusters').insert(chunk);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
if (rows.length === 0) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
await eachSplitted(rows, 500, async (chunk) => {
|
|
124
|
+
await trx('page_templates').insert(chunk);
|
|
125
|
+
});
|
|
126
|
+
const labelRows = [...labels].map(([templateKey, label]) => ({
|
|
127
|
+
template_key: templateKey,
|
|
128
|
+
section: label.section,
|
|
129
|
+
ordinal: label.ordinal,
|
|
130
|
+
}));
|
|
131
|
+
await eachSplitted(labelRows, 500, async (chunk) => {
|
|
132
|
+
await trx('page_template_labels').insert(chunk);
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The identity of a label as a name: its `(section, ordinal)` pair.
|
|
138
|
+
* @param label - The label.
|
|
139
|
+
* @returns A string key unique per name.
|
|
140
|
+
*/
|
|
141
|
+
function labelPair(label) {
|
|
142
|
+
return `${label.section ?? '\0'}:${label.ordinal}`;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Reads the previous run's `page_templates` rows as template key → page ids.
|
|
146
|
+
* @param trx - The replacing transaction.
|
|
147
|
+
* @returns The previous membership; empty on a first run.
|
|
148
|
+
*/
|
|
149
|
+
async function loadPreviousMembership(trx) {
|
|
150
|
+
const previousRows = (await trx('page_templates').select('page_id as pageId', 'template_key as templateKey'));
|
|
151
|
+
const membership = new Map();
|
|
152
|
+
for (const row of previousRows) {
|
|
153
|
+
const pageIds = membership.get(row.templateKey);
|
|
154
|
+
if (pageIds) {
|
|
155
|
+
pageIds.push(row.pageId);
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
membership.set(row.templateKey, [row.pageId]);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return membership;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Reads the previous run's `page_template_labels` rows.
|
|
165
|
+
* @param trx - The replacing transaction.
|
|
166
|
+
* @returns Template key → label; empty on a first run.
|
|
167
|
+
*/
|
|
168
|
+
async function loadPreviousLabels(trx) {
|
|
169
|
+
const labelRows = (await trx('page_template_labels').select('template_key as templateKey', 'section', 'ordinal'));
|
|
170
|
+
return new Map(labelRows.map((row) => [
|
|
171
|
+
row.templateKey,
|
|
172
|
+
{ section: row.section, ordinal: row.ordinal },
|
|
173
|
+
]));
|
|
174
|
+
}
|
|
@@ -46,6 +46,44 @@ export interface TemplateClusterReason {
|
|
|
46
46
|
readonly landmarks: Partial<Record<TemplateClusterLandmarkType, TemplateClusterLandmarkProfile>>;
|
|
47
47
|
readonly siblingClusterKeys: readonly string[];
|
|
48
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* The human-facing name of one template cluster, as stored in
|
|
51
|
+
* `page_template_labels`: rendered as `<section> template <letter>` (or
|
|
52
|
+
* `template <letter>` when `section` is `null`), where the letter is
|
|
53
|
+
* `ordinal` in A, B, …, Z, AA, AB, … form. Assigned by
|
|
54
|
+
* {@link import('./assign-template-labels.js').assignTemplateLabels}.
|
|
55
|
+
*/
|
|
56
|
+
export interface TemplateLabel {
|
|
57
|
+
/**
|
|
58
|
+
* The top-level URL directory every member page sits under (`events` for
|
|
59
|
+
* `/events/...`), or `null` when members span several directories or all
|
|
60
|
+
* sit at the site root — the label is then numbered site-wide.
|
|
61
|
+
*/
|
|
62
|
+
readonly section: string | null;
|
|
63
|
+
/** 1-based position within `section`'s label sequence. */
|
|
64
|
+
readonly ordinal: number;
|
|
65
|
+
}
|
|
66
|
+
/** One cluster's membership as {@link import('./assign-template-labels.js').assignTemplateLabels} sees it. */
|
|
67
|
+
export interface TemplateLabelClusterInput {
|
|
68
|
+
/** Resolved `content_items.id` of every member page. */
|
|
69
|
+
readonly pageIds: readonly number[];
|
|
70
|
+
/** URL of every member page, for deriving {@link TemplateLabel.section}. */
|
|
71
|
+
readonly urls: readonly string[];
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Params for {@link import('./assign-template-labels.js').assignTemplateLabels}.
|
|
75
|
+
*/
|
|
76
|
+
export interface AssignTemplateLabelsParams {
|
|
77
|
+
/** The new classification: template key → members. */
|
|
78
|
+
readonly clusters: ReadonlyMap<string, TemplateLabelClusterInput>;
|
|
79
|
+
/**
|
|
80
|
+
* The previous classification's `page_templates` rows: template key →
|
|
81
|
+
* member page ids. Empty on a first run.
|
|
82
|
+
*/
|
|
83
|
+
readonly previousMembership: ReadonlyMap<string, readonly number[]>;
|
|
84
|
+
/** The previous classification's `page_template_labels` rows. Empty on a first run. */
|
|
85
|
+
readonly previousLabels: ReadonlyMap<string, TemplateLabel>;
|
|
86
|
+
}
|
|
49
87
|
/**
|
|
50
88
|
* Params for {@link import('./replace-page-templates.js').replacePageTemplates}.
|
|
51
89
|
*/
|
|
@@ -13,7 +13,7 @@ export declare function applyConnectionPragmas(instance: Knex): Promise<void>;
|
|
|
13
13
|
/**
|
|
14
14
|
* Initializes the archive database schema if tables do not exist.
|
|
15
15
|
*
|
|
16
|
-
* The schema is composed of
|
|
16
|
+
* The schema is composed of five groups, each owned by a dedicated DDL
|
|
17
17
|
* function so the migration script (`scripts/migrate-to-0.13.mjs`) can
|
|
18
18
|
* provision the exact same shapes on archives it upgrades:
|
|
19
19
|
*
|
|
@@ -34,6 +34,10 @@ export declare function applyConnectionPragmas(instance: Knex): Promise<void>;
|
|
|
34
34
|
* `analysis_text_refs` + `analysis_violations`, `page_html_blobs` +
|
|
35
35
|
* `page_html_ref`. Must run AFTER `createEntityTables` because the
|
|
36
36
|
* page-scoped tables FK into `content_items(id)`.
|
|
37
|
+
* - **Template classification tables** ({@link createTemplateTables}):
|
|
38
|
+
* `page_templates`, `page_template_clusters`, `page_template_labels` —
|
|
39
|
+
* the crawl-end DOM-structure classification, kept apart from the
|
|
40
|
+
* adjunct/analysis tables because it has its own producer and write path.
|
|
37
41
|
*
|
|
38
42
|
* The legacy flat write-model tables (`pages` / `anchors` / `images` /
|
|
39
43
|
* `resources` / `resources-referrers`) are deliberately NOT created:
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createAdjunctTables } from './create-adjunct-tables.js';
|
|
2
2
|
import { createEntityTables } from './create-entity-tables.js';
|
|
3
3
|
import { createRefTables } from './create-ref-tables.js';
|
|
4
|
+
import { createTemplateTables } from './create-template-tables.js';
|
|
4
5
|
/**
|
|
5
6
|
* Applies the connection-level PRAGMAs that govern foreign-key enforcement
|
|
6
7
|
* and BLOB-read performance. These are **per-connection** settings (libsql
|
|
@@ -38,7 +39,7 @@ export async function applyConnectionPragmas(instance) {
|
|
|
38
39
|
/**
|
|
39
40
|
* Initializes the archive database schema if tables do not exist.
|
|
40
41
|
*
|
|
41
|
-
* The schema is composed of
|
|
42
|
+
* The schema is composed of five groups, each owned by a dedicated DDL
|
|
42
43
|
* function so the migration script (`scripts/migrate-to-0.13.mjs`) can
|
|
43
44
|
* provision the exact same shapes on archives it upgrades:
|
|
44
45
|
*
|
|
@@ -59,6 +60,10 @@ export async function applyConnectionPragmas(instance) {
|
|
|
59
60
|
* `analysis_text_refs` + `analysis_violations`, `page_html_blobs` +
|
|
60
61
|
* `page_html_ref`. Must run AFTER `createEntityTables` because the
|
|
61
62
|
* page-scoped tables FK into `content_items(id)`.
|
|
63
|
+
* - **Template classification tables** ({@link createTemplateTables}):
|
|
64
|
+
* `page_templates`, `page_template_clusters`, `page_template_labels` —
|
|
65
|
+
* the crawl-end DOM-structure classification, kept apart from the
|
|
66
|
+
* adjunct/analysis tables because it has its own producer and write path.
|
|
62
67
|
*
|
|
63
68
|
* The legacy flat write-model tables (`pages` / `anchors` / `images` /
|
|
64
69
|
* `resources` / `resources-referrers`) are deliberately NOT created:
|
|
@@ -79,7 +84,7 @@ export async function applyConnectionPragmas(instance) {
|
|
|
79
84
|
*/
|
|
80
85
|
export async function initSchema(instance) {
|
|
81
86
|
// Only the one-shot work (PRAGMAs + `info` creation) is gated on the
|
|
82
|
-
// `info` table's existence. The
|
|
87
|
+
// `info` table's existence. The DDL groups below run on EVERY
|
|
83
88
|
// call: each is internally idempotent (sentinel / IF NOT EXISTS /
|
|
84
89
|
// per-table guards), and re-running them self-heals an archive whose
|
|
85
90
|
// provisioning crashed partway through — `info` created but a later
|
|
@@ -143,4 +148,10 @@ export async function initSchema(instance) {
|
|
|
143
148
|
// two paths is exactly how migrated archives ended up with stale
|
|
144
149
|
// `REFERENCES pages(id)` declarations in the pre-0.13 era.
|
|
145
150
|
await createAdjunctTables(instance);
|
|
151
|
+
// Template classification tables (page_templates / page_template_clusters /
|
|
152
|
+
// page_template_labels). Separate from the adjunct group because the
|
|
153
|
+
// producer is the crawl-end classification step, not the crawl write path
|
|
154
|
+
// or analyze. `page_templates` FKs into `content_items(id)`, so this too
|
|
155
|
+
// MUST run after {@link createEntityTables}.
|
|
156
|
+
await createTemplateTables(instance);
|
|
146
157
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Config } from '../types.js';
|
|
2
|
+
import type { Knex } from 'knex';
|
|
3
|
+
/**
|
|
4
|
+
* Builds a file-backed knex connection against the FULL current archive
|
|
5
|
+
* schema (every ref/entity/adjunct table, including columns only a
|
|
6
|
+
* migration adds to a legacy archive — `alias_of_id`, `dedupe_cap_event_id`,
|
|
7
|
+
* `body_hash`, …) by running the exact same {@link init} boot sequence a
|
|
8
|
+
* real `Archive.create`/`Archive.open` uses. Shared by every
|
|
9
|
+
* `archive/transfer/` spec that needs a realistic source or destination
|
|
10
|
+
* database — hand-rolling `createRefTables`/`createEntityTables`/
|
|
11
|
+
* `createAdjunctTables` directly would produce the schema `initSchema`
|
|
12
|
+
* creates but skip the migrations that add columns for archives created
|
|
13
|
+
* before those features existed (which happen to be a no-op on a fresh
|
|
14
|
+
* DB today, but drift is exactly the risk this helper avoids).
|
|
15
|
+
*
|
|
16
|
+
* A DB file must be used (not `:memory:`) because `ATTACH DATABASE` in
|
|
17
|
+
* the transfer primitives needs a real path — see `attach-source-database.ts`.
|
|
18
|
+
* @param filename - Absolute path to the SQLite file. The caller is
|
|
19
|
+
* responsible for removing it (`afterEach`) — see existing specs for the
|
|
20
|
+
* convention.
|
|
21
|
+
* @param config - Overrides merged over {@link DEFAULT_TEST_CONFIG} and
|
|
22
|
+
* written via `setConfig` once the schema exists. Pass `null` to skip
|
|
23
|
+
* writing an `info` row entirely (some specs seed `content_items`
|
|
24
|
+
* directly and never read `getConfig()`).
|
|
25
|
+
* @returns The connected knex instance, on the current schema, with an
|
|
26
|
+
* `info` row unless `config` is `null`.
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const db = await buildFullSchemaTestDb(path.resolve(workingDir, 'source.sqlite'), {
|
|
30
|
+
* roots: ['https://a.example.com/'],
|
|
31
|
+
* });
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare function buildFullSchemaTestDb(filename: string, config?: Partial<Config> | null): Promise<Knex>;
|