@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,74 @@
1
+ import knex from 'knex';
2
+ import { setConfig } from '../db-ops/config/set-config.js';
3
+ import { init } from '../db-ops/lifecycle/init.js';
4
+ import { LibsqlDialect } from '../libsql-dialect.js';
5
+ /**
6
+ * Default {@link Config} fields for {@link buildFullSchemaTestDb} — a
7
+ * single-root, recursive, non-list crawl of `https://example.com/`, no
8
+ * excludes. Overridable per-call for scope/`fromList`/`disableQueries`
9
+ * tests.
10
+ */
11
+ const DEFAULT_TEST_CONFIG = {
12
+ version: '0.13.0',
13
+ name: 'test',
14
+ baseUrl: 'https://example.com/',
15
+ roots: ['https://example.com/'],
16
+ recursive: true,
17
+ interval: 0,
18
+ image: false,
19
+ fetchExternal: false,
20
+ parallels: 1,
21
+ excludes: [],
22
+ excludeKeywords: [],
23
+ excludeUrls: [],
24
+ maxExcludedDepth: 0,
25
+ retry: 3,
26
+ fromList: false,
27
+ disableQueries: false,
28
+ userAgent: 'test',
29
+ ignoreRobots: false,
30
+ mainContentSelector: null,
31
+ };
32
+ /**
33
+ * Builds a file-backed knex connection against the FULL current archive
34
+ * schema (every ref/entity/adjunct table, including columns only a
35
+ * migration adds to a legacy archive — `alias_of_id`, `dedupe_cap_event_id`,
36
+ * `body_hash`, …) by running the exact same {@link init} boot sequence a
37
+ * real `Archive.create`/`Archive.open` uses. Shared by every
38
+ * `archive/transfer/` spec that needs a realistic source or destination
39
+ * database — hand-rolling `createRefTables`/`createEntityTables`/
40
+ * `createAdjunctTables` directly would produce the schema `initSchema`
41
+ * creates but skip the migrations that add columns for archives created
42
+ * before those features existed (which happen to be a no-op on a fresh
43
+ * DB today, but drift is exactly the risk this helper avoids).
44
+ *
45
+ * A DB file must be used (not `:memory:`) because `ATTACH DATABASE` in
46
+ * the transfer primitives needs a real path — see `attach-source-database.ts`.
47
+ * @param filename - Absolute path to the SQLite file. The caller is
48
+ * responsible for removing it (`afterEach`) — see existing specs for the
49
+ * convention.
50
+ * @param config - Overrides merged over {@link DEFAULT_TEST_CONFIG} and
51
+ * written via `setConfig` once the schema exists. Pass `null` to skip
52
+ * writing an `info` row entirely (some specs seed `content_items`
53
+ * directly and never read `getConfig()`).
54
+ * @returns The connected knex instance, on the current schema, with an
55
+ * `info` row unless `config` is `null`.
56
+ * @example
57
+ * ```ts
58
+ * const db = await buildFullSchemaTestDb(path.resolve(workingDir, 'source.sqlite'), {
59
+ * roots: ['https://a.example.com/'],
60
+ * });
61
+ * ```
62
+ */
63
+ export async function buildFullSchemaTestDb(filename, config = {}) {
64
+ const instance = knex({
65
+ client: LibsqlDialect,
66
+ connection: { filename },
67
+ useNullAsDefault: true,
68
+ });
69
+ await init(instance, false);
70
+ if (config !== null) {
71
+ await setConfig(instance, { ...DEFAULT_TEST_CONFIG, ...config });
72
+ }
73
+ return instance;
74
+ }
@@ -0,0 +1,31 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Attaches a source archive's `db.sqlite` file to the destination
4
+ * connection under the {@link TRANSFER_SOURCE_ALIAS} schema alias, so a
5
+ * transfer can read the source and write the destination in the same SQL
6
+ * statement (`INSERT INTO main.content_items SELECT ... FROM xfer_src.content_items`).
7
+ *
8
+ * `ATTACH DATABASE` must run OUTSIDE any transaction — SQLite rejects it
9
+ * with "cannot ATTACH database within transaction" otherwise — so this is
10
+ * always called before `knex.transaction(...)` opens, never inside it. The
11
+ * returned function detaches and must be called after the transaction
12
+ * commits or rolls back, in a `finally`.
13
+ * @param knex - Knex query builder connected to the destination archive DB
14
+ * (the connection whose schema this attaches to — not a transaction).
15
+ * @param sourceDbPath - Absolute path to the source's `db.sqlite` file
16
+ * (typically `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
17
+ * @returns An async function that detaches the source. Idempotent-safe to
18
+ * call even if the attach itself failed partway (best-effort).
19
+ * @throws {Error} If `ATTACH DATABASE` fails (e.g. the path does not exist,
20
+ * or a transaction is already open on this connection).
21
+ * @example
22
+ * ```ts
23
+ * const detach = await attachSourceDatabase(knex, sourceDbPath);
24
+ * try {
25
+ * await knex.transaction(async (trx) => { ... trx.raw('SELECT * FROM xfer_src.content_items') ... });
26
+ * } finally {
27
+ * await detach();
28
+ * }
29
+ * ```
30
+ */
31
+ export declare function attachSourceDatabase(knex: Knex, sourceDbPath: string): Promise<() => Promise<void>>;
@@ -0,0 +1,40 @@
1
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
2
+ /**
3
+ * Attaches a source archive's `db.sqlite` file to the destination
4
+ * connection under the {@link TRANSFER_SOURCE_ALIAS} schema alias, so a
5
+ * transfer can read the source and write the destination in the same SQL
6
+ * statement (`INSERT INTO main.content_items SELECT ... FROM xfer_src.content_items`).
7
+ *
8
+ * `ATTACH DATABASE` must run OUTSIDE any transaction — SQLite rejects it
9
+ * with "cannot ATTACH database within transaction" otherwise — so this is
10
+ * always called before `knex.transaction(...)` opens, never inside it. The
11
+ * returned function detaches and must be called after the transaction
12
+ * commits or rolls back, in a `finally`.
13
+ * @param knex - Knex query builder connected to the destination archive DB
14
+ * (the connection whose schema this attaches to — not a transaction).
15
+ * @param sourceDbPath - Absolute path to the source's `db.sqlite` file
16
+ * (typically `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
17
+ * @returns An async function that detaches the source. Idempotent-safe to
18
+ * call even if the attach itself failed partway (best-effort).
19
+ * @throws {Error} If `ATTACH DATABASE` fails (e.g. the path does not exist,
20
+ * or a transaction is already open on this connection).
21
+ * @example
22
+ * ```ts
23
+ * const detach = await attachSourceDatabase(knex, sourceDbPath);
24
+ * try {
25
+ * await knex.transaction(async (trx) => { ... trx.raw('SELECT * FROM xfer_src.content_items') ... });
26
+ * } finally {
27
+ * await detach();
28
+ * }
29
+ * ```
30
+ */
31
+ export async function attachSourceDatabase(knex, sourceDbPath) {
32
+ await knex.raw('ATTACH DATABASE ? AS ' + TRANSFER_SOURCE_ALIAS, [sourceDbPath]);
33
+ const attached = await knex.raw('PRAGMA database_list');
34
+ if (!attached.some((row) => row.name === TRANSFER_SOURCE_ALIAS)) {
35
+ throw new Error(`Failed to attach source database at ${sourceDbPath} — PRAGMA database_list does not list "${TRANSFER_SOURCE_ALIAS}" after ATTACH.`);
36
+ }
37
+ return async () => {
38
+ await knex.raw('DETACH DATABASE ' + TRANSFER_SOURCE_ALIAS).catch(() => { });
39
+ };
40
+ }
@@ -0,0 +1,30 @@
1
+ import type { Config } from '../types.js';
2
+ /**
3
+ * Derives the output {@link Config} for a `split`, from the source's own
4
+ * config plus the scope URLs the operator gave on the command line.
5
+ *
6
+ * `roots` becomes exactly the given URLs (their `withoutHash` form,
7
+ * matching how `crawl`'s own roots are recorded); `baseUrl` is the first
8
+ * one. Every other scalar field is carried over verbatim from the
9
+ * source — a split narrows WHICH pages are kept, it does not change HOW
10
+ * they were crawled (`recursive`/`interval`/`userAgent`/etc. all still
11
+ * describe the original session honestly). `excludes`/`excludeKeywords`/
12
+ * `excludeUrls` are likewise carried over unchanged (they described the
13
+ * source's own crawl-time exclusions, still true of the subset that
14
+ * survives). `version` is pinned to {@link REQUIRED_FORMAT_VERSION} and
15
+ * `createdCwd` is always `null`, matching `mergeArchiveConfigs`'s same
16
+ * two fields for the same reasons.
17
+ *
18
+ * Callers must reject a `fromList` source BEFORE calling this — `roots`
19
+ * for such an archive is a URL LIST, not a scope, so "roots = the given
20
+ * scope URLs" has no coherent meaning for it (see `docs/split.md`).
21
+ * @param source - The source archive's `getConfig()` result.
22
+ * @param scopeUrls - The scope URLs the operator gave (`withoutHash` form).
23
+ * @param name - The output archive's `name` (typically its basename).
24
+ * @returns The derived {@link Config} to write via `Archive#setConfig`.
25
+ * @example
26
+ * ```ts
27
+ * const config = buildSplitConfig(await source.getConfig(), ['https://example.com/blog/'], 'blog');
28
+ * ```
29
+ */
30
+ export declare function buildSplitConfig(source: Config, scopeUrls: readonly string[], name: string): Config;
@@ -0,0 +1,42 @@
1
+ import { REQUIRED_FORMAT_VERSION } from '../meta/assert-compatible-version.js';
2
+ /**
3
+ * Derives the output {@link Config} for a `split`, from the source's own
4
+ * config plus the scope URLs the operator gave on the command line.
5
+ *
6
+ * `roots` becomes exactly the given URLs (their `withoutHash` form,
7
+ * matching how `crawl`'s own roots are recorded); `baseUrl` is the first
8
+ * one. Every other scalar field is carried over verbatim from the
9
+ * source — a split narrows WHICH pages are kept, it does not change HOW
10
+ * they were crawled (`recursive`/`interval`/`userAgent`/etc. all still
11
+ * describe the original session honestly). `excludes`/`excludeKeywords`/
12
+ * `excludeUrls` are likewise carried over unchanged (they described the
13
+ * source's own crawl-time exclusions, still true of the subset that
14
+ * survives). `version` is pinned to {@link REQUIRED_FORMAT_VERSION} and
15
+ * `createdCwd` is always `null`, matching `mergeArchiveConfigs`'s same
16
+ * two fields for the same reasons.
17
+ *
18
+ * Callers must reject a `fromList` source BEFORE calling this — `roots`
19
+ * for such an archive is a URL LIST, not a scope, so "roots = the given
20
+ * scope URLs" has no coherent meaning for it (see `docs/split.md`).
21
+ * @param source - The source archive's `getConfig()` result.
22
+ * @param scopeUrls - The scope URLs the operator gave (`withoutHash` form).
23
+ * @param name - The output archive's `name` (typically its basename).
24
+ * @returns The derived {@link Config} to write via `Archive#setConfig`.
25
+ * @example
26
+ * ```ts
27
+ * const config = buildSplitConfig(await source.getConfig(), ['https://example.com/blog/'], 'blog');
28
+ * ```
29
+ */
30
+ export function buildSplitConfig(source, scopeUrls, name) {
31
+ if (scopeUrls.length === 0) {
32
+ throw new Error('buildSplitConfig: at least one scope URL is required');
33
+ }
34
+ return {
35
+ ...source,
36
+ version: REQUIRED_FORMAT_VERSION,
37
+ name,
38
+ roots: [...scopeUrls],
39
+ baseUrl: scopeUrls[0],
40
+ createdCwd: null,
41
+ };
42
+ }
@@ -0,0 +1,20 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Deletes every page-scoped derived row for a concat source's `replace`-
4
+ * action destination ids (`temp.xfer_ci_plan.dest_id`), across all 21
5
+ * tables in {@link REMAPPED_PAGE_ROW_TABLES} + {@link SIMPLE_PAGE_SCOPED_TABLES}
6
+ * combined — set-based (`WHERE ... IN (subquery)`), so there is no
7
+ * `SQLITE_LIMIT_VARIABLE_NUMBER` bind-count concern regardless of how many
8
+ * rows are being replaced.
9
+ *
10
+ * Must run BEFORE the page-scoped table copies
11
+ * (`copy-page-meta.ts` et al.) so their `INSERT`s never collide with
12
+ * stale rows left over from the losing destination row's own prior data.
13
+ * @param trx - Transaction with the source ATTACHed.
14
+ * @example
15
+ * ```ts
16
+ * await clearReplacedPageRows(trx);
17
+ * await replaceContentItems(trx, { crawlOrderOffset: 0 });
18
+ * ```
19
+ */
20
+ export declare function clearReplacedPageRows(trx: Knex): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import { SIMPLE_PAGE_SCOPED_TABLES } from './simple-page-scoped-tables.js';
2
+ import { TRANSFER_ACTION } from './transfer-action.js';
3
+ /**
4
+ * The page-scoped tables NOT covered by {@link SIMPLE_PAGE_SCOPED_TABLES}
5
+ * (which this file also clears — see below) — each of these has its own
6
+ * dedicated FK-remapping copy function (`copy-page-meta.ts`,
7
+ * `copy-anchor-edges.ts`, `copy-image-items.ts`,
8
+ * `copy-resource-ref-edges.ts`, `copy-page-console-logs.ts`,
9
+ * `copy-analysis-violations.ts`), so they are listed explicitly rather
10
+ * than folded into the shared "plain passthrough" table. Together the two
11
+ * lists are a superset of `clearPageDerivedRows`' 17 tables (reused by
12
+ * `resetFailedPages`/`repromoteExternalPages` for the same
13
+ * un-scrape-then-re-insert shape) — this combined 21 additionally covers
14
+ * `page_console_logs`/`page_templates`/`analysis_violations`/`page_errors`,
15
+ * which that shared helper deliberately omits (see its own JSDoc for why:
16
+ * `repromoteExternalPages` never needed them cleared, and folding them in
17
+ * would have silently changed its existing behaviour). Concat's replace
18
+ * path needs all 21 — a `replace` is a full Scoped-Replace of every
19
+ * page-scoped table, not a partial one.
20
+ */
21
+ const REMAPPED_PAGE_ROW_TABLES = [
22
+ { table: 'page_meta', pageColumn: 'page_id' },
23
+ { table: 'anchor_edges', pageColumn: 'page_id' },
24
+ { table: 'image_items', pageColumn: 'page_id' },
25
+ { table: 'resource_ref_edges', pageColumn: 'page_id' },
26
+ { table: 'page_console_logs', pageColumn: 'pageId' },
27
+ { table: 'analysis_violations', pageColumn: 'page_id' },
28
+ ];
29
+ /**
30
+ * Deletes every page-scoped derived row for a concat source's `replace`-
31
+ * action destination ids (`temp.xfer_ci_plan.dest_id`), across all 21
32
+ * tables in {@link REMAPPED_PAGE_ROW_TABLES} + {@link SIMPLE_PAGE_SCOPED_TABLES}
33
+ * combined — set-based (`WHERE ... IN (subquery)`), so there is no
34
+ * `SQLITE_LIMIT_VARIABLE_NUMBER` bind-count concern regardless of how many
35
+ * rows are being replaced.
36
+ *
37
+ * Must run BEFORE the page-scoped table copies
38
+ * (`copy-page-meta.ts` et al.) so their `INSERT`s never collide with
39
+ * stale rows left over from the losing destination row's own prior data.
40
+ * @param trx - Transaction with the source ATTACHed.
41
+ * @example
42
+ * ```ts
43
+ * await clearReplacedPageRows(trx);
44
+ * await replaceContentItems(trx, { crawlOrderOffset: 0 });
45
+ * ```
46
+ */
47
+ export async function clearReplacedPageRows(trx) {
48
+ const tables = [...REMAPPED_PAGE_ROW_TABLES, ...SIMPLE_PAGE_SCOPED_TABLES];
49
+ for (const { table, pageColumn } of tables) {
50
+ await trx.raw(`
51
+ DELETE FROM main.${table}
52
+ WHERE ${pageColumn} IN (
53
+ SELECT dest_id FROM xfer_ci_plan WHERE action = ${TRANSFER_ACTION.replace}
54
+ )
55
+ `);
56
+ }
57
+ }
@@ -0,0 +1,55 @@
1
+ import type { ArchiveAccessor } from '../archive-accessor.js';
2
+ import type Archive from '../archive.js';
3
+ import type { ConcatArchivesResult, TransferCallbacks } from './types.js';
4
+ /**
5
+ * Merges two or more read-only-opened source archives into an already
6
+ * `Archive.create`d, empty destination — the crawler-side half of the
7
+ * `concat` CLI command. Does not open/close/write anything itself: the
8
+ * caller owns every accessor's and the destination's lifecycle (see
9
+ * `docs/concat.md` and the CLI's `commands/concat.ts`, which owns the
10
+ * full open → transfer → rebuild-read-model → write sequence this is one
11
+ * step of).
12
+ *
13
+ * Sources are transferred ONE AT A TIME, in argument order, each one's
14
+ * `crawlOrderOffset` set to the destination's current
15
+ * `MAX(content_items.crawl_order)` so a later source's pages always sort
16
+ * after an earlier one's — this is what makes "ties go to the later
17
+ * argument" (see `plan-content-items-for-concat.ts`) match the pages'
18
+ * OWN display order too, not just their win/lose outcome.
19
+ *
20
+ * After every source is transferred: `flattenRedirectChains` (a merge can
21
+ * reintroduce a two-hop redirect chain no single source ever has),
22
+ * `reclassifyResourceExternality` against the MERGED scope, and
23
+ * `countExternalPagesInScope` for the CLI's `--append` hint (concat never
24
+ * promotes such pages itself — see `types.ts`'s
25
+ * `ConcatArchivesResult.externalInScopeCount` docs).
26
+ * @param options - See individual properties.
27
+ * @param options.sources - Every source, read-only opened
28
+ * (`Archive.openCached`), in argument order.
29
+ * @param options.destination - The empty destination, already
30
+ * `Archive.create`d by the caller.
31
+ * @param options.name - The output archive's `name` config field
32
+ * (typically its basename without extension).
33
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
34
+ * @returns The merged config, each source's transfer outcome, and the
35
+ * two summary counts.
36
+ * @throws {import('./types.js').ArchiveConfigConflictError} If sources
37
+ * disagree on `disableQueries`/`fromList` — see `mergeArchiveConfigs`.
38
+ * @example
39
+ * ```ts
40
+ * const destination = await Archive.create({ filePath: outputPath, cwd });
41
+ * const sources = await Promise.all(
42
+ * inputPaths.map(async (p) => ({ path: p, accessor: await Archive.openCached(p) })),
43
+ * );
44
+ * const result = await concatArchives({ sources, destination, name: 'merged' });
45
+ * ```
46
+ */
47
+ export declare function concatArchives(options: {
48
+ readonly sources: readonly {
49
+ readonly accessor: ArchiveAccessor;
50
+ readonly path: string;
51
+ }[];
52
+ readonly destination: Archive;
53
+ readonly name: string;
54
+ readonly callbacks?: TransferCallbacks;
55
+ }): Promise<ConcatArchivesResult>;
@@ -0,0 +1,95 @@
1
+ import path from 'node:path';
2
+ import { buildScopeMap } from '../../crawler/build-scope-map.js';
3
+ import ArchiveDefault from '../archive.js';
4
+ import { copyInventorySourceLists } from './copy-inventory-source-lists.js';
5
+ import { countExternalPagesInScope } from './count-external-pages-in-scope.js';
6
+ import { flattenRedirectChains } from './flatten-redirect-chains.js';
7
+ import { mergeArchiveConfigs } from './merge-archive-configs.js';
8
+ import { reclassifyResourceExternality } from './reclassify-resource-externality.js';
9
+ import { transferArchiveRows } from './transfer-archive-rows.js';
10
+ /**
11
+ * Merges two or more read-only-opened source archives into an already
12
+ * `Archive.create`d, empty destination — the crawler-side half of the
13
+ * `concat` CLI command. Does not open/close/write anything itself: the
14
+ * caller owns every accessor's and the destination's lifecycle (see
15
+ * `docs/concat.md` and the CLI's `commands/concat.ts`, which owns the
16
+ * full open → transfer → rebuild-read-model → write sequence this is one
17
+ * step of).
18
+ *
19
+ * Sources are transferred ONE AT A TIME, in argument order, each one's
20
+ * `crawlOrderOffset` set to the destination's current
21
+ * `MAX(content_items.crawl_order)` so a later source's pages always sort
22
+ * after an earlier one's — this is what makes "ties go to the later
23
+ * argument" (see `plan-content-items-for-concat.ts`) match the pages'
24
+ * OWN display order too, not just their win/lose outcome.
25
+ *
26
+ * After every source is transferred: `flattenRedirectChains` (a merge can
27
+ * reintroduce a two-hop redirect chain no single source ever has),
28
+ * `reclassifyResourceExternality` against the MERGED scope, and
29
+ * `countExternalPagesInScope` for the CLI's `--append` hint (concat never
30
+ * promotes such pages itself — see `types.ts`'s
31
+ * `ConcatArchivesResult.externalInScopeCount` docs).
32
+ * @param options - See individual properties.
33
+ * @param options.sources - Every source, read-only opened
34
+ * (`Archive.openCached`), in argument order.
35
+ * @param options.destination - The empty destination, already
36
+ * `Archive.create`d by the caller.
37
+ * @param options.name - The output archive's `name` config field
38
+ * (typically its basename without extension).
39
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
40
+ * @returns The merged config, each source's transfer outcome, and the
41
+ * two summary counts.
42
+ * @throws {import('./types.js').ArchiveConfigConflictError} If sources
43
+ * disagree on `disableQueries`/`fromList` — see `mergeArchiveConfigs`.
44
+ * @example
45
+ * ```ts
46
+ * const destination = await Archive.create({ filePath: outputPath, cwd });
47
+ * const sources = await Promise.all(
48
+ * inputPaths.map(async (p) => ({ path: p, accessor: await Archive.openCached(p) })),
49
+ * );
50
+ * const result = await concatArchives({ sources, destination, name: 'merged' });
51
+ * ```
52
+ */
53
+ export async function concatArchives(options) {
54
+ const { sources, destination, name, callbacks } = options;
55
+ if (sources.length < 2) {
56
+ throw new Error('concatArchives: at least two sources are required');
57
+ }
58
+ const configs = await Promise.all(sources.map((s) => s.accessor.getConfig()));
59
+ const merged = mergeArchiveConfigs(configs, name);
60
+ await destination.setConfig(merged);
61
+ const knex = destination.getKnex();
62
+ const scope = buildScopeMap(merged.roots, merged);
63
+ const results = [];
64
+ for (const [index, source] of sources.entries()) {
65
+ callbacks?.onSourceStart?.(index, source.path);
66
+ const sourceDbPath = path.join(source.accessor.tmpDir, ArchiveDefault.SQLITE_DB_FILE_NAME);
67
+ const maxRows = await knex('content_items').max({
68
+ max: 'crawl_order',
69
+ });
70
+ const crawlOrderOffset = maxRows[0]?.max ?? 0;
71
+ const result = await transferArchiveRows({
72
+ knex,
73
+ sourceDbPath,
74
+ mode: { kind: 'concat' },
75
+ crawlOrderOffset,
76
+ sourceIndex: index,
77
+ callbacks,
78
+ });
79
+ results.push(result);
80
+ }
81
+ const postIndex = sources.length;
82
+ callbacks?.onPhase?.(postIndex, 'flatteningRedirects');
83
+ await flattenRedirectChains(knex);
84
+ callbacks?.onPhase?.(postIndex, 'reclassifyingResources');
85
+ await reclassifyResourceExternality(knex, scope, merged);
86
+ callbacks?.onPhase?.(postIndex, 'countingExternalInScope');
87
+ const externalInScopeCount = await countExternalPagesInScope(knex, scope, merged);
88
+ const inventoryListsCopied = await copyInventorySourceLists(destination, sources.map((s) => s.accessor.tmpDir));
89
+ return {
90
+ config: merged,
91
+ sources: results,
92
+ externalInScopeCount,
93
+ inventoryListsCopied,
94
+ };
95
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * SQL fragment computing a `content_items` row's "richness" rank for
3
+ * concat's same-URL conflict resolution: `2` (scraped internal page) beats
4
+ * `1` (scraped external HEAD-only observation) beats `0` (never scraped).
5
+ * Concat keeps whichever source's row ranks highest for a given URL; a tie
6
+ * is resolved by processing sources in argument order and overwriting on
7
+ * `>=` (see {@link import('./plan-content-items-for-concat.js').planContentItemsForConcat}),
8
+ * so the LAST source with an equal-or-better rank wins.
9
+ *
10
+ * This is the single definition of the ranking lattice — every other
11
+ * ranking (or a change to it) must go through this function so concat's
12
+ * conflict resolution cannot silently drift from what this doc describes.
13
+ * @param alias - The table alias (or bare table name) the fragment reads
14
+ * `scraped`/`is_external` from, e.g. `'s'` for `xfer_src.content_items s`.
15
+ * @returns A SQL expression (no trailing semicolon) evaluating to `0`, `1`, or `2`.
16
+ * @example
17
+ * ```ts
18
+ * trx.raw(`SELECT ${contentItemRankSql('s')} as rank FROM xfer_src.content_items s`);
19
+ * ```
20
+ */
21
+ export declare function contentItemRankSql(alias: string): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * SQL fragment computing a `content_items` row's "richness" rank for
3
+ * concat's same-URL conflict resolution: `2` (scraped internal page) beats
4
+ * `1` (scraped external HEAD-only observation) beats `0` (never scraped).
5
+ * Concat keeps whichever source's row ranks highest for a given URL; a tie
6
+ * is resolved by processing sources in argument order and overwriting on
7
+ * `>=` (see {@link import('./plan-content-items-for-concat.js').planContentItemsForConcat}),
8
+ * so the LAST source with an equal-or-better rank wins.
9
+ *
10
+ * This is the single definition of the ranking lattice — every other
11
+ * ranking (or a change to it) must go through this function so concat's
12
+ * conflict resolution cannot silently drift from what this doc describes.
13
+ * @param alias - The table alias (or bare table name) the fragment reads
14
+ * `scraped`/`is_external` from, e.g. `'s'` for `xfer_src.content_items s`.
15
+ * @returns A SQL expression (no trailing semicolon) evaluating to `0`, `1`, or `2`.
16
+ * @example
17
+ * ```ts
18
+ * trx.raw(`SELECT ${contentItemRankSql('s')} as rank FROM xfer_src.content_items s`);
19
+ * ```
20
+ */
21
+ export function contentItemRankSql(alias) {
22
+ return `(CASE WHEN ${alias}.scraped = 1 THEN 2 - ${alias}.is_external ELSE 0 END)`;
23
+ }
@@ -0,0 +1,19 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Copies `analysis_violations` for every `full`/`replace`-action page,
4
+ * remapping `message_text_id` (required) and `code_text_id` (nullable)
5
+ * through `temp.xfer_map_analysis_text_refs`. Every other column
6
+ * (`validator`/`severity`/`rule`/the three `*_sort_key` strings/`line`/
7
+ * `col`) passes through unchanged — none of them reference another
8
+ * dictionary or entity.
9
+ * @param trx - Transaction with the source ATTACHed as
10
+ * {@link TRANSFER_SOURCE_ALIAS}. Must run after
11
+ * `copyDictionariesForConcat`/`copyDictionariesForSplit` has populated
12
+ * `temp.xfer_map_analysis_text_refs`.
13
+ * @example
14
+ * ```ts
15
+ * await copyPageMeta(trx);
16
+ * await copyAnalysisViolations(trx);
17
+ * ```
18
+ */
19
+ export declare function copyAnalysisViolations(trx: Knex): Promise<void>;
@@ -0,0 +1,43 @@
1
+ import { listTransferColumns } from './list-transfer-columns.js';
2
+ import { quoteTransferIdentifier } from './quote-transfer-identifier.js';
3
+ import { TRANSFER_ACTION } from './transfer-action.js';
4
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
5
+ const SRC = TRANSFER_SOURCE_ALIAS;
6
+ /**
7
+ * Copies `analysis_violations` for every `full`/`replace`-action page,
8
+ * remapping `message_text_id` (required) and `code_text_id` (nullable)
9
+ * through `temp.xfer_map_analysis_text_refs`. Every other column
10
+ * (`validator`/`severity`/`rule`/the three `*_sort_key` strings/`line`/
11
+ * `col`) passes through unchanged — none of them reference another
12
+ * dictionary or entity.
13
+ * @param trx - Transaction with the source ATTACHed as
14
+ * {@link TRANSFER_SOURCE_ALIAS}. Must run after
15
+ * `copyDictionariesForConcat`/`copyDictionariesForSplit` has populated
16
+ * `temp.xfer_map_analysis_text_refs`.
17
+ * @example
18
+ * ```ts
19
+ * await copyPageMeta(trx);
20
+ * await copyAnalysisViolations(trx);
21
+ * ```
22
+ */
23
+ export async function copyAnalysisViolations(trx) {
24
+ const columns = await listTransferColumns(trx, SRC, 'analysis_violations', [
25
+ 'id',
26
+ 'page_id',
27
+ 'message_text_id',
28
+ 'code_text_id',
29
+ ]);
30
+ const passthrough = columns
31
+ .map((col) => `s.${quoteTransferIdentifier(col)}`)
32
+ .join(', ');
33
+ await trx.raw(`
34
+ INSERT INTO main.analysis_violations
35
+ (page_id, message_text_id, code_text_id, ${columns.map(quoteTransferIdentifier).join(', ')})
36
+ SELECT p.dest_id, mm.dest_id, mc.dest_id, ${passthrough}
37
+ FROM ${SRC}.analysis_violations s
38
+ JOIN xfer_ci_plan p ON p.src_id = s.page_id
39
+ AND p.action IN (${TRANSFER_ACTION.full}, ${TRANSFER_ACTION.replace})
40
+ JOIN xfer_map_analysis_text_refs mm ON mm.src_id = s.message_text_id
41
+ LEFT JOIN xfer_map_analysis_text_refs mc ON mc.src_id = s.code_text_id
42
+ `);
43
+ }
@@ -0,0 +1,28 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Copies `anchor_edges` for every `full`/`replace`-action page's OUTBOUND
4
+ * links, remapping both `page_id` (the link's own page — must be
5
+ * `full`/`replace`, same rule as every other page-scoped table) and
6
+ * `href_page_id` (the link's target — resolved through
7
+ * `temp.xfer_ci_plan` directly, via an INNER JOIN, NOT `LEFT JOIN`):
8
+ *
9
+ * - Concat: every source row has a plan entry (even `skip`), so the
10
+ * INNER JOIN always matches — an anchor to a `skip`ped URL still
11
+ * resolves to whichever destination row won that URL.
12
+ * - Split: a target NOT in the plan means "dropped" (out of scope and
13
+ * unreferenced by anything else) — the INNER JOIN drops that anchor
14
+ * row entirely rather than inserting a dangling `href_page_id`. This is
15
+ * intentional: `plan-content-items-for-split.ts`'s own closure already
16
+ * guarantees every anchor target of a KEPT page is itself kept (as
17
+ * `full` or `stub`), so in practice this INNER JOIN never actually
18
+ * filters anything out for split — it exists as a structural safety net,
19
+ * not as an active filter.
20
+ * @param trx - Transaction with the source ATTACHed as
21
+ * {@link TRANSFER_SOURCE_ALIAS}.
22
+ * @example
23
+ * ```ts
24
+ * await copyPageMeta(trx);
25
+ * await copyAnchorEdges(trx);
26
+ * ```
27
+ */
28
+ export declare function copyAnchorEdges(trx: Knex): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { TRANSFER_ACTION } from './transfer-action.js';
2
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
3
+ const SRC = TRANSFER_SOURCE_ALIAS;
4
+ /**
5
+ * Copies `anchor_edges` for every `full`/`replace`-action page's OUTBOUND
6
+ * links, remapping both `page_id` (the link's own page — must be
7
+ * `full`/`replace`, same rule as every other page-scoped table) and
8
+ * `href_page_id` (the link's target — resolved through
9
+ * `temp.xfer_ci_plan` directly, via an INNER JOIN, NOT `LEFT JOIN`):
10
+ *
11
+ * - Concat: every source row has a plan entry (even `skip`), so the
12
+ * INNER JOIN always matches — an anchor to a `skip`ped URL still
13
+ * resolves to whichever destination row won that URL.
14
+ * - Split: a target NOT in the plan means "dropped" (out of scope and
15
+ * unreferenced by anything else) — the INNER JOIN drops that anchor
16
+ * row entirely rather than inserting a dangling `href_page_id`. This is
17
+ * intentional: `plan-content-items-for-split.ts`'s own closure already
18
+ * guarantees every anchor target of a KEPT page is itself kept (as
19
+ * `full` or `stub`), so in practice this INNER JOIN never actually
20
+ * filters anything out for split — it exists as a structural safety net,
21
+ * not as an active filter.
22
+ * @param trx - Transaction with the source ATTACHed as
23
+ * {@link TRANSFER_SOURCE_ALIAS}.
24
+ * @example
25
+ * ```ts
26
+ * await copyPageMeta(trx);
27
+ * await copyAnchorEdges(trx);
28
+ * ```
29
+ */
30
+ export async function copyAnchorEdges(trx) {
31
+ await trx.raw(`
32
+ INSERT INTO main.anchor_edges (page_id, href_page_id, count, first_hash, first_text_id)
33
+ SELECT p.dest_id, pd.dest_id, ae.count, ae.first_hash, mt.dest_id
34
+ FROM ${SRC}.anchor_edges ae
35
+ JOIN xfer_ci_plan p ON p.src_id = ae.page_id
36
+ AND p.action IN (${TRANSFER_ACTION.full}, ${TRANSFER_ACTION.replace})
37
+ JOIN xfer_ci_plan pd ON pd.src_id = ae.href_page_id
38
+ LEFT JOIN xfer_map_text_refs mt ON mt.src_id = ae.first_text_id
39
+ WHERE true
40
+ ON CONFLICT(page_id, href_page_id) DO NOTHING
41
+ `);
42
+ }