@nitpicker/crawler 0.14.0 → 0.15.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 (120) hide show
  1. package/lib/archive/archive.d.ts +98 -10
  2. package/lib/archive/archive.js +98 -9
  3. package/lib/archive/body-hash/compute-body-hash.d.ts +22 -0
  4. package/lib/archive/body-hash/compute-body-hash.js +31 -0
  5. package/lib/archive/body-hash/extract-body.d.ts +18 -0
  6. package/lib/archive/body-hash/extract-body.js +29 -0
  7. package/lib/archive/body-hash/mask-dynamic-ids.d.ts +33 -0
  8. package/lib/archive/body-hash/mask-dynamic-ids.js +44 -0
  9. package/lib/archive/body-hash/normalize-url-like-strings.d.ts +16 -0
  10. package/lib/archive/body-hash/normalize-url-like-strings.js +19 -0
  11. package/lib/archive/cache/clear-archive-cache-entry.d.ts +19 -0
  12. package/lib/archive/cache/clear-archive-cache-entry.js +25 -0
  13. package/lib/archive/cache/clear-archive-cache-root.d.ts +26 -0
  14. package/lib/archive/cache/clear-archive-cache-root.js +32 -0
  15. package/lib/archive/cache/list-archive-cache-entries.d.ts +23 -0
  16. package/lib/archive/cache/list-archive-cache-entries.js +125 -0
  17. package/lib/archive/cache/path-exists.d.ts +9 -0
  18. package/lib/archive/cache/path-exists.js +18 -0
  19. package/lib/archive/cache/types.d.ts +33 -0
  20. package/lib/archive/cache/types.js +1 -0
  21. package/lib/archive/create-adjunct-tables.d.ts +11 -0
  22. package/lib/archive/create-adjunct-tables.js +127 -0
  23. package/lib/archive/create-entity-tables.js +21 -1
  24. package/lib/archive/database.d.ts +37 -2
  25. package/lib/archive/database.js +50 -3
  26. package/lib/archive/db-ops/_shared/clear-write-ref-caches.js +1 -0
  27. package/lib/archive/db-ops/_shared/compress-payload.d.ts +26 -0
  28. package/lib/archive/db-ops/_shared/compress-payload.js +30 -0
  29. package/lib/archive/db-ops/_shared/create-write-ref-caches.js +1 -0
  30. package/lib/archive/db-ops/_shared/types.d.ts +2 -0
  31. package/lib/archive/db-ops/_shared/upsert-json-ref.js +3 -3
  32. package/lib/archive/db-ops/analysis/replace-page-templates.d.ts +12 -3
  33. package/lib/archive/db-ops/analysis/replace-page-templates.js +35 -3
  34. package/lib/archive/db-ops/analysis/types.d.ts +61 -0
  35. package/lib/archive/db-ops/analysis/types.js +1 -0
  36. package/lib/archive/db-ops/console-logs/compute-console-log-hash.d.ts +19 -0
  37. package/lib/archive/db-ops/console-logs/compute-console-log-hash.js +30 -0
  38. package/lib/archive/db-ops/console-logs/replace-console-logs.d.ts +34 -0
  39. package/lib/archive/db-ops/console-logs/replace-console-logs.js +123 -0
  40. package/lib/archive/db-ops/console-logs/stringify-console-log-args.d.ts +16 -0
  41. package/lib/archive/db-ops/console-logs/stringify-console-log-args.js +26 -0
  42. package/lib/archive/db-ops/console-logs/types.d.ts +38 -0
  43. package/lib/archive/db-ops/console-logs/types.js +1 -0
  44. package/lib/archive/db-ops/console-logs/upsert-console-log-item.d.ts +29 -0
  45. package/lib/archive/db-ops/console-logs/upsert-console-log-item.js +52 -0
  46. package/lib/archive/db-ops/errors/list-dns-burned-host-candidates.d.ts +11 -0
  47. package/lib/archive/db-ops/errors/list-dns-burned-host-candidates.js +21 -4
  48. package/lib/archive/db-ops/inventory/record-inventory-run.js +1 -0
  49. package/lib/archive/db-ops/lifecycle/init.d.ts +11 -2
  50. package/lib/archive/db-ops/lifecycle/init.js +21 -2
  51. package/lib/archive/db-ops/outages/close-network-outage.d.ts +12 -0
  52. package/lib/archive/db-ops/outages/close-network-outage.js +15 -0
  53. package/lib/archive/db-ops/outages/close-stale-open-network-outages.d.ts +26 -0
  54. package/lib/archive/db-ops/outages/close-stale-open-network-outages.js +42 -0
  55. package/lib/archive/db-ops/outages/compute-outage-clamp-timestamp.d.ts +26 -0
  56. package/lib/archive/db-ops/outages/compute-outage-clamp-timestamp.js +31 -0
  57. package/lib/archive/db-ops/outages/insert-network-outage.d.ts +14 -0
  58. package/lib/archive/db-ops/outages/insert-network-outage.js +29 -0
  59. package/lib/archive/db-ops/outages/list-network-outages.d.ts +28 -0
  60. package/lib/archive/db-ops/outages/list-network-outages.js +42 -0
  61. package/lib/archive/db-ops/pages/reset/reset-failed-pages.d.ts +13 -0
  62. package/lib/archive/db-ops/pages/reset/reset-failed-pages.js +35 -7
  63. package/lib/archive/db-ops/pages/write/update-page.js +12 -0
  64. package/lib/archive/db-ops/pages/write/write-page-html-blob.js +6 -6
  65. package/lib/archive/filesystem/output-binary.d.ts +12 -0
  66. package/lib/archive/filesystem/output-binary.js +17 -0
  67. package/lib/archive/get-failed-page-messages.d.ts +20 -8
  68. package/lib/archive/get-failed-page-messages.js +29 -15
  69. package/lib/archive/migrate-content-items-alias-of-id.d.ts +47 -0
  70. package/lib/archive/migrate-content-items-alias-of-id.js +58 -0
  71. package/lib/archive/migrate-inventory-runs-invalid-skipped.d.ts +11 -0
  72. package/lib/archive/migrate-inventory-runs-invalid-skipped.js +24 -0
  73. package/lib/archive/migrate-page-meta-body-hash.d.ts +39 -0
  74. package/lib/archive/migrate-page-meta-body-hash.js +52 -0
  75. package/lib/archive/migrate-page-meta-console-error-count.d.ts +22 -0
  76. package/lib/archive/migrate-page-meta-console-error-count.js +34 -0
  77. package/lib/archive/page.d.ts +1 -1
  78. package/lib/archive/types.d.ts +47 -2
  79. package/lib/archive/url-alias/compute-tier-a-alias-key.d.ts +31 -0
  80. package/lib/archive/url-alias/compute-tier-a-alias-key.js +36 -0
  81. package/lib/archive/url-alias/compute-tier-b-alias-key.d.ts +19 -0
  82. package/lib/archive/url-alias/compute-tier-b-alias-key.js +30 -0
  83. package/lib/archive/url-alias/format-alias-key.d.ts +13 -0
  84. package/lib/archive/url-alias/format-alias-key.js +14 -0
  85. package/lib/archive/url-alias/parse-alias-key-parts.d.ts +15 -0
  86. package/lib/archive/url-alias/parse-alias-key-parts.js +40 -0
  87. package/lib/archive/url-alias/types.d.ts +7 -0
  88. package/lib/archive/url-alias/types.js +1 -0
  89. package/lib/crawler/choose-probe-host.d.ts +24 -0
  90. package/lib/crawler/choose-probe-host.js +38 -0
  91. package/lib/crawler/clear-dns-burned-host-cache.js +2 -0
  92. package/lib/crawler/crawler.js +257 -0
  93. package/lib/crawler/dns-burned-host-burn-timestamps.d.ts +17 -0
  94. package/lib/crawler/dns-burned-host-burn-timestamps.js +17 -0
  95. package/lib/crawler/evict-network-classified-destination-cache-entries.d.ts +26 -0
  96. package/lib/crawler/evict-network-classified-destination-cache-entries.js +34 -0
  97. package/lib/crawler/evict-outage-tainted-dns-burns.d.ts +23 -0
  98. package/lib/crawler/evict-outage-tainted-dns-burns.js +26 -0
  99. package/lib/crawler/network-gate.d.ts +49 -0
  100. package/lib/crawler/network-gate.js +78 -0
  101. package/lib/crawler/network-outage-detector.d.ts +51 -0
  102. package/lib/crawler/network-outage-detector.js +81 -0
  103. package/lib/crawler/network-outage-summary-counter.d.ts +21 -0
  104. package/lib/crawler/network-outage-summary-counter.js +18 -0
  105. package/lib/crawler/probe-network.d.ts +26 -0
  106. package/lib/crawler/probe-network.js +21 -0
  107. package/lib/crawler/types.d.ts +147 -1
  108. package/lib/crawler-orchestrator.d.ts +62 -18
  109. package/lib/crawler-orchestrator.js +161 -26
  110. package/lib/crawler.d.ts +21 -0
  111. package/lib/crawler.js +17 -0
  112. package/lib/is-within-outage-window.d.ts +49 -0
  113. package/lib/is-within-outage-window.js +33 -0
  114. package/lib/network-related-error-kinds.d.ts +23 -0
  115. package/lib/network-related-error-kinds.js +28 -0
  116. package/lib/types.d.ts +9 -1
  117. package/lib/utils/array/each-splitted.d.ts +1 -1
  118. package/lib/utils/compute-file-sha256.d.ts +17 -17
  119. package/lib/utils/compute-file-sha256.js +18 -47
  120. package/package.json +3 -3
@@ -0,0 +1,32 @@
1
+ import fs from 'node:fs/promises';
2
+ import { pathExists } from './path-exists.js';
3
+ /**
4
+ * Remove an entire archive cache root, including every tar-cache entry and
5
+ * any sibling directory living under it (e.g. the `@nitpicker/core` analyze
6
+ * `table` cache, which is resolved as a child of the same root).
7
+ *
8
+ * Pure: takes `cacheRoot` as a parameter and never resolves it itself, so
9
+ * tests can point it at a throwaway directory instead of the real OS temp
10
+ * cache. Mirrors the "manual `rm -rf` is safe" contract already documented
11
+ * for the tar cache (ARCHITECTURE.md) — no confirmation, no lock check.
12
+ *
13
+ * Why not lock-aware: a concurrent `extractArchiveToCache` elsewhere may be
14
+ * holding `<cacheDir>.lock` / writing `<cacheDir>.staging` inside this root
15
+ * when it is removed, which can surface as an ENOENT in that extraction (or,
16
+ * rarely, a second extractor racing into a freshly recreated `.staging`
17
+ * path). This is the same exposure a manual `rm -rf` already has today —
18
+ * this function does not add new risk, it just makes that pre-existing,
19
+ * accepted risk reachable via a single explicit command.
20
+ * @param cacheRoot - Absolute path to the cache root to remove.
21
+ * @returns `true` if `cacheRoot` existed and was removed, `false` if it was
22
+ * already absent.
23
+ * @example
24
+ * ```ts
25
+ * const removed = await clearArchiveCacheRoot(getArchiveCacheRoot());
26
+ * ```
27
+ */
28
+ export async function clearArchiveCacheRoot(cacheRoot) {
29
+ const existedBefore = await pathExists(cacheRoot);
30
+ await fs.rm(cacheRoot, { recursive: true, force: true });
31
+ return existedBefore;
32
+ }
@@ -0,0 +1,23 @@
1
+ import type { ArchiveCacheEntry } from './types.js';
2
+ /**
3
+ * List the top-level entries found directly under an archive cache root,
4
+ * with a recursive size total and the most recent mtime found in each.
5
+ *
6
+ * Pure: takes `cacheRoot` as a parameter and never resolves it itself (see
7
+ * {@link import('./get-archive-cache-root.js').getArchiveCacheRoot} for the
8
+ * production root), so tests can point it at a throwaway directory instead
9
+ * of the real OS temp cache.
10
+ *
11
+ * Symbolic links are reported but never followed, both at the top level and
12
+ * while walking a directory's contents — this avoids escaping `cacheRoot`
13
+ * and crashing on dangling links.
14
+ * @param cacheRoot - Absolute path to the cache root to inspect.
15
+ * @returns One entry per top-level child of `cacheRoot`, in `fs.readdir`
16
+ * order. Returns `[]` if `cacheRoot` does not exist.
17
+ * @example
18
+ * ```ts
19
+ * const entries = await listArchiveCacheEntries(getArchiveCacheRoot());
20
+ * const totalBytes = entries.reduce((sum, e) => sum + e.sizeBytes, 0);
21
+ * ```
22
+ */
23
+ export declare function listArchiveCacheEntries(cacheRoot: string): Promise<ArchiveCacheEntry[]>;
@@ -0,0 +1,125 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /**
4
+ * List the top-level entries found directly under an archive cache root,
5
+ * with a recursive size total and the most recent mtime found in each.
6
+ *
7
+ * Pure: takes `cacheRoot` as a parameter and never resolves it itself (see
8
+ * {@link import('./get-archive-cache-root.js').getArchiveCacheRoot} for the
9
+ * production root), so tests can point it at a throwaway directory instead
10
+ * of the real OS temp cache.
11
+ *
12
+ * Symbolic links are reported but never followed, both at the top level and
13
+ * while walking a directory's contents — this avoids escaping `cacheRoot`
14
+ * and crashing on dangling links.
15
+ * @param cacheRoot - Absolute path to the cache root to inspect.
16
+ * @returns One entry per top-level child of `cacheRoot`, in `fs.readdir`
17
+ * order. Returns `[]` if `cacheRoot` does not exist.
18
+ * @example
19
+ * ```ts
20
+ * const entries = await listArchiveCacheEntries(getArchiveCacheRoot());
21
+ * const totalBytes = entries.reduce((sum, e) => sum + e.sizeBytes, 0);
22
+ * ```
23
+ */
24
+ export async function listArchiveCacheEntries(cacheRoot) {
25
+ let topLevel;
26
+ try {
27
+ topLevel = await fs.readdir(cacheRoot, { withFileTypes: true });
28
+ }
29
+ catch (error) {
30
+ if (error.code === 'ENOENT') {
31
+ return [];
32
+ }
33
+ throw error;
34
+ }
35
+ const entries = [];
36
+ for (const dirent of topLevel) {
37
+ const entryPath = path.join(cacheRoot, dirent.name);
38
+ if (dirent.isSymbolicLink()) {
39
+ entries.push({
40
+ kind: 'unknown',
41
+ name: dirent.name,
42
+ path: entryPath,
43
+ sizeBytes: 0,
44
+ mtimeMs: 0,
45
+ });
46
+ continue;
47
+ }
48
+ if (dirent.isDirectory()) {
49
+ const { sizeBytes, mtimeMs } = await computeDirectoryStats(entryPath);
50
+ entries.push({
51
+ kind: classifyEntryName(dirent.name),
52
+ name: dirent.name,
53
+ path: entryPath,
54
+ sizeBytes,
55
+ mtimeMs,
56
+ });
57
+ continue;
58
+ }
59
+ const stat = await fs.stat(entryPath);
60
+ entries.push({
61
+ kind: 'unknown',
62
+ name: dirent.name,
63
+ path: entryPath,
64
+ sizeBytes: stat.size,
65
+ mtimeMs: stat.mtimeMs,
66
+ });
67
+ }
68
+ return entries;
69
+ }
70
+ /**
71
+ * Matches the corrupt-quarantine suffix `extractArchiveToCache` appends
72
+ * (`${cacheDir}.corrupt.${pid}.${counter}`, both segments always numeric —
73
+ * see `quarantineHalfPopulatedCacheDir` in `extract-archive-to-cache.ts`).
74
+ * Anchored and numeric-specific rather than a loose `includes('.corrupt.')`
75
+ * so an archive whose own (sanitized) basename merely contains the
76
+ * substring `.corrupt.` — e.g. `my.corrupt.report.nitpicker` — is not
77
+ * misclassified as an orphan and offered up for deletion by `cache list`.
78
+ */
79
+ const CORRUPT_QUARANTINE_SUFFIX = /\.corrupt\.\d+\.\d+$/;
80
+ /**
81
+ * Classify a cache-root child by name pattern alone (no filesystem access).
82
+ *
83
+ * This is a heuristic: `.staging`/corrupt-quarantine suffixes are appended
84
+ * by `extractArchiveToCache` onto an existing tar-cache dir name, so an
85
+ * archive whose own sanitized basename happens to end in exactly one of
86
+ * these literal suffixes is indistinguishable from a real orphan by name
87
+ * alone. Disambiguating fully would require re-deriving each entry's
88
+ * expected name from its source archive, which `list`/`clear` (by design,
89
+ * see grill-me scope) never has access to. Accepted as a rare, low-cost
90
+ * misclassification.
91
+ * @param name - Base name of the top-level entry.
92
+ */
93
+ function classifyEntryName(name) {
94
+ if (name === 'table') {
95
+ return 'table';
96
+ }
97
+ if (name.endsWith('.staging') || CORRUPT_QUARANTINE_SUFFIX.test(name)) {
98
+ return 'orphan';
99
+ }
100
+ return 'tar-cache';
101
+ }
102
+ /**
103
+ * Recursively sum file sizes and find the most recent mtime under a
104
+ * directory. Symbolic links are neither followed nor counted.
105
+ * @param dirPath - Absolute path to the directory to walk.
106
+ */
107
+ async function computeDirectoryStats(dirPath) {
108
+ let sizeBytes = 0;
109
+ let mtimeMs = 0;
110
+ const children = await fs.readdir(dirPath, { recursive: true, withFileTypes: true });
111
+ for (const child of children) {
112
+ if (!child.isFile()) {
113
+ continue;
114
+ }
115
+ const childPath = path.join(child.parentPath, child.name);
116
+ const stat = await fs.stat(childPath);
117
+ sizeBytes += stat.size;
118
+ mtimeMs = Math.max(mtimeMs, stat.mtimeMs);
119
+ }
120
+ if (mtimeMs === 0) {
121
+ const dirStat = await fs.stat(dirPath);
122
+ mtimeMs = dirStat.mtimeMs;
123
+ }
124
+ return { sizeBytes, mtimeMs };
125
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Async existence probe — avoids blocking the event loop on the common
3
+ * "check before remove" path shared by
4
+ * {@link import('./clear-archive-cache-root.js').clearArchiveCacheRoot} and
5
+ * {@link import('./clear-archive-cache-entry.js').clearArchiveCacheEntry}.
6
+ * @param targetPath - Absolute path to probe.
7
+ * @returns `true` if the path is reachable via `fs.access`.
8
+ */
9
+ export declare function pathExists(targetPath: string): Promise<boolean>;
@@ -0,0 +1,18 @@
1
+ import fs from 'node:fs/promises';
2
+ /**
3
+ * Async existence probe — avoids blocking the event loop on the common
4
+ * "check before remove" path shared by
5
+ * {@link import('./clear-archive-cache-root.js').clearArchiveCacheRoot} and
6
+ * {@link import('./clear-archive-cache-entry.js').clearArchiveCacheEntry}.
7
+ * @param targetPath - Absolute path to probe.
8
+ * @returns `true` if the path is reachable via `fs.access`.
9
+ */
10
+ export async function pathExists(targetPath) {
11
+ try {
12
+ await fs.access(targetPath);
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Classification of a top-level entry found directly under an archive cache
3
+ * root ({@link import('./get-archive-cache-root.js').getArchiveCacheRoot}).
4
+ *
5
+ * - `'tar-cache'`: a per-archive extraction produced by
6
+ * {@link import('./resolve-archive-cache-dir.js').resolveArchiveCacheDir}
7
+ * (`<cacheKey>-<safeBasename>`).
8
+ * - `'table'`: the `@nitpicker/core` analyze-plugin scratch cache
9
+ * (`getTableCacheRoot()`), a sibling directory literally named `table`.
10
+ * - `'orphan'`: a `.staging` or `.corrupt.<pid>.<n>` leftover from an
11
+ * interrupted {@link import('./extract-archive-to-cache.js').extractArchiveToCache}
12
+ * run (see that file's quarantine/staging logic).
13
+ * - `'unknown'`: anything else (a stray file, a foreign directory a user
14
+ * dropped into the cache root).
15
+ *
16
+ * `'tar-cache'` and `'table'` cannot collide: `resolveArchiveCacheDir` always
17
+ * prefixes the cache key (digits and hyphens), so a tar-cache directory name
18
+ * is never the bare literal `table`.
19
+ */
20
+ export type ArchiveCacheEntryKind = 'tar-cache' | 'table' | 'orphan' | 'unknown';
21
+ /** A single top-level entry found under an archive cache root. */
22
+ export interface ArchiveCacheEntry {
23
+ /** How this entry was classified by name pattern. */
24
+ readonly kind: ArchiveCacheEntryKind;
25
+ /** Base name of the entry (its final path segment). */
26
+ readonly name: string;
27
+ /** Absolute path to the entry. */
28
+ readonly path: string;
29
+ /** Total size in bytes of all regular files found under this entry (recursive for directories). */
30
+ readonly sizeBytes: number;
31
+ /** Most recent mtime (epoch ms) found among the entry's files, or the entry's own mtime if it has none. */
32
+ readonly mtimeMs: number;
33
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -14,13 +14,24 @@ import type { Knex } from 'knex';
14
14
  * `MainContentsData` sub-entity arrays, one row per DOM element, FK →
15
15
  * `content_items(id)`
16
16
  * - `inventory_runs` — `--inventory` audit log (no FK; append-only)
17
+ * - `network_outages` — operator-network-outage journal (no FK; append-only
18
+ * except `ended_at`, which is written once on recovery)
17
19
  * - `analysis_text_refs` + `analysis_violations` — analyze-phase findings,
18
20
  * FK → `content_items(id)`
19
21
  * - `page_templates` — DOM-structure template classification (`--templates`,
20
22
  * `@nitpicker/core`'s `template-classification/`), one row per classified
21
23
  * page, FK → `content_items(id)`
24
+ * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
25
+ * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
26
+ * `template_key` is not a `page_templates` FK target, so consistency is
27
+ * maintained by replacing both tables together, not by a foreign key)
22
28
  * - `page_html_blobs` + `page_html_ref` — content-addressable HTML
23
29
  * snapshots, FK → `content_items(id)`
30
+ * - `console_log_items` — content-addressable dictionary of distinct
31
+ * console messages / page errors (no FK; hash-deduplicated across every
32
+ * page in the archive, mirroring `text_refs` / `json_refs`)
33
+ * - `page_console_logs` — one row per (page, console log) occurrence, FK →
34
+ * `content_items(id)` and `console_log_items(id)`
24
35
  *
25
36
  * The DDL is shared between fresh-archive provisioning ({@link initSchema}
26
37
  * calls this right after `createEntityTables`) and the migration script
@@ -13,13 +13,24 @@
13
13
  * `MainContentsData` sub-entity arrays, one row per DOM element, FK →
14
14
  * `content_items(id)`
15
15
  * - `inventory_runs` — `--inventory` audit log (no FK; append-only)
16
+ * - `network_outages` — operator-network-outage journal (no FK; append-only
17
+ * except `ended_at`, which is written once on recovery)
16
18
  * - `analysis_text_refs` + `analysis_violations` — analyze-phase findings,
17
19
  * FK → `content_items(id)`
18
20
  * - `page_templates` — DOM-structure template classification (`--templates`,
19
21
  * `@nitpicker/core`'s `template-classification/`), one row per classified
20
22
  * page, FK → `content_items(id)`
23
+ * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
24
+ * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
25
+ * `template_key` is not a `page_templates` FK target, so consistency is
26
+ * maintained by replacing both tables together, not by a foreign key)
21
27
  * - `page_html_blobs` + `page_html_ref` — content-addressable HTML
22
28
  * snapshots, FK → `content_items(id)`
29
+ * - `console_log_items` — content-addressable dictionary of distinct
30
+ * console messages / page errors (no FK; hash-deduplicated across every
31
+ * page in the archive, mirroring `text_refs` / `json_refs`)
32
+ * - `page_console_logs` — one row per (page, console log) occurrence, FK →
33
+ * `content_items(id)` and `console_log_items(id)`
23
34
  *
24
35
  * The DDL is shared between fresh-archive provisioning ({@link initSchema}
25
36
  * calls this right after `createEntityTables`) and the migration script
@@ -279,10 +290,42 @@ export async function createAdjunctTables(instance) {
279
290
  t.integer('new_pages').nullable();
280
291
  t.integer('new_resources').nullable();
281
292
  t.integer('scope_skipped').nullable();
293
+ t.integer('invalid_skipped').nullable();
282
294
  t.text('notes').nullable();
283
295
  t.index('ran_at');
284
296
  });
285
297
  }
298
+ if (!(await instance.schema.hasTable('network_outages'))) {
299
+ await instance.schema.createTable('network_outages', (t) => {
300
+ // One row per detected operator-network outage. The archive's
301
+ // evidence that a run of `dns`/`local-network`-shaped failures
302
+ // was caused by the crawl operator's own connectivity, not the
303
+ // target sites — used to retroactively re-classify `crawl_errors`
304
+ // / `page_errors` rows whose `createdAt` falls inside a window
305
+ // (see `is-within-outage-window.ts`). No index: a crawl session
306
+ // produces at most a handful of these rows, so a full in-memory
307
+ // scan by every consumer is cheaper than maintaining a B-tree
308
+ // that few queries would use (`ARCHITECTURE.md`'s
309
+ // perf-index-is-not-free / evidence-before-indexing rules).
310
+ t.increments('id');
311
+ // Backdated to the earliest error still inside the detector's
312
+ // sliding window at trigger time, NOT the trigger instant —
313
+ // see `NetworkOutageDetector`'s `OutageSuspect.startedAt`.
314
+ t.integer('started_at').notNullable();
315
+ // When the sliding window actually crossed both thresholds.
316
+ t.integer('detected_at').notNullable();
317
+ // NULL until a recovery probe succeeds. A row can also be left
318
+ // NULL forever if the crawl process is killed mid-outage; readers
319
+ // MUST NOT treat a NULL `ended_at` as an unbounded window (that
320
+ // would retroactively cover every later error as
321
+ // network-caused) — see `is-within-outage-window.ts` and the
322
+ // writer-side clamp-on-next-open in `db-ops/outages/`.
323
+ t.integer('ended_at').nullable();
324
+ t.string('probe_host').nullable();
325
+ t.integer('trigger_error_count').notNullable();
326
+ t.integer('trigger_host_count').notNullable();
327
+ });
328
+ }
286
329
  if (!(await instance.schema.hasTable('analysis_text_refs'))) {
287
330
  await instance.raw(`
288
331
  CREATE TABLE analysis_text_refs (
@@ -334,6 +377,34 @@ export async function createAdjunctTables(instance) {
334
377
  ) WITHOUT ROWID
335
378
  `);
336
379
  }
380
+ // One row per distinct `template_key` produced by the same `--templates`
381
+ // classification run, holding `@d-zero/page-cluster`'s cluster-selection
382
+ // evidence (`ClusterReason`, renamed `TemplateClusterReason` on this side)
383
+ // as a zstd-compressed JSON blob — same BLOB+codec+size shape as
384
+ // `page_html_blobs` below. A column on `page_templates` was rejected: that
385
+ // table is one row per *page*, so the same cluster's reason would be
386
+ // duplicated across every member page (multi-GB on a large archive with a
387
+ // few-hundred-member cluster). A `json_refs` row was also rejected: reason
388
+ // payloads differ per cluster (distinct `memberCount`/token sets), so
389
+ // content-address dedup would not pay for itself, and `json_refs` is a
390
+ // shared dictionary that other tables reference — this table's full
391
+ // replace-on-every-run write pattern (see `replacePageTemplates`) would
392
+ // otherwise leave orphaned rows behind with no owner able to delete them.
393
+ // No FK to `page_templates`: `template_key` is not that table's primary
394
+ // key (`page_id` is), so there is nothing to reference — consistency is
395
+ // instead maintained by replacing both tables in the same transaction.
396
+ if (!(await instance.schema.hasTable('page_template_clusters'))) {
397
+ await instance.raw(`
398
+ CREATE TABLE page_template_clusters (
399
+ template_key TEXT PRIMARY KEY,
400
+ member_count INTEGER NOT NULL,
401
+ reason_json BLOB NOT NULL,
402
+ codec TEXT NOT NULL CHECK(codec IN ('zstd', 'none')),
403
+ size_raw INTEGER NOT NULL,
404
+ size_stored INTEGER NOT NULL
405
+ ) WITHOUT ROWID
406
+ `);
407
+ }
337
408
  // Content-addressable HTML blob storage. Knex's schema builder doesn't
338
409
  // expose a WITHOUT ROWID toggle, so the BLOB tables are created via raw
339
410
  // SQL. WITHOUT ROWID keeps the rows packed inside the b-tree leaves
@@ -360,4 +431,60 @@ export async function createAdjunctTables(instance) {
360
431
  `);
361
432
  await instance.raw('CREATE INDEX idx_page_html_ref_hash ON page_html_ref(hash)');
362
433
  }
434
+ // Content-addressable dictionary of distinct console messages / page
435
+ // errors (beholder's `ConsoleLogEntry`, issue #228). `hash` is
436
+ // SHA-256 over a canonical tuple of every content field (type, text,
437
+ // args JSON, location, stack) — the same identical warning emitted by
438
+ // a shared framework on every page therefore collapses to one row
439
+ // regardless of how many pages or how many times it fires, mirroring
440
+ // `text_refs` / `json_refs`. `args_json_id` is nullable because a
441
+ // call with no arguments (or one whose args failed to
442
+ // `JSON.stringify`, e.g. a circular reference) has nothing to store.
443
+ // `text_id` is nullable too: `text_refs` never stores the empty
444
+ // string (its dictionary upsert treats `''` as "nothing to dedupe"),
445
+ // so a call like `console.log()` with zero arguments — whose
446
+ // `text` beholder reports as `''` — has no `text_refs` row to point
447
+ // at; `text_id = NULL` there means "empty text", read back as `''`.
448
+ // `type` keeps its own index for the Console Logs view's type filter.
449
+ if (!(await instance.schema.hasTable('console_log_items'))) {
450
+ await instance.raw(`
451
+ CREATE TABLE console_log_items (
452
+ id INTEGER PRIMARY KEY,
453
+ hash BLOB NOT NULL UNIQUE,
454
+ type TEXT NOT NULL,
455
+ text_id INTEGER REFERENCES text_refs(id),
456
+ args_json_id INTEGER REFERENCES json_refs(id),
457
+ loc_url_id INTEGER REFERENCES url_refs(id),
458
+ loc_line INTEGER,
459
+ loc_column INTEGER,
460
+ stack_text_id INTEGER REFERENCES text_refs(id)
461
+ )
462
+ `);
463
+ await instance.raw('CREATE INDEX idx_console_log_items_type ON console_log_items(type)');
464
+ }
465
+ // One row per (page, console log) occurrence — beholder captures a
466
+ // `ts` per firing, so the same message logged 3 times on one page
467
+ // yields 3 rows (unlike `anchor_edges`' first-wins dedup: an
468
+ // occurrence count matters here, not just presence). Replaced
469
+ // wholesale per page on every non-empty scrape by
470
+ // `replaceConsoleLogs`, the same Scoped-Replace pattern as
471
+ // `anchor_edges` / `image_items` — there is no natural key to UPDATE
472
+ // a specific prior occurrence against.
473
+ if (!(await instance.schema.hasTable('page_console_logs'))) {
474
+ await instance.schema.createTable('page_console_logs', (t) => {
475
+ t.increments('id');
476
+ t.integer('pageId')
477
+ .notNullable()
478
+ .unsigned()
479
+ .references('content_items.id')
480
+ .onDelete('CASCADE');
481
+ t.integer('consoleLogId')
482
+ .notNullable()
483
+ .unsigned()
484
+ .references('console_log_items.id');
485
+ t.integer('ts').notNullable();
486
+ t.index('pageId');
487
+ t.index('consoleLogId');
488
+ });
489
+ }
363
490
  }
@@ -197,6 +197,7 @@ export async function createEntityTables(instance) {
197
197
  content_length INTEGER,
198
198
  header_set_id INTEGER REFERENCES header_sets(id),
199
199
  redirect_dest_id INTEGER REFERENCES content_items(id) DEFERRABLE INITIALLY DEFERRED,
200
+ alias_of_id INTEGER REFERENCES content_items(id) DEFERRABLE INITIALLY DEFERRED,
200
201
  source TEXT NOT NULL DEFAULT 'crawled',
201
202
  first_crawled_at INTEGER,
202
203
  last_crawled_at INTEGER,
@@ -208,6 +209,15 @@ export async function createEntityTables(instance) {
208
209
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_content_items_external ON content_items(is_external)');
209
210
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_content_items_scraped ON content_items(scraped)');
210
211
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_content_items_redirect_dest_id ON content_items(redirect_dest_id)');
212
+ // `idx_content_items_alias_of_id` is NOT created here even though
213
+ // `alias_of_id` is: this DDL runs unconditionally on every archive open
214
+ // (including legacy archives that still lack the column at this point,
215
+ // before `migrateContentItemsAliasOfId` adds it), so an unconditional
216
+ // `CREATE INDEX ... alias_of_id` here would fail with `no such column`
217
+ // on any archive that predates this feature. The index is created in
218
+ // `migrateContentItemsAliasOfId` instead, which runs after the
219
+ // column-add guard for both fresh and legacy archives (same reasoning as
220
+ // `page_meta.body_hash`'s index).
211
221
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_content_items_content_type_id ON content_items(content_type_id)');
212
222
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_content_items_crawl_order ON content_items(crawl_order)');
213
223
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_content_items_source ON content_items(source)');
@@ -279,10 +289,20 @@ export async function createEntityTables(instance) {
279
289
  main_content_audio_count INTEGER,
280
290
  main_content_canvas_count INTEGER,
281
291
  scroll_height_desktop INTEGER,
282
- scroll_height_mobile INTEGER
292
+ scroll_height_mobile INTEGER,
293
+ body_hash BLOB,
294
+ console_error_count INTEGER
283
295
  )
284
296
  `);
285
297
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_page_meta_og_type ON page_meta(og_type)');
298
+ // `idx_page_meta_body_hash` is NOT created here even though `body_hash`
299
+ // is: this DDL runs unconditionally on every archive open (including
300
+ // legacy archives that still lack the column at this point, before
301
+ // `migratePageMetaBodyHash` adds it), so an unconditional
302
+ // `CREATE INDEX ... body_hash` here would fail with `no such column` on
303
+ // any archive that predates this feature. The index is created in
304
+ // `migratePageMetaBodyHash` instead, which runs after the column-add
305
+ // guard for both fresh and legacy archives.
286
306
  await instance.raw('CREATE INDEX IF NOT EXISTS idx_page_meta_robots_noindex ON page_meta(robots_noindex)');
287
307
  await instance.raw(`
288
308
  CREATE TABLE IF NOT EXISTS resource_items (
@@ -1,6 +1,9 @@
1
+ import type { TemplateClusterReason } from './db-ops/analysis/types.js';
1
2
  import type { JsonLdRow, MainContentAudioRow, MainContentButtonRow, MainContentCanvasRow, MainContentHeadingRow, MainContentIframeRow, MainContentImageRow, MainContentTableRow, MainContentVideoRow, TagRow } from './meta/types.js';
2
- import type { Config, DatabaseOption, DB_Redirect, DB_Resource, DatabaseEvent, InventoryRunMeta, PageFilter, PageSource } from './types.js';
3
+ import type { Config, DatabaseOption, DB_Redirect, DB_Resource, DatabaseEvent, InsertNetworkOutageParams, InventoryRunMeta, PageFilter, PageSource } from './types.js';
4
+ import type { OutageWindow } from '../is-within-outage-window.js';
3
5
  import type { PageData, Resource } from '../utils/types/types.js';
6
+ import type { ConsoleLogEntry } from '@d-zero/beholder';
4
7
  import type { ExURL, ParseURLOptions } from '@d-zero/shared/parse-url';
5
8
  import type { Knex } from 'knex';
6
9
  import { TypedAwaitEventEmitter as EventEmitter } from '@d-zero/shared/typed-await-event-emitter';
@@ -34,6 +37,13 @@ export declare class Database extends EventEmitter<DatabaseEvent> {
34
37
  * database file. Delegates to {@link checkpointOp}.
35
38
  */
36
39
  checkpoint(): Promise<void>;
40
+ /**
41
+ * Closes an outage row by stamping `ended_at` — a no-op if the row is
42
+ * already closed. Delegates to {@link closeNetworkOutageOp}.
43
+ * @param id - The `network_outages.id` to close.
44
+ * @param endedAt - Epoch ms the outage is considered to have ended.
45
+ */
46
+ closeNetworkOutage(id: number, endedAt: number): Promise<void>;
37
47
  /**
38
48
  * Destroys the database connection, releasing all pooled resources.
39
49
  * Delegates to {@link destroyOp}.
@@ -277,6 +287,13 @@ export declare class Database extends EventEmitter<DatabaseEvent> {
277
287
  * @param urls - URL strings already in `withoutHashAndAuth` form.
278
288
  */
279
289
  insertInventorySeeds(urls: readonly string[]): Promise<void>;
290
+ /**
291
+ * Appends one open (`ended_at = NULL`) row to the `network_outages`
292
+ * journal. Delegates to {@link insertNetworkOutageOp}.
293
+ * @param params - The confirmed-outage fields to record.
294
+ * @returns The autoincremented `id` of the newly-inserted row.
295
+ */
296
+ insertNetworkOutage(params: InsertNetworkOutageParams): Promise<number>;
280
297
  /**
281
298
  * Records a partial scrape failure against the page identified by `url`.
282
299
  * Delegates to {@link insertPageErrorOp}.
@@ -307,6 +324,13 @@ export declare class Database extends EventEmitter<DatabaseEvent> {
307
324
  * @returns Lower-cased hostnames safe to short-circuit.
308
325
  */
309
326
  listDnsBurnedHostCandidates(): Promise<string[]>;
327
+ /**
328
+ * Lists every recorded outage as a resolved {@link OutageWindow}.
329
+ * Delegates to {@link listNetworkOutagesOp}.
330
+ * @returns Resolved outage windows, or `[]` on an archive that predates
331
+ * `network_outages` or has recorded no outages.
332
+ */
333
+ listNetworkOutages(): Promise<OutageWindow[]>;
310
334
  /**
311
335
  * Appends one row to the `inventory_runs` audit log.
312
336
  * Delegates to {@link recordInventoryRunOp}.
@@ -339,12 +363,23 @@ export declare class Database extends EventEmitter<DatabaseEvent> {
339
363
  line?: number | null;
340
364
  col?: number | null;
341
365
  }[]): Promise<void>;
366
+ /**
367
+ * Replaces one page's `page_console_logs` rows with a freshly captured
368
+ * set of console messages / page errors. Delegates to
369
+ * {@link replaceConsoleLogsOp}.
370
+ * @param pageUrl - The originally-requested URL, normalised (`withoutHashAndAuth` form).
371
+ * @param redirectPaths - The redirect chain hops captured during fetch, in order.
372
+ * @param entries - The console log entries to persist.
373
+ */
374
+ replaceConsoleLogs(pageUrl: string, redirectPaths: readonly string[], entries: readonly ConsoleLogEntry[]): Promise<void>;
342
375
  /**
343
376
  * Replaces the stored DOM-structure template classification with a
344
377
  * freshly generated set. Delegates to {@link replacePageTemplatesOp}.
345
378
  * @param templateKeysByUrl - Page URL → template key.
379
+ * @param clusterReasonsByTemplateKey - Template key → cluster-selection
380
+ * evidence, if the caller captured it.
346
381
  */
347
- replacePageTemplates(templateKeysByUrl: ReadonlyMap<string, string>): Promise<void>;
382
+ replacePageTemplates(templateKeysByUrl: ReadonlyMap<string, string>, clusterReasonsByTemplateKey?: ReadonlyMap<string, TemplateClusterReason>): Promise<void>;
348
383
  /**
349
384
  * Promote previously-external pages whose URL falls under any of the new
350
385
  * scope entries back to a "needs scraping" state.