@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.
Files changed (136) hide show
  1. package/lib/archive/archive.d.ts +13 -5
  2. package/lib/archive/archive.js +13 -5
  3. package/lib/archive/cache/extract-archive-to-cache.d.ts +6 -1
  4. package/lib/archive/cache/extract-archive-to-cache.js +13 -6
  5. package/lib/archive/create-adjunct-tables.d.ts +0 -7
  6. package/lib/archive/create-adjunct-tables.js +0 -50
  7. package/lib/archive/create-template-tables.d.ts +30 -0
  8. package/lib/archive/create-template-tables.js +95 -0
  9. package/lib/archive/database.d.ts +1 -1
  10. package/lib/archive/database.js +1 -1
  11. package/lib/archive/db-ops/pages/read/get-crawling-state.d.ts +43 -3
  12. package/lib/archive/db-ops/pages/read/get-crawling-state.js +61 -6
  13. package/lib/archive/db-ops/pages/write/update-page.js +10 -2
  14. package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
  15. package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
  16. package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
  17. package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
  18. package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
  19. package/lib/archive/init-schema.d.ts +5 -1
  20. package/lib/archive/init-schema.js +13 -2
  21. package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
  22. package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
  23. package/lib/archive/transfer/attach-source-database.d.ts +31 -0
  24. package/lib/archive/transfer/attach-source-database.js +40 -0
  25. package/lib/archive/transfer/build-split-config.d.ts +30 -0
  26. package/lib/archive/transfer/build-split-config.js +42 -0
  27. package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
  28. package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
  29. package/lib/archive/transfer/concat-archives.d.ts +55 -0
  30. package/lib/archive/transfer/concat-archives.js +95 -0
  31. package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
  32. package/lib/archive/transfer/content-item-rank-sql.js +23 -0
  33. package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
  34. package/lib/archive/transfer/copy-analysis-violations.js +43 -0
  35. package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
  36. package/lib/archive/transfer/copy-anchor-edges.js +42 -0
  37. package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  38. package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
  39. package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
  40. package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
  41. package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
  42. package/lib/archive/transfer/copy-header-set-children.js +51 -0
  43. package/lib/archive/transfer/copy-image-items.d.ts +21 -0
  44. package/lib/archive/transfer/copy-image-items.js +62 -0
  45. package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
  46. package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
  47. package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
  48. package/lib/archive/transfer/copy-journal-tables.js +56 -0
  49. package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
  50. package/lib/archive/transfer/copy-page-console-logs.js +27 -0
  51. package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
  52. package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
  53. package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
  54. package/lib/archive/transfer/copy-page-meta.js +68 -0
  55. package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
  56. package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
  57. package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
  58. package/lib/archive/transfer/copy-page-template-labels.js +88 -0
  59. package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
  60. package/lib/archive/transfer/copy-resource-items.js +89 -0
  61. package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
  62. package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
  63. package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  64. package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
  65. package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
  66. package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
  67. package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
  68. package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
  69. package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
  70. package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
  71. package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
  72. package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
  73. package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
  74. package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
  75. package/lib/archive/transfer/insert-content-items.d.ts +35 -0
  76. package/lib/archive/transfer/insert-content-items.js +116 -0
  77. package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
  78. package/lib/archive/transfer/list-transfer-columns.js +45 -0
  79. package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
  80. package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
  81. package/lib/archive/transfer/merge-archive-configs.d.ts +48 -0
  82. package/lib/archive/transfer/merge-archive-configs.js +78 -0
  83. package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
  84. package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
  85. package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
  86. package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
  87. package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
  88. package/lib/archive/transfer/plan-resource-items.js +69 -0
  89. package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
  90. package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
  91. package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
  92. package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
  93. package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
  94. package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
  95. package/lib/archive/transfer/replace-content-items.d.ts +39 -0
  96. package/lib/archive/transfer/replace-content-items.js +83 -0
  97. package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
  98. package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
  99. package/lib/archive/transfer/split-archive.d.ts +55 -0
  100. package/lib/archive/transfer/split-archive.js +98 -0
  101. package/lib/archive/transfer/transfer-action.d.ts +34 -0
  102. package/lib/archive/transfer/transfer-action.js +32 -0
  103. package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
  104. package/lib/archive/transfer/transfer-archive-rows.js +158 -0
  105. package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
  106. package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
  107. package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
  108. package/lib/archive/transfer/transfer-source-alias.js +9 -0
  109. package/lib/archive/transfer/types.d.ts +111 -0
  110. package/lib/archive/transfer/types.js +35 -0
  111. package/lib/concat-source-transfer-phases.d.ts +10 -0
  112. package/lib/concat-source-transfer-phases.js +17 -0
  113. package/lib/crawler/build-scope-map.d.ts +21 -0
  114. package/lib/crawler/build-scope-map.js +32 -0
  115. package/lib/crawler-orchestrator.js +10 -16
  116. package/lib/crawler.d.ts +13 -1
  117. package/lib/crawler.js +22 -0
  118. package/lib/split-source-transfer-phases.d.ts +11 -0
  119. package/lib/split-source-transfer-phases.js +18 -0
  120. package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
  121. package/lib/template-classification/classify-archive-page-templates.js +79 -0
  122. package/lib/template-classification/classify-page-templates.d.ts +37 -0
  123. package/lib/template-classification/classify-page-templates.js +69 -0
  124. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  125. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  126. package/lib/template-classification/create-content-root-hint.d.ts +36 -0
  127. package/lib/template-classification/create-content-root-hint.js +47 -0
  128. package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
  129. package/lib/template-classification/create-page-cluster-factory.js +98 -0
  130. package/lib/template-classification/types.d.ts +108 -0
  131. package/lib/template-classification/types.js +1 -0
  132. package/lib/transfer-post-phases.d.ts +10 -0
  133. package/lib/transfer-post-phases.js +13 -0
  134. package/package.json +3 -2
  135. package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
  136. /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
@@ -0,0 +1,65 @@
1
+ import type { TransferCallbacks, TransferSourceResult } from './types.js';
2
+ import type { ExURL, ParseURLOptions } from '@d-zero/shared/parse-url';
3
+ import type { Knex } from 'knex';
4
+ /** One source's transfer mode and (for split) scope-check inputs. */
5
+ export type TransferSourceMode = {
6
+ readonly kind: 'concat';
7
+ } | {
8
+ readonly kind: 'split';
9
+ readonly scopeMap: ReadonlyMap<string, readonly ExURL[]>;
10
+ readonly parseOptions?: ParseURLOptions;
11
+ };
12
+ /**
13
+ * Transfers ONE source archive's rows into the destination — the shared
14
+ * engine {@link import('./concat-archives.js').concatArchives} and
15
+ * {@link import('./split-archive.js').splitArchive} both drive, once per
16
+ * source. Attaches the source, plans, copies every table in dependency
17
+ * order, and detaches — always, even on failure (`finally`).
18
+ *
19
+ * Order within the transaction (see each step's own docs for why this
20
+ * exact order, not a different one):
21
+ * 1. Plan `content_items` (mode-specific) and `resource_items`.
22
+ * 2. Copy every dictionary (mode-specific), then their `header_sets`
23
+ * children and `page_html_blobs` (both depend on the dictionary maps
24
+ * dictionaries step just built).
25
+ * 3. Concat only: clear the old page-scoped rows of every `replace`
26
+ * destination, then overwrite its `content_items` row. Both modes:
27
+ * insert every `full`/`stub` row, backfilling `dest_id`; remap
28
+ * `redirect_dest_id` now that every row has one.
29
+ * 4. Copy every page-scoped table.
30
+ * 5. Copy `resource_items` (and its js-scan cache), then
31
+ * `resource_ref_edges` (needs the resource plan's `dest_id`, just
32
+ * resolved).
33
+ * 6. Copy the append-only journal tables.
34
+ * @param options - See individual properties.
35
+ * @param options.knex - Knex connected to the destination archive DB (the
36
+ * connection ATTACH/temp-tables/transaction all operate against).
37
+ * @param options.sourceDbPath - Absolute path to the source's `db.sqlite`
38
+ * (e.g. `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
39
+ * @param options.mode - `{ kind: 'concat' }`, or `{ kind: 'split',
40
+ * scopeMap, parseOptions? }` for the narrower-scope pass.
41
+ * @param options.crawlOrderOffset - Forwarded to
42
+ * `insertContentItems`/`replaceContentItems` — see their docs.
43
+ * @param options.sourceIndex - This source's 0-based position, forwarded
44
+ * verbatim to `callbacks` — purely for display, not used in any query.
45
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
46
+ * @returns Per-action row counts — see {@link TransferSourceResult}.
47
+ * @example
48
+ * ```ts
49
+ * const result = await transferArchiveRows({
50
+ * knex: destination.getKnex(),
51
+ * sourceDbPath: path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME),
52
+ * mode: { kind: 'concat' },
53
+ * crawlOrderOffset: 0,
54
+ * sourceIndex: 0,
55
+ * });
56
+ * ```
57
+ */
58
+ export declare function transferArchiveRows(options: {
59
+ readonly knex: Knex;
60
+ readonly sourceDbPath: string;
61
+ readonly mode: TransferSourceMode;
62
+ readonly crawlOrderOffset: number;
63
+ readonly sourceIndex: number;
64
+ readonly callbacks?: TransferCallbacks;
65
+ }): Promise<TransferSourceResult>;
@@ -0,0 +1,158 @@
1
+ import { attachSourceDatabase } from './attach-source-database.js';
2
+ import { clearReplacedPageRows } from './clear-replaced-page-rows.js';
3
+ import { copyAnalysisViolations } from './copy-analysis-violations.js';
4
+ import { copyAnchorEdges } from './copy-anchor-edges.js';
5
+ import { copyDictionariesForConcat } from './copy-dictionaries-for-concat.js';
6
+ import { copyDictionariesForSplit } from './copy-dictionaries-for-split.js';
7
+ import { copyHeaderSetChildren } from './copy-header-set-children.js';
8
+ import { copyImageItems } from './copy-image-items.js';
9
+ import { copyJournalTables } from './copy-journal-tables.js';
10
+ import { copyPageConsoleLogs } from './copy-page-console-logs.js';
11
+ import { copyPageHtmlBlobs } from './copy-page-html-blobs.js';
12
+ import { copyPageMeta } from './copy-page-meta.js';
13
+ import { copyPageTemplateClusters } from './copy-page-template-clusters.js';
14
+ import { copyPageTemplateLabels } from './copy-page-template-labels.js';
15
+ import { copyResourceItems } from './copy-resource-items.js';
16
+ import { copyResourceRefEdges } from './copy-resource-ref-edges.js';
17
+ import { copySimplePageScopedTables } from './copy-simple-page-scoped-tables.js';
18
+ import { createTransferTempTables } from './create-transfer-temp-tables.js';
19
+ import { dropTransferTempTables } from './drop-transfer-temp-tables.js';
20
+ import { insertContentItems } from './insert-content-items.js';
21
+ import { markInScopeContentItems } from './mark-in-scope-content-items.js';
22
+ import { planContentItemsForConcat } from './plan-content-items-for-concat.js';
23
+ import { planContentItemsForSplit } from './plan-content-items-for-split.js';
24
+ import { planResourceItems } from './plan-resource-items.js';
25
+ import { remapRedirectDestIds } from './remap-redirect-dest-ids.js';
26
+ import { replaceContentItems } from './replace-content-items.js';
27
+ import { TRANSFER_ACTION } from './transfer-action.js';
28
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
29
+ /**
30
+ * Computes {@link TransferSourceResult} from the finished plan tables.
31
+ * `dropped` (split only) is `sourceTotal - (inserted + stubbed)` — the
32
+ * plan never lists dropped rows explicitly, so this is a subtraction
33
+ * against the source's own total row count rather than a query for
34
+ * absence.
35
+ * @param trx - The open transaction.
36
+ * @param mode - `'split'` computes `dropped`; `'concat'` always reports `0`.
37
+ */
38
+ async function summarizeTransferResult(trx, mode) {
39
+ const rows = await trx
40
+ .select('action')
41
+ .count({ count: '*' })
42
+ .from('xfer_ci_plan')
43
+ .groupBy('action');
44
+ const byAction = new Map(rows.map((r) => [r.action, Number(r.count)]));
45
+ const inserted = byAction.get(TRANSFER_ACTION.full) ?? 0;
46
+ const replaced = byAction.get(TRANSFER_ACTION.replace) ?? 0;
47
+ const skipped = byAction.get(TRANSFER_ACTION.skip) ?? 0;
48
+ const stubbed = byAction.get(TRANSFER_ACTION.stub) ?? 0;
49
+ let dropped = 0;
50
+ if (mode === 'split') {
51
+ const [totalRow] = await trx
52
+ .count({ total: '*' })
53
+ .from(`${TRANSFER_SOURCE_ALIAS}.content_items`);
54
+ dropped = Number(totalRow?.total ?? 0) - (inserted + stubbed);
55
+ }
56
+ return { inserted, replaced, skipped, stubbed, dropped };
57
+ }
58
+ /**
59
+ * Transfers ONE source archive's rows into the destination — the shared
60
+ * engine {@link import('./concat-archives.js').concatArchives} and
61
+ * {@link import('./split-archive.js').splitArchive} both drive, once per
62
+ * source. Attaches the source, plans, copies every table in dependency
63
+ * order, and detaches — always, even on failure (`finally`).
64
+ *
65
+ * Order within the transaction (see each step's own docs for why this
66
+ * exact order, not a different one):
67
+ * 1. Plan `content_items` (mode-specific) and `resource_items`.
68
+ * 2. Copy every dictionary (mode-specific), then their `header_sets`
69
+ * children and `page_html_blobs` (both depend on the dictionary maps
70
+ * dictionaries step just built).
71
+ * 3. Concat only: clear the old page-scoped rows of every `replace`
72
+ * destination, then overwrite its `content_items` row. Both modes:
73
+ * insert every `full`/`stub` row, backfilling `dest_id`; remap
74
+ * `redirect_dest_id` now that every row has one.
75
+ * 4. Copy every page-scoped table.
76
+ * 5. Copy `resource_items` (and its js-scan cache), then
77
+ * `resource_ref_edges` (needs the resource plan's `dest_id`, just
78
+ * resolved).
79
+ * 6. Copy the append-only journal tables.
80
+ * @param options - See individual properties.
81
+ * @param options.knex - Knex connected to the destination archive DB (the
82
+ * connection ATTACH/temp-tables/transaction all operate against).
83
+ * @param options.sourceDbPath - Absolute path to the source's `db.sqlite`
84
+ * (e.g. `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
85
+ * @param options.mode - `{ kind: 'concat' }`, or `{ kind: 'split',
86
+ * scopeMap, parseOptions? }` for the narrower-scope pass.
87
+ * @param options.crawlOrderOffset - Forwarded to
88
+ * `insertContentItems`/`replaceContentItems` — see their docs.
89
+ * @param options.sourceIndex - This source's 0-based position, forwarded
90
+ * verbatim to `callbacks` — purely for display, not used in any query.
91
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
92
+ * @returns Per-action row counts — see {@link TransferSourceResult}.
93
+ * @example
94
+ * ```ts
95
+ * const result = await transferArchiveRows({
96
+ * knex: destination.getKnex(),
97
+ * sourceDbPath: path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME),
98
+ * mode: { kind: 'concat' },
99
+ * crawlOrderOffset: 0,
100
+ * sourceIndex: 0,
101
+ * });
102
+ * ```
103
+ */
104
+ export async function transferArchiveRows(options) {
105
+ const { knex, sourceDbPath, mode, crawlOrderOffset, sourceIndex, callbacks } = options;
106
+ const detach = await attachSourceDatabase(knex, sourceDbPath);
107
+ await createTransferTempTables(knex);
108
+ try {
109
+ return await knex.transaction(async (trx) => {
110
+ callbacks?.onPhase?.(sourceIndex, 'planningContentItems');
111
+ if (mode.kind === 'split') {
112
+ await markInScopeContentItems(trx, mode.scopeMap, mode.parseOptions);
113
+ await planContentItemsForSplit(trx);
114
+ await planResourceItems(trx, 'split');
115
+ }
116
+ else {
117
+ await planContentItemsForConcat(trx);
118
+ await planResourceItems(trx, 'concat');
119
+ }
120
+ callbacks?.onPhase?.(sourceIndex, 'copyingDictionaries');
121
+ if (mode.kind === 'split') {
122
+ await copyDictionariesForSplit(trx);
123
+ }
124
+ else {
125
+ await copyDictionariesForConcat(trx);
126
+ }
127
+ await copyHeaderSetChildren(trx);
128
+ await copyPageHtmlBlobs(trx);
129
+ callbacks?.onPhase?.(sourceIndex, 'copyingContentItems');
130
+ if (mode.kind === 'concat') {
131
+ await clearReplacedPageRows(trx);
132
+ await replaceContentItems(trx, { crawlOrderOffset });
133
+ }
134
+ await insertContentItems(trx, { crawlOrderOffset });
135
+ await remapRedirectDestIds(trx);
136
+ callbacks?.onPhase?.(sourceIndex, 'copyingPageRows');
137
+ await copyPageMeta(trx);
138
+ await copyImageItems(trx);
139
+ await copyAnchorEdges(trx);
140
+ await copySimplePageScopedTables(trx);
141
+ await copyPageTemplateClusters(trx);
142
+ await copyPageTemplateLabels(trx);
143
+ await copyPageConsoleLogs(trx);
144
+ await copyAnalysisViolations(trx);
145
+ callbacks?.onPhase?.(sourceIndex, 'copyingResources');
146
+ await copyResourceItems(trx);
147
+ await copyResourceRefEdges(trx);
148
+ callbacks?.onPhase?.(sourceIndex, 'copyingJournals');
149
+ await copyJournalTables(trx, mode.kind);
150
+ callbacks?.onPhase?.(sourceIndex, 'committing');
151
+ return await summarizeTransferResult(trx, mode.kind);
152
+ });
153
+ }
154
+ finally {
155
+ await dropTransferTempTables(knex);
156
+ await detach();
157
+ }
158
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The fixed set of dictionary tables a transfer's need-based dictionary
3
+ * copy tracks per-id "is this row referenced by anything kept" state for.
4
+ * Drives the loop in {@link import('./create-transfer-temp-tables.js').createTransferTempTables} /
5
+ * {@link import('./drop-transfer-temp-tables.js').dropTransferTempTables}
6
+ * that creates/drops one `(src_id PRIMARY KEY)` need-table and one
7
+ * `(src_id PRIMARY KEY, dest_id)` map-table per dictionary — every
8
+ * dictionary table shares that exact temp-table shape, only the
9
+ * population query differs (see `copy-dictionaries-for-concat.ts` /
10
+ * `copy-dictionaries-for-split.ts`).
11
+ */
12
+ export declare const TRANSFER_DICTIONARY_TABLES: readonly string[];
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The fixed set of dictionary tables a transfer's need-based dictionary
3
+ * copy tracks per-id "is this row referenced by anything kept" state for.
4
+ * Drives the loop in {@link import('./create-transfer-temp-tables.js').createTransferTempTables} /
5
+ * {@link import('./drop-transfer-temp-tables.js').dropTransferTempTables}
6
+ * that creates/drops one `(src_id PRIMARY KEY)` need-table and one
7
+ * `(src_id PRIMARY KEY, dest_id)` map-table per dictionary — every
8
+ * dictionary table shares that exact temp-table shape, only the
9
+ * population query differs (see `copy-dictionaries-for-concat.ts` /
10
+ * `copy-dictionaries-for-split.ts`).
11
+ */
12
+ export const TRANSFER_DICTIONARY_TABLES = [
13
+ 'url_refs',
14
+ 'content_type_refs',
15
+ 'text_refs',
16
+ 'json_refs',
17
+ 'blob_refs',
18
+ 'header_name_refs',
19
+ 'header_value_refs',
20
+ 'header_sets',
21
+ 'console_log_items',
22
+ 'analysis_text_refs',
23
+ ];
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The fixed schema alias a source archive's `db.sqlite` is `ATTACH`ed under
3
+ * during a transfer. A constant (not a per-call parameter) because every
4
+ * transfer SQL statement in `archive/transfer/` hard-codes this name —
5
+ * allowing a caller-supplied alias would mean threading it through every
6
+ * one of those statements for no real benefit (a transfer only ever
7
+ * attaches one source at a time; see `transfer-archive-rows.ts`).
8
+ */
9
+ export declare const TRANSFER_SOURCE_ALIAS = "xfer_src";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The fixed schema alias a source archive's `db.sqlite` is `ATTACH`ed under
3
+ * during a transfer. A constant (not a per-call parameter) because every
4
+ * transfer SQL statement in `archive/transfer/` hard-codes this name —
5
+ * allowing a caller-supplied alias would mean threading it through every
6
+ * one of those statements for no real benefit (a transfer only ever
7
+ * attaches one source at a time; see `transfer-archive-rows.ts`).
8
+ */
9
+ export const TRANSFER_SOURCE_ALIAS = 'xfer_src';
@@ -0,0 +1,111 @@
1
+ import type { Config } from '../types.js';
2
+ /**
3
+ * Ordered phase sequence a single source's transfer announces via
4
+ * `onPhase`, unconditionally and always in this order (mirrors
5
+ * `ViewerReadModelBuildPhase`'s contract — no branch skips a phase, so a
6
+ * caller can pre-build one `TaskList` row per phase and rely on them
7
+ * settling in order).
8
+ */
9
+ export type TransferPhase = 'planningContentItems' | 'copyingDictionaries' | 'copyingContentItems' | 'copyingPageRows' | 'copyingResources' | 'copyingJournals' | 'committing' | 'flatteningRedirects' | 'reclassifyingResources' | 'countingExternalInScope';
10
+ /**
11
+ * Progress callbacks a caller (the CLI's `concat`/`split` commands) passes
12
+ * into {@link import('./concat-archives.js').concatArchives} /
13
+ * {@link import('./split-archive.js').splitArchive} to drive a `TaskList`
14
+ * display. `onPhase` fires once per phase per source (plus once per
15
+ * whole-operation post phase); `onProgress` fires zero or more times while
16
+ * a phase is active, with a phase-specific unit (rows copied, ids
17
+ * classified, …).
18
+ */
19
+ export interface TransferCallbacks {
20
+ /** Called when a new source's extraction begins (0-based index). */
21
+ readonly onSourceStart?: (sourceIndex: number, filePath: string) => void;
22
+ /**
23
+ * Called whenever the active phase changes, for the source at
24
+ * `sourceIndex` (or after every source has finished, for the
25
+ * whole-operation post phases — `flatteningRedirects` /
26
+ * `reclassifyingResources` / `countingExternalInScope` — where
27
+ * `sourceIndex` is `sources.length`).
28
+ */
29
+ readonly onPhase?: (sourceIndex: number, phase: TransferPhase) => void;
30
+ /** Called zero or more times while a phase is active. */
31
+ readonly onProgress?: (processed: number, total: number) => void;
32
+ }
33
+ /** Per-source outcome of {@link import('./transfer-archive-rows.js').transferArchiveRows}. */
34
+ export interface TransferSourceResult {
35
+ /** Number of `content_items` rows copied as brand-new rows (no prior dest row for that URL). */
36
+ readonly inserted: number;
37
+ /**
38
+ * Number of existing dest `content_items` rows overwritten because this
39
+ * source's observation outranked the dest's (concat only; always `0`
40
+ * for split, which never merges into an existing archive).
41
+ */
42
+ readonly replaced: number;
43
+ /** Number of source rows skipped because dest already held an equal-or-better observation (concat only). */
44
+ readonly skipped: number;
45
+ /** Number of source rows kept as an external stub, not a full copy (split only; always `0` for concat). */
46
+ readonly stubbed: number;
47
+ /** Number of source rows dropped entirely — out of scope and unreferenced (split only; always `0` for concat). */
48
+ readonly dropped: number;
49
+ }
50
+ /** Result of {@link import('./concat-archives.js').concatArchives}. */
51
+ export interface ConcatArchivesResult {
52
+ /** The merged config written to the destination's `info` row. */
53
+ readonly config: Config;
54
+ /** Per-source transfer outcome, in argument order. */
55
+ readonly sources: readonly TransferSourceResult[];
56
+ /**
57
+ * Number of URLs that fall inside the merged scope but were never
58
+ * fetched as an internal page by any source (still `is_external = 1`
59
+ * in the output) — the count the CLI surfaces with a
60
+ * `crawl <out> --append <root>` hint, since concat never re-promotes
61
+ * external rows on its own (that would fabricate a `scraped = 1`
62
+ * observation with no body/meta behind it).
63
+ */
64
+ readonly externalInScopeCount: number;
65
+ /** Number of `inventory/<sha256>.txt` source lists copied (deduplicated by filename across sources). */
66
+ readonly inventoryListsCopied: number;
67
+ }
68
+ /** Result of {@link import('./split-archive.js').splitArchive}. */
69
+ export interface SplitArchiveResult {
70
+ /** The derived config (roots = the given scope URLs) written to the destination's `info` row. */
71
+ readonly config: Config;
72
+ /** The single source's transfer outcome. */
73
+ readonly source: TransferSourceResult;
74
+ /**
75
+ * Usually `0`, but not structurally guaranteed to be: the operator's
76
+ * scope URLs are not required to be a subset of the source's original
77
+ * roots, so a scope broader than (or merely different from) the
78
+ * original can bring an external-only (never crawled) page inside the
79
+ * new scope, the same way concat's own external-in-scope count can be
80
+ * non-zero.
81
+ */
82
+ readonly externalInScopeCount: number;
83
+ /** Number of `inventory/<sha256>.txt` source lists copied. */
84
+ readonly inventoryListsCopied: number;
85
+ }
86
+ /**
87
+ * Thrown by {@link import('./merge-archive-configs.js').mergeArchiveConfigs}
88
+ * when two source archives disagree on a config field that concat cannot
89
+ * silently reconcile (`disableQueries`, `fromList`) — see that function's
90
+ * docs for why these two specifically cannot fall back to "first archive
91
+ * wins" like every other scalar field.
92
+ */
93
+ export declare class ArchiveConfigConflictError extends Error {
94
+ readonly field: string;
95
+ readonly values: readonly unknown[];
96
+ /**
97
+ * @param field - The conflicting `Config` field name.
98
+ * @param values - The distinct values seen across sources, in argument order.
99
+ */
100
+ constructor(field: string, values: readonly unknown[]);
101
+ }
102
+ /**
103
+ * Thrown when a dictionary-table copy's post-copy id map does not cover
104
+ * every id it needed to map (a source row referencing a value that failed
105
+ * to insert or resolve) — a defensive integrity check, since a silently
106
+ * incomplete map would surface much later as a confusing "no such row" or
107
+ * a dangling NULL FK deep in an unrelated read path.
108
+ */
109
+ export declare class TransferIntegrityError extends Error {
110
+ constructor(message: string);
111
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Thrown by {@link import('./merge-archive-configs.js').mergeArchiveConfigs}
3
+ * when two source archives disagree on a config field that concat cannot
4
+ * silently reconcile (`disableQueries`, `fromList`) — see that function's
5
+ * docs for why these two specifically cannot fall back to "first archive
6
+ * wins" like every other scalar field.
7
+ */
8
+ export class ArchiveConfigConflictError extends Error {
9
+ field;
10
+ values;
11
+ /**
12
+ * @param field - The conflicting `Config` field name.
13
+ * @param values - The distinct values seen across sources, in argument order.
14
+ */
15
+ constructor(field, values) {
16
+ super(`Cannot merge archives: "${field}" differs across sources (${values.map((v) => JSON.stringify(v)).join(' vs ')}). ` +
17
+ 'Re-crawl the sources with matching settings before concatenating them.');
18
+ this.field = field;
19
+ this.values = values;
20
+ this.name = 'ArchiveConfigConflictError';
21
+ }
22
+ }
23
+ /**
24
+ * Thrown when a dictionary-table copy's post-copy id map does not cover
25
+ * every id it needed to map (a source row referencing a value that failed
26
+ * to insert or resolve) — a defensive integrity check, since a silently
27
+ * incomplete map would surface much later as a confusing "no such row" or
28
+ * a dangling NULL FK deep in an unrelated read path.
29
+ */
30
+ export class TransferIntegrityError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = 'TransferIntegrityError';
34
+ }
35
+ }
@@ -0,0 +1,10 @@
1
+ import type { TransferPhase } from './archive/transfer/types.js';
2
+ /**
3
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
4
+ * announces via `onPhase`, once per concat source, unconditionally and
5
+ * always in this order (see that function's own source — no branch skips
6
+ * a phase). Single source of truth for the per-source `TaskList` rows a
7
+ * CLI caller pre-builds (mirrors `VIEWER_READ_MODEL_FULL_BUILD_PHASES`'s
8
+ * same role for the read-model build).
9
+ */
10
+ export declare const CONCAT_SOURCE_TRANSFER_PHASES: readonly TransferPhase[];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
3
+ * announces via `onPhase`, once per concat source, unconditionally and
4
+ * always in this order (see that function's own source — no branch skips
5
+ * a phase). Single source of truth for the per-source `TaskList` rows a
6
+ * CLI caller pre-builds (mirrors `VIEWER_READ_MODEL_FULL_BUILD_PHASES`'s
7
+ * same role for the read-model build).
8
+ */
9
+ export const CONCAT_SOURCE_TRANSFER_PHASES = [
10
+ 'planningContentItems',
11
+ 'copyingDictionaries',
12
+ 'copyingContentItems',
13
+ 'copyingPageRows',
14
+ 'copyingResources',
15
+ 'copyingJournals',
16
+ 'committing',
17
+ ];
@@ -0,0 +1,21 @@
1
+ import type { ExURL, ParseURLOptions } from '@d-zero/shared/parse-url';
2
+ /**
3
+ * Builds a hostname-indexed scope map from a list of root URL strings, for
4
+ * use with {@link findScopeEntry}.
5
+ *
6
+ * Each root that fails to parse is silently skipped (a malformed root can
7
+ * never match anything anyway) rather than throwing, matching the existing
8
+ * inline construction this replaces (`crawler-orchestrator.ts`'s `append`
9
+ * and inventory-classification call sites, `Crawler`'s own scope build).
10
+ * Roots sharing a hostname are grouped under one array entry so
11
+ * `findScopeEntry` can pick the most specific match among them.
12
+ * @param roots - Root URL strings (e.g. `Config.roots`).
13
+ * @param options - URL parsing options forwarded to {@link parseUrl}.
14
+ * @returns A hostname-indexed map of parsed root URLs.
15
+ * @example
16
+ * ```ts
17
+ * const scope = buildScopeMap(['https://example.com/blog/', 'https://example.com/docs/']);
18
+ * findScopeEntry(url, scope); // deepest matching root, or null if external
19
+ * ```
20
+ */
21
+ export declare function buildScopeMap(roots: readonly string[], options?: ParseURLOptions): Map<string, ExURL[]>;
@@ -0,0 +1,32 @@
1
+ import { tryParseUrl as parseUrl } from '@d-zero/shared/parse-url';
2
+ /**
3
+ * Builds a hostname-indexed scope map from a list of root URL strings, for
4
+ * use with {@link findScopeEntry}.
5
+ *
6
+ * Each root that fails to parse is silently skipped (a malformed root can
7
+ * never match anything anyway) rather than throwing, matching the existing
8
+ * inline construction this replaces (`crawler-orchestrator.ts`'s `append`
9
+ * and inventory-classification call sites, `Crawler`'s own scope build).
10
+ * Roots sharing a hostname are grouped under one array entry so
11
+ * `findScopeEntry` can pick the most specific match among them.
12
+ * @param roots - Root URL strings (e.g. `Config.roots`).
13
+ * @param options - URL parsing options forwarded to {@link parseUrl}.
14
+ * @returns A hostname-indexed map of parsed root URLs.
15
+ * @example
16
+ * ```ts
17
+ * const scope = buildScopeMap(['https://example.com/blog/', 'https://example.com/docs/']);
18
+ * findScopeEntry(url, scope); // deepest matching root, or null if external
19
+ * ```
20
+ */
21
+ export function buildScopeMap(roots, options) {
22
+ const scope = new Map();
23
+ for (const raw of roots) {
24
+ const parsed = parseUrl(raw, options);
25
+ if (!parsed) {
26
+ continue;
27
+ }
28
+ const existing = scope.get(parsed.hostname) ?? [];
29
+ scope.set(parsed.hostname, [...existing, parsed]);
30
+ }
31
+ return scope;
32
+ }
@@ -9,6 +9,7 @@ import Archive from './archive/archive.js';
9
9
  import { copyFileWithProgress } from './archive/filesystem/copy-file-with-progress.js';
10
10
  import { REQUIRED_FORMAT_VERSION } from './archive/meta/assert-compatible-version.js';
11
11
  import { computeAutoRetryBackoffDelayMs } from './compute-auto-retry-backoff-delay.js';
12
+ import { buildScopeMap } from './crawler/build-scope-map.js';
12
13
  import { clearDestinationCache } from './crawler/clear-destination-cache.js';
13
14
  import { clearDnsBurnedHostCache } from './crawler/clear-dns-burned-host-cache.js';
14
15
  import Crawler from './crawler/crawler.js';
@@ -773,6 +774,13 @@ export class CrawlerOrchestrator extends EventEmitter {
773
774
  * that a final attempt which is both exhausted AND made no progress
774
775
  * reports as `'exhausted'` — the more actionable of the two (it tells
775
776
  * the operator the budget, not just that this one attempt stalled).
777
+ * `getCrawlingState()`'s "Confirmed same-cluster trap exclusion"
778
+ * filter (issue #350) keeps a `--dedupe-cap`-confirmed shape's own
779
+ * never-scraped descendants out of `pending` in the first place, so
780
+ * `pending` genuinely converging to 0 is no longer blocked by that
781
+ * shape — a `'no-progress'` or `'exhausted'` result here now points
782
+ * at a real, currently-unresolvable fetch failure (network/host),
783
+ * not at a same-cluster trap the cap already confirmed.
776
784
  *
777
785
  * Each retry attempt re-reads `getCrawlingState()` and
778
786
  * `getResourceUrlList()` in full — the same cost `retryFailed`/`resume`/
@@ -1073,14 +1081,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1073
1081
  await copyFileWithProgress(absFilePath, backupPath, setupProgress?.onCopyProgress);
1074
1082
  try {
1075
1083
  await archive.updateConfig(mergedConfig);
1076
- const scopeMap = new Map();
1077
- for (const raw of mergedRoots) {
1078
- const parsed = parseUrl(raw, archived);
1079
- if (!parsed)
1080
- continue;
1081
- const existing = scopeMap.get(parsed.hostname) ?? [];
1082
- scopeMap.set(parsed.hostname, [...existing, parsed]);
1083
- }
1084
+ const scopeMap = buildScopeMap(mergedRoots, archived);
1084
1085
  setupProgress?.onPhase?.(PHASE_REPROMOTING);
1085
1086
  await archive.repromoteExternalPages(scopeMap, archived, setupProgress?.onChunkProgress);
1086
1087
  // Seed the sticky set from prior sessions' confirmed traps so
@@ -1854,14 +1855,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1854
1855
  */
1855
1856
  static async #classifyInventoryCandidateUrls(rawUrls, archived, archive) {
1856
1857
  const parsedAll = sortUrl(rawUrls, archived);
1857
- const scopeMap = new Map();
1858
- for (const raw of archived.roots) {
1859
- const parsed = parseUrl(raw, archived);
1860
- if (!parsed)
1861
- continue;
1862
- const existing = scopeMap.get(parsed.hostname) ?? [];
1863
- scopeMap.set(parsed.hostname, [...existing, parsed]);
1864
- }
1858
+ const scopeMap = buildScopeMap(archived.roots, archived);
1865
1859
  const inScope = [];
1866
1860
  let outOfScope = 0;
1867
1861
  for (const url of parsedAll) {
package/lib/crawler.d.ts CHANGED
@@ -73,4 +73,16 @@ export { populateBlobRefs } from './archive/populate-ref-tables/populate-blob-re
73
73
  export { populateHeaderTables } from './archive/populate-ref-tables/populate-header-tables.js';
74
74
  export { loadResponseHeadersBySetIds } from './archive/db-ops/_shared/load-response-headers-by-set-ids.js';
75
75
  export { decodeJsonRef } from './archive/db-ops/_shared/decode-json-ref.js';
76
- export type { TemplateClusterBlockingEvidence, TemplateClusterBlockingReason, TemplateClusterLandmarkProfile, TemplateClusterLandmarkType, TemplateClusterReason, } from './archive/db-ops/analysis/types.js';
76
+ export type { AssignTemplateLabelsParams, TemplateClusterBlockingEvidence, TemplateClusterBlockingReason, TemplateClusterLandmarkProfile, TemplateClusterLandmarkType, TemplateClusterReason, TemplateLabel, TemplateLabelClusterInput, } from './archive/db-ops/templates/types.js';
77
+ export { assignTemplateLabels } from './archive/db-ops/templates/assign-template-labels.js';
78
+ export { classifyArchivePageTemplates } from './template-classification/classify-archive-page-templates.js';
79
+ export type { ClassifyArchivePageTemplatesOptions, ClassifyArchivePageTemplatesResult, TemplateClassificationProgress, TemplateClusteringProgress, } from './template-classification/types.js';
80
+ export { resolveOutputPath } from './resolve-output-path.js';
81
+ export { buildScopeMap } from './crawler/build-scope-map.js';
82
+ export type { ConcatArchivesResult, SplitArchiveResult, TransferCallbacks, TransferPhase, TransferSourceResult, } from './archive/transfer/types.js';
83
+ export { ArchiveConfigConflictError, TransferIntegrityError, } from './archive/transfer/types.js';
84
+ export { concatArchives } from './archive/transfer/concat-archives.js';
85
+ export { splitArchive } from './archive/transfer/split-archive.js';
86
+ export { CONCAT_SOURCE_TRANSFER_PHASES } from './concat-source-transfer-phases.js';
87
+ export { SPLIT_SOURCE_TRANSFER_PHASES } from './split-source-transfer-phases.js';
88
+ export { TRANSFER_POST_PHASES } from './transfer-post-phases.js';
package/lib/crawler.js CHANGED
@@ -78,3 +78,25 @@ export { populateHeaderTables } from './archive/populate-ref-tables/populate-hea
78
78
  // no cross-package drift.
79
79
  export { loadResponseHeadersBySetIds } from './archive/db-ops/_shared/load-response-headers-by-set-ids.js';
80
80
  export { decodeJsonRef } from './archive/db-ops/_shared/decode-json-ref.js';
81
+ // The label assigner is exported so `@nitpicker/query` can number clusters
82
+ // provisionally, with the exact same rules, for an archive classified before
83
+ // labels were stored — one implementation, no cross-package drift.
84
+ export { assignTemplateLabels } from './archive/db-ops/templates/assign-template-labels.js';
85
+ // Crawl-end DOM-structure template classification (page_templates /
86
+ // page_template_clusters / page_template_labels). A post-crawl derived-data
87
+ // step like `scanJsResourcesForTechnologySignals`, run by the CLI's crawl
88
+ // post-processing, `viewer-build`, `concat` and `split`.
89
+ export { classifyArchivePageTemplates } from './template-classification/classify-archive-page-templates.js';
90
+ // Output-path resolution and scope-map construction, needed by CLI commands
91
+ // that produce a NEW `.nitpicker` archive from existing ones (`concat` /
92
+ // `split`) rather than crawling — same normalization `crawl --output` and
93
+ // `pipeline` already apply, and the same hostname-indexed scope shape
94
+ // `findScopeEntry` consumes.
95
+ export { resolveOutputPath } from './resolve-output-path.js';
96
+ export { buildScopeMap } from './crawler/build-scope-map.js';
97
+ export { ArchiveConfigConflictError, TransferIntegrityError, } from './archive/transfer/types.js';
98
+ export { concatArchives } from './archive/transfer/concat-archives.js';
99
+ export { splitArchive } from './archive/transfer/split-archive.js';
100
+ export { CONCAT_SOURCE_TRANSFER_PHASES } from './concat-source-transfer-phases.js';
101
+ export { SPLIT_SOURCE_TRANSFER_PHASES } from './split-source-transfer-phases.js';
102
+ export { TRANSFER_POST_PHASES } from './transfer-post-phases.js';
@@ -0,0 +1,11 @@
1
+ import type { TransferPhase } from './archive/transfer/types.js';
2
+ /**
3
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
4
+ * announces via `onPhase` for split's single source — identical to
5
+ * {@link import('./concat-source-transfer-phases.js').CONCAT_SOURCE_TRANSFER_PHASES}
6
+ * (the phase sequence inside `transferArchiveRows` does not branch on
7
+ * mode, only what each phase DOES differs), kept as its own named export
8
+ * so a CLI caller building split's `TaskList` rows never has to reason
9
+ * about why it is importing something named "concat".
10
+ */
11
+ export declare const SPLIT_SOURCE_TRANSFER_PHASES: readonly TransferPhase[];
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
3
+ * announces via `onPhase` for split's single source — identical to
4
+ * {@link import('./concat-source-transfer-phases.js').CONCAT_SOURCE_TRANSFER_PHASES}
5
+ * (the phase sequence inside `transferArchiveRows` does not branch on
6
+ * mode, only what each phase DOES differs), kept as its own named export
7
+ * so a CLI caller building split's `TaskList` rows never has to reason
8
+ * about why it is importing something named "concat".
9
+ */
10
+ export const SPLIT_SOURCE_TRANSFER_PHASES = [
11
+ 'planningContentItems',
12
+ 'copyingDictionaries',
13
+ 'copyingContentItems',
14
+ 'copyingPageRows',
15
+ 'copyingResources',
16
+ 'copyingJournals',
17
+ 'committing',
18
+ ];