@nitpicker/crawler 0.22.2 → 0.24.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 (158) hide show
  1. package/lib/archive/archive.d.ts +13 -5
  2. package/lib/archive/archive.js +16 -7
  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/config/get-config.d.ts +1 -1
  12. package/lib/archive/db-ops/config/get-config.js +2 -1
  13. package/lib/archive/db-ops/config/info-column-allowlist.js +1 -0
  14. package/lib/archive/db-ops/config/info-json-columns.js +1 -0
  15. package/lib/archive/db-ops/lifecycle/init.js +2 -0
  16. package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
  17. package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
  18. package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
  19. package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
  20. package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
  21. package/lib/archive/init-schema.d.ts +5 -1
  22. package/lib/archive/init-schema.js +14 -2
  23. package/lib/archive/migrate-info-request-header-names.d.ts +16 -0
  24. package/lib/archive/migrate-info-request-header-names.js +35 -0
  25. package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
  26. package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
  27. package/lib/archive/transfer/attach-source-database.d.ts +31 -0
  28. package/lib/archive/transfer/attach-source-database.js +40 -0
  29. package/lib/archive/transfer/build-split-config.d.ts +30 -0
  30. package/lib/archive/transfer/build-split-config.js +42 -0
  31. package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
  32. package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
  33. package/lib/archive/transfer/concat-archives.d.ts +55 -0
  34. package/lib/archive/transfer/concat-archives.js +95 -0
  35. package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
  36. package/lib/archive/transfer/content-item-rank-sql.js +23 -0
  37. package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
  38. package/lib/archive/transfer/copy-analysis-violations.js +43 -0
  39. package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
  40. package/lib/archive/transfer/copy-anchor-edges.js +42 -0
  41. package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  42. package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
  43. package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
  44. package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
  45. package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
  46. package/lib/archive/transfer/copy-header-set-children.js +51 -0
  47. package/lib/archive/transfer/copy-image-items.d.ts +21 -0
  48. package/lib/archive/transfer/copy-image-items.js +62 -0
  49. package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
  50. package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
  51. package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
  52. package/lib/archive/transfer/copy-journal-tables.js +56 -0
  53. package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
  54. package/lib/archive/transfer/copy-page-console-logs.js +27 -0
  55. package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
  56. package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
  57. package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
  58. package/lib/archive/transfer/copy-page-meta.js +68 -0
  59. package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
  60. package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
  61. package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
  62. package/lib/archive/transfer/copy-page-template-labels.js +88 -0
  63. package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
  64. package/lib/archive/transfer/copy-resource-items.js +89 -0
  65. package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
  66. package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
  67. package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  68. package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
  69. package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
  70. package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
  71. package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
  72. package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
  73. package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
  74. package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
  75. package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
  76. package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
  77. package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
  78. package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
  79. package/lib/archive/transfer/insert-content-items.d.ts +35 -0
  80. package/lib/archive/transfer/insert-content-items.js +116 -0
  81. package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
  82. package/lib/archive/transfer/list-transfer-columns.js +45 -0
  83. package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
  84. package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
  85. package/lib/archive/transfer/merge-archive-configs.d.ts +51 -0
  86. package/lib/archive/transfer/merge-archive-configs.js +85 -0
  87. package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
  88. package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
  89. package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
  90. package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
  91. package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
  92. package/lib/archive/transfer/plan-resource-items.js +69 -0
  93. package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
  94. package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
  95. package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
  96. package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
  97. package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
  98. package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
  99. package/lib/archive/transfer/replace-content-items.d.ts +39 -0
  100. package/lib/archive/transfer/replace-content-items.js +83 -0
  101. package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
  102. package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
  103. package/lib/archive/transfer/split-archive.d.ts +55 -0
  104. package/lib/archive/transfer/split-archive.js +98 -0
  105. package/lib/archive/transfer/transfer-action.d.ts +34 -0
  106. package/lib/archive/transfer/transfer-action.js +32 -0
  107. package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
  108. package/lib/archive/transfer/transfer-archive-rows.js +158 -0
  109. package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
  110. package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
  111. package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
  112. package/lib/archive/transfer/transfer-source-alias.js +9 -0
  113. package/lib/archive/transfer/types.d.ts +111 -0
  114. package/lib/archive/transfer/types.js +35 -0
  115. package/lib/archive/types.d.ts +10 -0
  116. package/lib/concat-source-transfer-phases.d.ts +10 -0
  117. package/lib/concat-source-transfer-phases.js +17 -0
  118. package/lib/crawler/apply-request-header-interception.d.ts +22 -0
  119. package/lib/crawler/apply-request-header-interception.js +28 -0
  120. package/lib/crawler/build-scope-map.d.ts +21 -0
  121. package/lib/crawler/build-scope-map.js +32 -0
  122. package/lib/crawler/crawler.js +34 -0
  123. package/lib/crawler/create-scoped-header-request-handler.d.ts +40 -0
  124. package/lib/crawler/create-scoped-header-request-handler.js +64 -0
  125. package/lib/crawler/create-strip-headers-on-redirect.d.ts +41 -0
  126. package/lib/crawler/create-strip-headers-on-redirect.js +67 -0
  127. package/lib/crawler/fetch-destination.d.ts +14 -0
  128. package/lib/crawler/fetch-destination.js +56 -9
  129. package/lib/crawler/fetch-robots-txt.d.ts +7 -0
  130. package/lib/crawler/fetch-robots-txt.js +7 -0
  131. package/lib/crawler/scan-js-resource-for-license-comment.d.ts +6 -0
  132. package/lib/crawler/scan-js-resource-for-license-comment.js +6 -0
  133. package/lib/crawler/types.d.ts +44 -0
  134. package/lib/crawler-orchestrator.d.ts +6 -0
  135. package/lib/crawler-orchestrator.js +17 -17
  136. package/lib/crawler.d.ts +14 -1
  137. package/lib/crawler.js +23 -0
  138. package/lib/split-source-transfer-phases.d.ts +11 -0
  139. package/lib/split-source-transfer-phases.js +18 -0
  140. package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
  141. package/lib/template-classification/classify-archive-page-templates.js +79 -0
  142. package/lib/template-classification/classify-page-templates.d.ts +37 -0
  143. package/lib/template-classification/classify-page-templates.js +69 -0
  144. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  145. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  146. package/lib/template-classification/create-content-root-hint.d.ts +36 -0
  147. package/lib/template-classification/create-content-root-hint.js +47 -0
  148. package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
  149. package/lib/template-classification/create-page-cluster-factory.js +98 -0
  150. package/lib/template-classification/types.d.ts +108 -0
  151. package/lib/template-classification/types.js +1 -0
  152. package/lib/transfer-post-phases.d.ts +10 -0
  153. package/lib/transfer-post-phases.js +13 -0
  154. package/lib/utils/object/redact-request-headers.d.ts +15 -0
  155. package/lib/utils/object/redact-request-headers.js +27 -0
  156. package/package.json +4 -3
  157. package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
  158. /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
+ }
@@ -80,6 +80,16 @@ export interface Config extends Required<Pick<ParseURLOptions, 'disableQueries'>
80
80
  * detection, or `null`/omitted to use the automatic heuristic.
81
81
  */
82
82
  mainContentSelector?: string | null;
83
+ /**
84
+ * Names (never values) of the extra request headers the crawl was started
85
+ * with (`--header` / `--authorization` / `--header-file`). Header values
86
+ * are credentials and are deliberately NOT persisted — `.nitpicker` files
87
+ * are shared between users. The names exist only so a later
88
+ * `--resume` / `--append` / `--retry-failed` / `--recrawl` / `--inventory`
89
+ * run can warn that the operator did not re-supply them. Empty/omitted
90
+ * means no extra headers were used.
91
+ */
92
+ requestHeaderNames?: string[];
83
93
  /**
84
94
  * The `process.cwd()` recorded when this session's stub (tmpDir) was
85
95
  * created by `CrawlerOrchestrator.crawling` / `.append` / `.inventory` /
@@ -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,22 @@
1
+ import type { ApplyRequestHeaderInterceptionParams } from './types.js';
2
+ import type { Page } from 'puppeteer';
3
+ /**
4
+ * Turns on request interception for `page` and attaches the user-supplied
5
+ * extra headers to its in-scope requests — or does nothing at all when no
6
+ * headers were configured.
7
+ *
8
+ * The no-op for `undefined` / empty headers is the contract that keeps the
9
+ * default crawl path free of the per-request CDP round-trip interception adds
10
+ * (and of any change to caching behaviour), so it is pinned by a unit test.
11
+ * The caller also skips this for external pages: nothing of theirs is in
12
+ * scope, so interception would only slow them down.
13
+ * @param page - The Puppeteer page about to navigate.
14
+ * @param params - Headers, scope predicate and error sink.
15
+ * @returns Resolves once interception is configured (or immediately for a no-op).
16
+ * @example
17
+ * await applyRequestHeaderInterception(page, {
18
+ * requestHeaders: { Authorization: 'Bearer token' },
19
+ * isInScope: (href) => href.startsWith('https://example.com/'),
20
+ * });
21
+ */
22
+ export declare function applyRequestHeaderInterception(page: Pick<Page, 'on' | 'setRequestInterception'>, params: ApplyRequestHeaderInterceptionParams): Promise<void>;
@@ -0,0 +1,28 @@
1
+ import { createScopedHeaderRequestHandler } from './create-scoped-header-request-handler.js';
2
+ /**
3
+ * Turns on request interception for `page` and attaches the user-supplied
4
+ * extra headers to its in-scope requests — or does nothing at all when no
5
+ * headers were configured.
6
+ *
7
+ * The no-op for `undefined` / empty headers is the contract that keeps the
8
+ * default crawl path free of the per-request CDP round-trip interception adds
9
+ * (and of any change to caching behaviour), so it is pinned by a unit test.
10
+ * The caller also skips this for external pages: nothing of theirs is in
11
+ * scope, so interception would only slow them down.
12
+ * @param page - The Puppeteer page about to navigate.
13
+ * @param params - Headers, scope predicate and error sink.
14
+ * @returns Resolves once interception is configured (or immediately for a no-op).
15
+ * @example
16
+ * await applyRequestHeaderInterception(page, {
17
+ * requestHeaders: { Authorization: 'Bearer token' },
18
+ * isInScope: (href) => href.startsWith('https://example.com/'),
19
+ * });
20
+ */
21
+ export async function applyRequestHeaderInterception(page, params) {
22
+ const { requestHeaders, isInScope, onError } = params;
23
+ if (!requestHeaders || Object.keys(requestHeaders).length === 0) {
24
+ return;
25
+ }
26
+ await page.setRequestInterception(true);
27
+ page.on('request', createScopedHeaderRequestHandler({ requestHeaders, isInScope, onError }));
28
+ }
@@ -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
+ }