@nitpicker/archive 0.0.0-stage → 0.25.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 (737) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +105 -2
  3. package/lib/apply-connection-pragmas.d.ts +18 -0
  4. package/lib/apply-connection-pragmas.js +40 -0
  5. package/lib/archive-accessor.d.ts +265 -0
  6. package/lib/archive-accessor.js +477 -0
  7. package/lib/archive-lock.d.ts +45 -0
  8. package/lib/archive-lock.js +154 -0
  9. package/lib/archive.d.ts +736 -0
  10. package/lib/archive.js +1056 -0
  11. package/lib/body-hash/compute-body-hash.d.ts +32 -0
  12. package/lib/body-hash/compute-body-hash.js +35 -0
  13. package/lib/cache/clear-archive-cache-entry.d.ts +18 -0
  14. package/lib/cache/clear-archive-cache-entry.js +24 -0
  15. package/lib/cache/clear-archive-cache-root.d.ts +26 -0
  16. package/lib/cache/clear-archive-cache-root.js +32 -0
  17. package/lib/cache/compute-archive-cache-key.d.ts +39 -0
  18. package/lib/cache/compute-archive-cache-key.js +95 -0
  19. package/lib/cache/extract-archive-to-cache.d.ts +57 -0
  20. package/lib/cache/extract-archive-to-cache.js +326 -0
  21. package/lib/cache/get-archive-cache-root.d.ts +20 -0
  22. package/lib/cache/get-archive-cache-root.js +53 -0
  23. package/lib/cache/is-archive-cache-disabled.d.ts +24 -0
  24. package/lib/cache/is-archive-cache-disabled.js +34 -0
  25. package/lib/cache/list-archive-cache-entries.d.ts +23 -0
  26. package/lib/cache/list-archive-cache-entries.js +130 -0
  27. package/lib/cache/path-exists.d.ts +9 -0
  28. package/lib/cache/path-exists.js +18 -0
  29. package/lib/cache/resolve-archive-cache-dir.d.ts +26 -0
  30. package/lib/cache/resolve-archive-cache-dir.js +32 -0
  31. package/lib/cache/types.d.ts +33 -0
  32. package/lib/cache/types.js +1 -0
  33. package/lib/content-type/is-html-content-type.d.ts +17 -0
  34. package/lib/content-type/is-html-content-type.js +19 -0
  35. package/lib/content-type/normalize-content-type.d.ts +14 -0
  36. package/lib/content-type/normalize-content-type.js +20 -0
  37. package/lib/create-adjunct-tables.d.ts +66 -0
  38. package/lib/create-adjunct-tables.js +510 -0
  39. package/lib/create-entity-tables.d.ts +191 -0
  40. package/lib/create-entity-tables.js +387 -0
  41. package/lib/create-progress-reporter.d.ts +30 -0
  42. package/lib/create-progress-reporter.js +38 -0
  43. package/lib/create-ref-tables.d.ts +35 -0
  44. package/lib/create-ref-tables.js +185 -0
  45. package/lib/create-template-tables.d.ts +28 -0
  46. package/lib/create-template-tables.js +92 -0
  47. package/lib/database.d.ts +549 -0
  48. package/lib/database.js +804 -0
  49. package/lib/db-ops/_shared/clear-write-ref-caches.d.ts +27 -0
  50. package/lib/db-ops/_shared/clear-write-ref-caches.js +35 -0
  51. package/lib/db-ops/_shared/compress-payload.d.ts +26 -0
  52. package/lib/db-ops/_shared/compress-payload.js +30 -0
  53. package/lib/db-ops/_shared/create-write-ref-caches.d.ts +17 -0
  54. package/lib/db-ops/_shared/create-write-ref-caches.js +27 -0
  55. package/lib/db-ops/_shared/decode-json-ref.d.ts +17 -0
  56. package/lib/db-ops/_shared/decode-json-ref.js +31 -0
  57. package/lib/db-ops/_shared/keyset-paginate-by-id.d.ts +49 -0
  58. package/lib/db-ops/_shared/keyset-paginate-by-id.js +69 -0
  59. package/lib/db-ops/_shared/load-response-headers-by-set-ids.d.ts +20 -0
  60. package/lib/db-ops/_shared/load-response-headers-by-set-ids.js +53 -0
  61. package/lib/db-ops/_shared/resolve-content-item-id.d.ts +62 -0
  62. package/lib/db-ops/_shared/resolve-content-item-id.js +143 -0
  63. package/lib/db-ops/_shared/resolve-url-or-blob.d.ts +23 -0
  64. package/lib/db-ops/_shared/resolve-url-or-blob.js +29 -0
  65. package/lib/db-ops/_shared/retry-setting.d.ts +16 -0
  66. package/lib/db-ops/_shared/retry-setting.js +18 -0
  67. package/lib/db-ops/_shared/safe-parse-json.d.ts +11 -0
  68. package/lib/db-ops/_shared/safe-parse-json.js +18 -0
  69. package/lib/db-ops/_shared/types.d.ts +94 -0
  70. package/lib/db-ops/_shared/types.js +1 -0
  71. package/lib/db-ops/_shared/upsert-blob-ref.d.ts +25 -0
  72. package/lib/db-ops/_shared/upsert-blob-ref.js +48 -0
  73. package/lib/db-ops/_shared/upsert-content-type-ref.d.ts +30 -0
  74. package/lib/db-ops/_shared/upsert-content-type-ref.js +45 -0
  75. package/lib/db-ops/_shared/upsert-json-ref.d.ts +22 -0
  76. package/lib/db-ops/_shared/upsert-json-ref.js +41 -0
  77. package/lib/db-ops/_shared/upsert-response-headers.d.ts +35 -0
  78. package/lib/db-ops/_shared/upsert-response-headers.js +49 -0
  79. package/lib/db-ops/_shared/upsert-url-ref.d.ts +39 -0
  80. package/lib/db-ops/_shared/upsert-url-ref.js +62 -0
  81. package/lib/db-ops/anchors/get-anchors-on-page.d.ts +10 -0
  82. package/lib/db-ops/anchors/get-anchors-on-page.js +21 -0
  83. package/lib/db-ops/config/get-base-url.d.ts +8 -0
  84. package/lib/db-ops/config/get-base-url.js +14 -0
  85. package/lib/db-ops/config/get-config.d.ts +10 -0
  86. package/lib/db-ops/config/get-config.js +29 -0
  87. package/lib/db-ops/config/get-created-cwd.d.ts +11 -0
  88. package/lib/db-ops/config/get-created-cwd.js +13 -0
  89. package/lib/db-ops/config/get-name.d.ts +8 -0
  90. package/lib/db-ops/config/get-name.js +14 -0
  91. package/lib/db-ops/config/info-column-allowlist.d.ts +7 -0
  92. package/lib/db-ops/config/info-column-allowlist.js +29 -0
  93. package/lib/db-ops/config/info-json-columns.d.ts +5 -0
  94. package/lib/db-ops/config/info-json-columns.js +11 -0
  95. package/lib/db-ops/config/set-config.d.ts +12 -0
  96. package/lib/db-ops/config/set-config.js +21 -0
  97. package/lib/db-ops/config/update-config.d.ts +17 -0
  98. package/lib/db-ops/config/update-config.js +36 -0
  99. package/lib/db-ops/console-logs/compute-console-log-hash.d.ts +19 -0
  100. package/lib/db-ops/console-logs/compute-console-log-hash.js +30 -0
  101. package/lib/db-ops/console-logs/replace-console-logs.d.ts +34 -0
  102. package/lib/db-ops/console-logs/replace-console-logs.js +123 -0
  103. package/lib/db-ops/console-logs/stringify-console-log-args.d.ts +16 -0
  104. package/lib/db-ops/console-logs/stringify-console-log-args.js +26 -0
  105. package/lib/db-ops/console-logs/types.d.ts +38 -0
  106. package/lib/db-ops/console-logs/types.js +1 -0
  107. package/lib/db-ops/console-logs/upsert-console-log-item.d.ts +29 -0
  108. package/lib/db-ops/console-logs/upsert-console-log-item.js +52 -0
  109. package/lib/db-ops/dedupe-cap/accumulate-dedupe-cap-rejected-count.d.ts +18 -0
  110. package/lib/db-ops/dedupe-cap/accumulate-dedupe-cap-rejected-count.js +23 -0
  111. package/lib/db-ops/dedupe-cap/finalize-dedupe-cap-event.d.ts +12 -0
  112. package/lib/db-ops/dedupe-cap/finalize-dedupe-cap-event.js +15 -0
  113. package/lib/db-ops/dedupe-cap/insert-dedupe-cap-event.d.ts +14 -0
  114. package/lib/db-ops/dedupe-cap/insert-dedupe-cap-event.js +30 -0
  115. package/lib/db-ops/dedupe-cap/list-dedupe-cap-observations.d.ts +57 -0
  116. package/lib/db-ops/dedupe-cap/list-dedupe-cap-observations.js +87 -0
  117. package/lib/db-ops/dedupe-cap/list-dedupe-cap-shape-keys.d.ts +21 -0
  118. package/lib/db-ops/dedupe-cap/list-dedupe-cap-shape-keys.js +27 -0
  119. package/lib/db-ops/errors/insert-crawl-error.d.ts +15 -0
  120. package/lib/db-ops/errors/insert-crawl-error.js +21 -0
  121. package/lib/db-ops/errors/insert-page-error.d.ts +21 -0
  122. package/lib/db-ops/errors/insert-page-error.js +30 -0
  123. package/lib/db-ops/errors/list-dns-burned-host-candidates.d.ts +33 -0
  124. package/lib/db-ops/errors/list-dns-burned-host-candidates.js +158 -0
  125. package/lib/db-ops/html/read-page-html-blob.d.ts +17 -0
  126. package/lib/db-ops/html/read-page-html-blob.js +20 -0
  127. package/lib/db-ops/lifecycle/checkpoint.d.ts +8 -0
  128. package/lib/db-ops/lifecycle/checkpoint.js +9 -0
  129. package/lib/db-ops/lifecycle/destroy.d.ts +6 -0
  130. package/lib/db-ops/lifecycle/destroy.js +7 -0
  131. package/lib/db-ops/lifecycle/init.d.ts +58 -0
  132. package/lib/db-ops/lifecycle/init.js +122 -0
  133. package/lib/db-ops/list-reconcile/record-list-reconcile-run.d.ts +22 -0
  134. package/lib/db-ops/list-reconcile/record-list-reconcile-run.js +41 -0
  135. package/lib/db-ops/meta/get-audios-of-page.d.ts +11 -0
  136. package/lib/db-ops/meta/get-audios-of-page.js +15 -0
  137. package/lib/db-ops/meta/get-buttons-of-page.d.ts +11 -0
  138. package/lib/db-ops/meta/get-buttons-of-page.js +15 -0
  139. package/lib/db-ops/meta/get-canvases-of-page.d.ts +11 -0
  140. package/lib/db-ops/meta/get-canvases-of-page.js +15 -0
  141. package/lib/db-ops/meta/get-custom-elements-of-page.d.ts +11 -0
  142. package/lib/db-ops/meta/get-custom-elements-of-page.js +15 -0
  143. package/lib/db-ops/meta/get-headings-of-page.d.ts +11 -0
  144. package/lib/db-ops/meta/get-headings-of-page.js +15 -0
  145. package/lib/db-ops/meta/get-iframes-of-page.d.ts +11 -0
  146. package/lib/db-ops/meta/get-iframes-of-page.js +15 -0
  147. package/lib/db-ops/meta/get-jsonld-of-page.d.ts +13 -0
  148. package/lib/db-ops/meta/get-jsonld-of-page.js +27 -0
  149. package/lib/db-ops/meta/get-main-content-images-of-page.d.ts +11 -0
  150. package/lib/db-ops/meta/get-main-content-images-of-page.js +15 -0
  151. package/lib/db-ops/meta/get-main-content-tables-of-page.d.ts +11 -0
  152. package/lib/db-ops/meta/get-main-content-tables-of-page.js +15 -0
  153. package/lib/db-ops/meta/get-page-technologies-of-page.d.ts +11 -0
  154. package/lib/db-ops/meta/get-page-technologies-of-page.js +15 -0
  155. package/lib/db-ops/meta/get-technology-signals-of-page.d.ts +11 -0
  156. package/lib/db-ops/meta/get-technology-signals-of-page.js +15 -0
  157. package/lib/db-ops/meta/get-videos-of-page.d.ts +11 -0
  158. package/lib/db-ops/meta/get-videos-of-page.js +15 -0
  159. package/lib/db-ops/outages/close-network-outage.d.ts +12 -0
  160. package/lib/db-ops/outages/close-network-outage.js +15 -0
  161. package/lib/db-ops/outages/close-stale-open-network-outages.d.ts +26 -0
  162. package/lib/db-ops/outages/close-stale-open-network-outages.js +42 -0
  163. package/lib/db-ops/outages/compute-outage-clamp-timestamp.d.ts +26 -0
  164. package/lib/db-ops/outages/compute-outage-clamp-timestamp.js +31 -0
  165. package/lib/db-ops/outages/insert-network-outage.d.ts +14 -0
  166. package/lib/db-ops/outages/insert-network-outage.js +29 -0
  167. package/lib/db-ops/outages/list-network-outages.d.ts +28 -0
  168. package/lib/db-ops/outages/list-network-outages.js +42 -0
  169. package/lib/db-ops/pages/order/set-url-order.d.ts +13 -0
  170. package/lib/db-ops/pages/order/set-url-order.js +38 -0
  171. package/lib/db-ops/pages/read/build-page-query.d.ts +18 -0
  172. package/lib/db-ops/pages/read/build-page-query.js +40 -0
  173. package/lib/db-ops/pages/read/get-crawling-state.d.ts +117 -0
  174. package/lib/db-ops/pages/read/get-crawling-state.js +161 -0
  175. package/lib/db-ops/pages/read/get-existing-page-urls.d.ts +15 -0
  176. package/lib/db-ops/pages/read/get-existing-page-urls.js +30 -0
  177. package/lib/db-ops/pages/read/get-page-count.d.ts +12 -0
  178. package/lib/db-ops/pages/read/get-page-count.js +21 -0
  179. package/lib/db-ops/pages/read/get-page-source-by-url.d.ts +24 -0
  180. package/lib/db-ops/pages/read/get-page-source-by-url.js +28 -0
  181. package/lib/db-ops/pages/read/get-pages-with-rels.d.ts +38 -0
  182. package/lib/db-ops/pages/read/get-pages-with-rels.js +107 -0
  183. package/lib/db-ops/pages/read/get-pages.d.ts +11 -0
  184. package/lib/db-ops/pages/read/get-pages.js +51 -0
  185. package/lib/db-ops/pages/read/get-scraped-html-page-count.d.ts +18 -0
  186. package/lib/db-ops/pages/read/get-scraped-html-page-count.js +25 -0
  187. package/lib/db-ops/pages/read/reconstruct-page-rows.d.ts +31 -0
  188. package/lib/db-ops/pages/read/reconstruct-page-rows.js +32 -0
  189. package/lib/db-ops/pages/reset/clear-page-derived-rows.d.ts +20 -0
  190. package/lib/db-ops/pages/reset/clear-page-derived-rows.js +37 -0
  191. package/lib/db-ops/pages/reset/repromote-external-pages.d.ts +30 -0
  192. package/lib/db-ops/pages/reset/repromote-external-pages.js +91 -0
  193. package/lib/db-ops/pages/reset/reset-failed-pages.d.ts +88 -0
  194. package/lib/db-ops/pages/reset/reset-failed-pages.js +216 -0
  195. package/lib/db-ops/pages/reset/reset-pages-by-urls.d.ts +80 -0
  196. package/lib/db-ops/pages/reset/reset-pages-by-urls.js +151 -0
  197. package/lib/db-ops/pages/reset/retryable-image-scan-codes.d.ts +24 -0
  198. package/lib/db-ops/pages/reset/retryable-image-scan-codes.js +24 -0
  199. package/lib/db-ops/pages/write/insert-audios.d.ts +14 -0
  200. package/lib/db-ops/pages/write/insert-audios.js +25 -0
  201. package/lib/db-ops/pages/write/insert-buttons.d.ts +14 -0
  202. package/lib/db-ops/pages/write/insert-buttons.js +29 -0
  203. package/lib/db-ops/pages/write/insert-canvases.d.ts +14 -0
  204. package/lib/db-ops/pages/write/insert-canvases.js +26 -0
  205. package/lib/db-ops/pages/write/insert-custom-elements.d.ts +27 -0
  206. package/lib/db-ops/pages/write/insert-custom-elements.js +40 -0
  207. package/lib/db-ops/pages/write/insert-headings.d.ts +15 -0
  208. package/lib/db-ops/pages/write/insert-headings.js +27 -0
  209. package/lib/db-ops/pages/write/insert-iframes.d.ts +14 -0
  210. package/lib/db-ops/pages/write/insert-iframes.js +28 -0
  211. package/lib/db-ops/pages/write/insert-inventory-content-items.d.ts +38 -0
  212. package/lib/db-ops/pages/write/insert-inventory-content-items.js +60 -0
  213. package/lib/db-ops/pages/write/insert-inventory-seeds.d.ts +36 -0
  214. package/lib/db-ops/pages/write/insert-inventory-seeds.js +48 -0
  215. package/lib/db-ops/pages/write/insert-inventory-skipped-pages.d.ts +42 -0
  216. package/lib/db-ops/pages/write/insert-inventory-skipped-pages.js +56 -0
  217. package/lib/db-ops/pages/write/insert-jsonld.d.ts +17 -0
  218. package/lib/db-ops/pages/write/insert-jsonld.js +49 -0
  219. package/lib/db-ops/pages/write/insert-main-content-images.d.ts +20 -0
  220. package/lib/db-ops/pages/write/insert-main-content-images.js +32 -0
  221. package/lib/db-ops/pages/write/insert-main-content-tables.d.ts +14 -0
  222. package/lib/db-ops/pages/write/insert-main-content-tables.js +29 -0
  223. package/lib/db-ops/pages/write/insert-page.d.ts +56 -0
  224. package/lib/db-ops/pages/write/insert-page.js +259 -0
  225. package/lib/db-ops/pages/write/insert-technologies.d.ts +25 -0
  226. package/lib/db-ops/pages/write/insert-technologies.js +45 -0
  227. package/lib/db-ops/pages/write/insert-videos.d.ts +14 -0
  228. package/lib/db-ops/pages/write/insert-videos.js +28 -0
  229. package/lib/db-ops/pages/write/link-redirect-sources.d.ts +42 -0
  230. package/lib/db-ops/pages/write/link-redirect-sources.js +101 -0
  231. package/lib/db-ops/pages/write/record-redirect.d.ts +35 -0
  232. package/lib/db-ops/pages/write/record-redirect.js +100 -0
  233. package/lib/db-ops/pages/write/set-skipped-page.d.ts +13 -0
  234. package/lib/db-ops/pages/write/set-skipped-page.js +24 -0
  235. package/lib/db-ops/pages/write/update-page.d.ts +40 -0
  236. package/lib/db-ops/pages/write/update-page.js +419 -0
  237. package/lib/db-ops/pages/write/write-page-html-blob.d.ts +19 -0
  238. package/lib/db-ops/pages/write/write-page-html-blob.js +41 -0
  239. package/lib/db-ops/referrers/get-redirects-for-pages.d.ts +9 -0
  240. package/lib/db-ops/referrers/get-redirects-for-pages.js +15 -0
  241. package/lib/db-ops/referrers/get-referrers-of-page.d.ts +17 -0
  242. package/lib/db-ops/referrers/get-referrers-of-page.js +32 -0
  243. package/lib/db-ops/referrers/get-referrers-of-resource.d.ts +8 -0
  244. package/lib/db-ops/referrers/get-referrers-of-resource.js +15 -0
  245. package/lib/db-ops/resources/build-resource-query.d.ts +25 -0
  246. package/lib/db-ops/resources/build-resource-query.js +29 -0
  247. package/lib/db-ops/resources/get-existing-resource-urls.d.ts +9 -0
  248. package/lib/db-ops/resources/get-existing-resource-urls.js +24 -0
  249. package/lib/db-ops/resources/get-resource-by-url.d.ts +13 -0
  250. package/lib/db-ops/resources/get-resource-by-url.js +22 -0
  251. package/lib/db-ops/resources/get-resource-url-list.d.ts +17 -0
  252. package/lib/db-ops/resources/get-resource-url-list.js +26 -0
  253. package/lib/db-ops/resources/get-resources.d.ts +8 -0
  254. package/lib/db-ops/resources/get-resources.js +11 -0
  255. package/lib/db-ops/resources/insert-inventory-resources.d.ts +24 -0
  256. package/lib/db-ops/resources/insert-inventory-resources.js +64 -0
  257. package/lib/db-ops/resources/insert-resource-referrers.d.ts +15 -0
  258. package/lib/db-ops/resources/insert-resource-referrers.js +54 -0
  259. package/lib/db-ops/resources/insert-resource.d.ts +34 -0
  260. package/lib/db-ops/resources/insert-resource.js +73 -0
  261. package/lib/db-ops/resources/reconstruct-resource-rows.d.ts +26 -0
  262. package/lib/db-ops/resources/reconstruct-resource-rows.js +30 -0
  263. package/lib/db-ops/templates/assign-template-labels.d.ts +60 -0
  264. package/lib/db-ops/templates/assign-template-labels.js +187 -0
  265. package/lib/db-ops/templates/replace-page-templates.d.ts +44 -0
  266. package/lib/db-ops/templates/replace-page-templates.js +174 -0
  267. package/lib/db-ops/templates/serialize-template-cluster-reason.d.ts +16 -0
  268. package/lib/db-ops/templates/serialize-template-cluster-reason.js +17 -0
  269. package/lib/db-ops/templates/types.d.ts +103 -0
  270. package/lib/db-ops/templates/types.js +1 -0
  271. package/lib/debug.d.ts +8 -0
  272. package/lib/debug.js +9 -0
  273. package/lib/decode-html-blob.d.ts +20 -0
  274. package/lib/decode-html-blob.js +23 -0
  275. package/lib/decode-page-html-blob-bytes.d.ts +25 -0
  276. package/lib/decode-page-html-blob-bytes.js +29 -0
  277. package/lib/decode-stored-blob-bytes.d.ts +25 -0
  278. package/lib/decode-stored-blob-bytes.js +47 -0
  279. package/lib/derive-lineage-from-parent.d.ts +37 -0
  280. package/lib/derive-lineage-from-parent.js +42 -0
  281. package/lib/drop-legacy-tables.d.ts +45 -0
  282. package/lib/drop-legacy-tables.js +56 -0
  283. package/lib/error-kind/classify-error-kind.d.ts +20 -0
  284. package/lib/error-kind/classify-error-kind.js +136 -0
  285. package/lib/error-kind/network-related-error-kinds.d.ts +23 -0
  286. package/lib/error-kind/network-related-error-kinds.js +28 -0
  287. package/lib/error-kind/permanent-error-kinds.d.ts +48 -0
  288. package/lib/error-kind/permanent-error-kinds.js +54 -0
  289. package/lib/error-kind/types.d.ts +54 -0
  290. package/lib/error-kind/types.js +1 -0
  291. package/lib/filesystem/append-text.d.ts +9 -0
  292. package/lib/filesystem/append-text.js +14 -0
  293. package/lib/filesystem/copy-dir-sync.d.ts +6 -0
  294. package/lib/filesystem/copy-dir-sync.js +9 -0
  295. package/lib/filesystem/copy-dir.d.ts +7 -0
  296. package/lib/filesystem/copy-dir.js +13 -0
  297. package/lib/filesystem/copy-file-with-progress.d.ts +20 -0
  298. package/lib/filesystem/copy-file-with-progress.js +34 -0
  299. package/lib/filesystem/exists.d.ts +6 -0
  300. package/lib/filesystem/exists.js +9 -0
  301. package/lib/filesystem/get-file-list.d.ts +8 -0
  302. package/lib/filesystem/get-file-list.js +12 -0
  303. package/lib/filesystem/is-dir.d.ts +6 -0
  304. package/lib/filesystem/is-dir.js +10 -0
  305. package/lib/filesystem/mkdir.d.ts +8 -0
  306. package/lib/filesystem/mkdir.js +15 -0
  307. package/lib/filesystem/output-binary.d.ts +12 -0
  308. package/lib/filesystem/output-binary.js +17 -0
  309. package/lib/filesystem/output-json.d.ts +9 -0
  310. package/lib/filesystem/output-json.js +14 -0
  311. package/lib/filesystem/output-text.d.ts +11 -0
  312. package/lib/filesystem/output-text.js +32 -0
  313. package/lib/filesystem/parse-pax-path.d.ts +18 -0
  314. package/lib/filesystem/parse-pax-path.js +47 -0
  315. package/lib/filesystem/parse-tar-size-field.d.ts +13 -0
  316. package/lib/filesystem/parse-tar-size-field.js +40 -0
  317. package/lib/filesystem/peek-tar-top-dir.d.ts +35 -0
  318. package/lib/filesystem/peek-tar-top-dir.js +215 -0
  319. package/lib/filesystem/read-json.d.ts +7 -0
  320. package/lib/filesystem/read-json.js +11 -0
  321. package/lib/filesystem/read-text.d.ts +6 -0
  322. package/lib/filesystem/read-text.js +10 -0
  323. package/lib/filesystem/readline.d.ts +11 -0
  324. package/lib/filesystem/readline.js +26 -0
  325. package/lib/filesystem/remove.d.ts +5 -0
  326. package/lib/filesystem/remove.js +10 -0
  327. package/lib/filesystem/rename.d.ts +16 -0
  328. package/lib/filesystem/rename.js +48 -0
  329. package/lib/filesystem/tar.d.ts +23 -0
  330. package/lib/filesystem/tar.js +78 -0
  331. package/lib/filesystem/untar.d.ts +33 -0
  332. package/lib/filesystem/untar.js +84 -0
  333. package/lib/get-failed-page-messages.d.ts +56 -0
  334. package/lib/get-failed-page-messages.js +146 -0
  335. package/lib/get-json.d.ts +10 -0
  336. package/lib/get-json.js +25 -0
  337. package/lib/html-snapshot/match-selector-html.d.ts +25 -0
  338. package/lib/html-snapshot/match-selector-html.js +28 -0
  339. package/lib/html-snapshot/match-selector-snapshots.d.ts +33 -0
  340. package/lib/html-snapshot/match-selector-snapshots.js +33 -0
  341. package/lib/html-snapshot/search-html-document.d.ts +29 -0
  342. package/lib/html-snapshot/search-html-document.js +27 -0
  343. package/lib/html-snapshot/search-html-snapshots.d.ts +36 -0
  344. package/lib/html-snapshot/search-html-snapshots.js +35 -0
  345. package/lib/html-snapshot/types.d.ts +111 -0
  346. package/lib/html-snapshot/types.js +7 -0
  347. package/lib/html-snapshot/validate-search-pattern.d.ts +15 -0
  348. package/lib/html-snapshot/validate-search-pattern.js +17 -0
  349. package/lib/init-schema.d.ts +48 -0
  350. package/lib/init-schema.js +124 -0
  351. package/lib/is-inventory-source.d.ts +21 -0
  352. package/lib/is-inventory-source.js +22 -0
  353. package/lib/is-within-outage-window.d.ts +49 -0
  354. package/lib/is-within-outage-window.js +33 -0
  355. package/lib/isolated-cluster/create-isolated-cluster-run.d.ts +24 -0
  356. package/lib/isolated-cluster/create-isolated-cluster-run.js +26 -0
  357. package/lib/libsql-dialect.d.ts +115 -0
  358. package/lib/libsql-dialect.js +116 -0
  359. package/lib/limited-page-ids.d.ts +9 -0
  360. package/lib/limited-page-ids.js +18 -0
  361. package/lib/meta/assert-compatible-version.d.ts +60 -0
  362. package/lib/meta/assert-compatible-version.js +93 -0
  363. package/lib/meta/classify-jsonld-type.d.ts +23 -0
  364. package/lib/meta/classify-jsonld-type.js +43 -0
  365. package/lib/meta/compare-semver.d.ts +23 -0
  366. package/lib/meta/compare-semver.js +51 -0
  367. package/lib/meta/compute-main-contents-denormalized.d.ts +41 -0
  368. package/lib/meta/compute-main-contents-denormalized.js +88 -0
  369. package/lib/meta/compute-page-denormalized.d.ts +20 -0
  370. package/lib/meta/compute-page-denormalized.js +35 -0
  371. package/lib/meta/derive-flat-from-meta.d.ts +34 -0
  372. package/lib/meta/derive-flat-from-meta.js +158 -0
  373. package/lib/meta/derive-meta-extras.d.ts +20 -0
  374. package/lib/meta/derive-meta-extras.js +23 -0
  375. package/lib/meta/extract-tags-for-archive.d.ts +17 -0
  376. package/lib/meta/extract-tags-for-archive.js +36 -0
  377. package/lib/meta/parse-main-content-class-list.d.ts +19 -0
  378. package/lib/meta/parse-main-content-class-list.js +34 -0
  379. package/lib/meta/summarize-jsonld.d.ts +17 -0
  380. package/lib/meta/summarize-jsonld.js +29 -0
  381. package/lib/meta/technologies/combine-technology-confidence.d.ts +46 -0
  382. package/lib/meta/technologies/combine-technology-confidence.js +93 -0
  383. package/lib/meta/technologies/convert-legacy-page-tags-to-inserts.d.ts +45 -0
  384. package/lib/meta/technologies/convert-legacy-page-tags-to-inserts.js +53 -0
  385. package/lib/meta/technologies/convert-tag-row-to-wappalyzer-signal.d.ts +33 -0
  386. package/lib/meta/technologies/convert-tag-row-to-wappalyzer-signal.js +46 -0
  387. package/lib/meta/technologies/extract-technologies-for-archive.d.ts +33 -0
  388. package/lib/meta/technologies/extract-technologies-for-archive.js +30 -0
  389. package/lib/meta/technologies/match-js-license-comment-signal.d.ts +21 -0
  390. package/lib/meta/technologies/match-js-license-comment-signal.js +23 -0
  391. package/lib/meta/technologies/match-structural-technology-signals.d.ts +26 -0
  392. package/lib/meta/technologies/match-structural-technology-signals.js +48 -0
  393. package/lib/meta/technologies/normalize-wappalyzer-entries.d.ts +25 -0
  394. package/lib/meta/technologies/normalize-wappalyzer-entries.js +35 -0
  395. package/lib/meta/technologies/technology-signal-definitions.d.ts +44 -0
  396. package/lib/meta/technologies/technology-signal-definitions.js +60 -0
  397. package/lib/meta/technologies/types.d.ts +70 -0
  398. package/lib/meta/technologies/types.js +13 -0
  399. package/lib/meta/types.d.ts +1490 -0
  400. package/lib/meta/types.js +65 -0
  401. package/lib/migrate-content-items-alias-of-id.d.ts +52 -0
  402. package/lib/migrate-content-items-alias-of-id.js +69 -0
  403. package/lib/migrate-content-items-dedupe-cap-event-id.d.ts +46 -0
  404. package/lib/migrate-content-items-dedupe-cap-event-id.js +62 -0
  405. package/lib/migrate-content-items-is-metadata-only.d.ts +44 -0
  406. package/lib/migrate-content-items-is-metadata-only.js +60 -0
  407. package/lib/migrate-entity-tables.d.ts +55 -0
  408. package/lib/migrate-entity-tables.js +66 -0
  409. package/lib/migrate-info-created-cwd.d.ts +17 -0
  410. package/lib/migrate-info-created-cwd.js +36 -0
  411. package/lib/migrate-info-main-content-selector.d.ts +16 -0
  412. package/lib/migrate-info-main-content-selector.js +35 -0
  413. package/lib/migrate-info-request-header-names.d.ts +16 -0
  414. package/lib/migrate-info-request-header-names.js +35 -0
  415. package/lib/migrate-info-roots.d.ts +20 -0
  416. package/lib/migrate-info-roots.js +52 -0
  417. package/lib/migrate-inventory-runs-to-list-reconcile-runs.d.ts +34 -0
  418. package/lib/migrate-inventory-runs-to-list-reconcile-runs.js +51 -0
  419. package/lib/migrate-list-reconcile-runs-exclude-skipped.d.ts +25 -0
  420. package/lib/migrate-list-reconcile-runs-exclude-skipped.js +44 -0
  421. package/lib/migrate-list-reconcile-runs-invalid-skipped.d.ts +16 -0
  422. package/lib/migrate-list-reconcile-runs-invalid-skipped.js +35 -0
  423. package/lib/migrate-main-contents-columns.d.ts +26 -0
  424. package/lib/migrate-main-contents-columns.js +61 -0
  425. package/lib/migrate-page-meta-body-hash.d.ts +44 -0
  426. package/lib/migrate-page-meta-body-hash.js +63 -0
  427. package/lib/migrate-page-meta-console-error-count.d.ts +27 -0
  428. package/lib/migrate-page-meta-console-error-count.js +45 -0
  429. package/lib/migrate-page-meta-custom-element-count.d.ts +33 -0
  430. package/lib/migrate-page-meta-custom-element-count.js +51 -0
  431. package/lib/migrate-page-meta-image-scan.d.ts +27 -0
  432. package/lib/migrate-page-meta-image-scan.js +52 -0
  433. package/lib/migrate-page-tags-to-page-technologies.d.ts +39 -0
  434. package/lib/migrate-page-tags-to-page-technologies.js +79 -0
  435. package/lib/migrate-ref-tables.d.ts +25 -0
  436. package/lib/migrate-ref-tables.js +38 -0
  437. package/lib/native-executor/check-native-executor-config.d.ts +17 -0
  438. package/lib/native-executor/check-native-executor-config.js +20 -0
  439. package/lib/page-meta-column-maps.d.ts +32 -0
  440. package/lib/page-meta-column-maps.js +43 -0
  441. package/lib/page.d.ts +546 -0
  442. package/lib/page.js +764 -0
  443. package/lib/peek-archive-lock.d.ts +40 -0
  444. package/lib/peek-archive-lock.js +62 -0
  445. package/lib/populate-entity-tables/collapse-anchor-rows.d.ts +41 -0
  446. package/lib/populate-entity-tables/collapse-anchor-rows.js +87 -0
  447. package/lib/populate-entity-tables/derive-dom-path.d.ts +35 -0
  448. package/lib/populate-entity-tables/derive-dom-path.js +72 -0
  449. package/lib/populate-entity-tables/is-blob-ref-value.d.ts +16 -0
  450. package/lib/populate-entity-tables/is-blob-ref-value.js +19 -0
  451. package/lib/populate-entity-tables/match-images-to-dom-paths.d.ts +66 -0
  452. package/lib/populate-entity-tables/match-images-to-dom-paths.js +96 -0
  453. package/lib/populate-entity-tables/populate-anchor-edges.d.ts +33 -0
  454. package/lib/populate-entity-tables/populate-anchor-edges.js +153 -0
  455. package/lib/populate-entity-tables/populate-content-items.d.ts +40 -0
  456. package/lib/populate-entity-tables/populate-content-items.js +141 -0
  457. package/lib/populate-entity-tables/populate-entities.d.ts +81 -0
  458. package/lib/populate-entity-tables/populate-entities.js +110 -0
  459. package/lib/populate-entity-tables/populate-image-items.d.ts +91 -0
  460. package/lib/populate-entity-tables/populate-image-items.js +226 -0
  461. package/lib/populate-entity-tables/populate-page-meta.d.ts +33 -0
  462. package/lib/populate-entity-tables/populate-page-meta.js +267 -0
  463. package/lib/populate-entity-tables/populate-resource-items.d.ts +22 -0
  464. package/lib/populate-entity-tables/populate-resource-items.js +114 -0
  465. package/lib/populate-entity-tables/populate-resource-ref-edges.d.ts +31 -0
  466. package/lib/populate-entity-tables/populate-resource-ref-edges.js +33 -0
  467. package/lib/populate-entity-tables/resolve-blob-refs.d.ts +31 -0
  468. package/lib/populate-entity-tables/resolve-blob-refs.js +100 -0
  469. package/lib/populate-entity-tables/resolve-content-type-refs.d.ts +22 -0
  470. package/lib/populate-entity-tables/resolve-content-type-refs.js +27 -0
  471. package/lib/populate-entity-tables/resolve-header-sets.d.ts +49 -0
  472. package/lib/populate-entity-tables/resolve-header-sets.js +122 -0
  473. package/lib/populate-entity-tables/resolve-json-refs.d.ts +25 -0
  474. package/lib/populate-entity-tables/resolve-json-refs.js +67 -0
  475. package/lib/populate-entity-tables/resolve-text-refs.d.ts +30 -0
  476. package/lib/populate-entity-tables/resolve-text-refs.js +61 -0
  477. package/lib/populate-entity-tables/resolve-url-or-blob-from-maps.d.ts +21 -0
  478. package/lib/populate-entity-tables/resolve-url-or-blob-from-maps.js +27 -0
  479. package/lib/populate-entity-tables/resolve-url-refs.d.ts +33 -0
  480. package/lib/populate-entity-tables/resolve-url-refs.js +60 -0
  481. package/lib/populate-entity-tables/test-utils/count-rows.d.ts +17 -0
  482. package/lib/populate-entity-tables/test-utils/count-rows.js +20 -0
  483. package/lib/populate-entity-tables/test-utils/seed-content-items.d.ts +25 -0
  484. package/lib/populate-entity-tables/test-utils/seed-content-items.js +42 -0
  485. package/lib/populate-entity-tables/test-utils/setup-entities-db.d.ts +30 -0
  486. package/lib/populate-entity-tables/test-utils/setup-entities-db.js +175 -0
  487. package/lib/populate-entity-tables/types.d.ts +157 -0
  488. package/lib/populate-entity-tables/types.js +12 -0
  489. package/lib/populate-entity-tables/upsert-text-refs.d.ts +38 -0
  490. package/lib/populate-entity-tables/upsert-text-refs.js +78 -0
  491. package/lib/populate-ref-tables/classify-content-type.d.ts +16 -0
  492. package/lib/populate-ref-tables/classify-content-type.js +52 -0
  493. package/lib/populate-ref-tables/compute-content-hash.d.ts +22 -0
  494. package/lib/populate-ref-tables/compute-content-hash.js +26 -0
  495. package/lib/populate-ref-tables/compute-header-flags.d.ts +16 -0
  496. package/lib/populate-ref-tables/compute-header-flags.js +70 -0
  497. package/lib/populate-ref-tables/content-type-rules.d.ts +38 -0
  498. package/lib/populate-ref-tables/content-type-rules.js +133 -0
  499. package/lib/populate-ref-tables/create-header-table-caches.d.ts +25 -0
  500. package/lib/populate-ref-tables/create-header-table-caches.js +49 -0
  501. package/lib/populate-ref-tables/data-uri-url-refs-limit.d.ts +15 -0
  502. package/lib/populate-ref-tables/data-uri-url-refs-limit.js +15 -0
  503. package/lib/populate-ref-tables/decode-data-uri.d.ts +21 -0
  504. package/lib/populate-ref-tables/decode-data-uri.js +126 -0
  505. package/lib/populate-ref-tables/decompose-header-set.d.ts +29 -0
  506. package/lib/populate-ref-tables/decompose-header-set.js +157 -0
  507. package/lib/populate-ref-tables/decompose-url.d.ts +25 -0
  508. package/lib/populate-ref-tables/decompose-url.js +70 -0
  509. package/lib/populate-ref-tables/header-stability.d.ts +19 -0
  510. package/lib/populate-ref-tables/header-stability.js +22 -0
  511. package/lib/populate-ref-tables/header-value-cache-key.d.ts +17 -0
  512. package/lib/populate-ref-tables/header-value-cache-key.js +19 -0
  513. package/lib/populate-ref-tables/normalize-mime.d.ts +24 -0
  514. package/lib/populate-ref-tables/normalize-mime.js +36 -0
  515. package/lib/populate-ref-tables/populate-blob-refs.d.ts +38 -0
  516. package/lib/populate-ref-tables/populate-blob-refs.js +134 -0
  517. package/lib/populate-ref-tables/populate-content-type-refs.d.ts +27 -0
  518. package/lib/populate-ref-tables/populate-content-type-refs.js +70 -0
  519. package/lib/populate-ref-tables/populate-header-tables.d.ts +35 -0
  520. package/lib/populate-ref-tables/populate-header-tables.js +80 -0
  521. package/lib/populate-ref-tables/populate-json-refs.d.ts +29 -0
  522. package/lib/populate-ref-tables/populate-json-refs.js +101 -0
  523. package/lib/populate-ref-tables/populate-refs.d.ts +51 -0
  524. package/lib/populate-ref-tables/populate-refs.js +62 -0
  525. package/lib/populate-ref-tables/populate-text-refs.d.ts +32 -0
  526. package/lib/populate-ref-tables/populate-text-refs.js +133 -0
  527. package/lib/populate-ref-tables/populate-url-refs.d.ts +28 -0
  528. package/lib/populate-ref-tables/populate-url-refs.js +148 -0
  529. package/lib/populate-ref-tables/test-utils/count-rows.d.ts +15 -0
  530. package/lib/populate-ref-tables/test-utils/count-rows.js +17 -0
  531. package/lib/populate-ref-tables/types.d.ts +197 -0
  532. package/lib/populate-ref-tables/types.js +7 -0
  533. package/lib/populate-ref-tables/upsert-one-header-set.d.ts +34 -0
  534. package/lib/populate-ref-tables/upsert-one-header-set.js +208 -0
  535. package/lib/populate-ref-tables/volatile-header-names.d.ts +20 -0
  536. package/lib/populate-ref-tables/volatile-header-names.js +33 -0
  537. package/lib/redirect-table.d.ts +9 -0
  538. package/lib/redirect-table.js +28 -0
  539. package/lib/release-finished-statements.d.ts +42 -0
  540. package/lib/release-finished-statements.js +45 -0
  541. package/lib/resolve-redirect-chain.d.ts +33 -0
  542. package/lib/resolve-redirect-chain.js +27 -0
  543. package/lib/resource.d.ts +46 -0
  544. package/lib/resource.js +62 -0
  545. package/lib/retarget-legacy-fk-tables.d.ts +61 -0
  546. package/lib/retarget-legacy-fk-tables.js +137 -0
  547. package/lib/safe-path.d.ts +9 -0
  548. package/lib/safe-path.js +17 -0
  549. package/lib/scope/build-scope-map.d.ts +21 -0
  550. package/lib/scope/build-scope-map.js +32 -0
  551. package/lib/scope/find-scope-entry.d.ts +25 -0
  552. package/lib/scope/find-scope-entry.js +45 -0
  553. package/lib/template-classification/classify-archive-page-templates.d.ts +42 -0
  554. package/lib/template-classification/classify-archive-page-templates.js +70 -0
  555. package/lib/template-classification/classify-page-templates.d.ts +33 -0
  556. package/lib/template-classification/classify-page-templates.js +60 -0
  557. package/lib/template-classification/collect-page-ids-with-html.d.ts +24 -0
  558. package/lib/template-classification/collect-page-ids-with-html.js +30 -0
  559. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  560. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  561. package/lib/template-classification/create-content-root-hint.d.ts +41 -0
  562. package/lib/template-classification/create-content-root-hint.js +51 -0
  563. package/lib/template-classification/create-page-cluster-factory.d.ts +36 -0
  564. package/lib/template-classification/create-page-cluster-factory.js +52 -0
  565. package/lib/template-classification/load-page-cluster-candidates.d.ts +32 -0
  566. package/lib/template-classification/load-page-cluster-candidates.js +93 -0
  567. package/lib/template-classification/page-cluster/resolve-page-cluster-keys.d.ts +34 -0
  568. package/lib/template-classification/page-cluster/resolve-page-cluster-keys.js +236 -0
  569. package/lib/template-classification/page-cluster/types.d.ts +123 -0
  570. package/lib/template-classification/page-cluster/types.js +1 -0
  571. package/lib/template-classification/types.d.ts +234 -0
  572. package/lib/template-classification/types.js +1 -0
  573. package/lib/test-utils/build-full-schema-test-db.d.ts +34 -0
  574. package/lib/test-utils/build-full-schema-test-db.js +74 -0
  575. package/lib/test-utils/create-legacy-analysis-tables.d.ts +13 -0
  576. package/lib/test-utils/create-legacy-analysis-tables.js +37 -0
  577. package/lib/test-utils/fk-parent-tables.d.ts +15 -0
  578. package/lib/test-utils/fk-parent-tables.js +19 -0
  579. package/lib/test-utils/seed-content-item.d.ts +35 -0
  580. package/lib/test-utils/seed-content-item.js +42 -0
  581. package/lib/test-utils/setup-legacy-fk-db.d.ts +34 -0
  582. package/lib/test-utils/setup-legacy-fk-db.js +271 -0
  583. package/lib/transfer/attach-source-database.d.ts +31 -0
  584. package/lib/transfer/attach-source-database.js +40 -0
  585. package/lib/transfer/build-split-config.d.ts +30 -0
  586. package/lib/transfer/build-split-config.js +42 -0
  587. package/lib/transfer/clear-replaced-page-rows.d.ts +23 -0
  588. package/lib/transfer/clear-replaced-page-rows.js +61 -0
  589. package/lib/transfer/concat-archives.d.ts +55 -0
  590. package/lib/transfer/concat-archives.js +95 -0
  591. package/lib/transfer/concat-source-transfer-phases.d.ts +10 -0
  592. package/lib/transfer/concat-source-transfer-phases.js +17 -0
  593. package/lib/transfer/content-item-rank-sql.d.ts +21 -0
  594. package/lib/transfer/content-item-rank-sql.js +23 -0
  595. package/lib/transfer/copy-anchor-edges.d.ts +28 -0
  596. package/lib/transfer/copy-anchor-edges.js +42 -0
  597. package/lib/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  598. package/lib/transfer/copy-dictionaries-for-concat.js +81 -0
  599. package/lib/transfer/copy-dictionaries-for-split.d.ts +29 -0
  600. package/lib/transfer/copy-dictionaries-for-split.js +224 -0
  601. package/lib/transfer/copy-header-set-children.d.ts +27 -0
  602. package/lib/transfer/copy-header-set-children.js +51 -0
  603. package/lib/transfer/copy-image-items.d.ts +21 -0
  604. package/lib/transfer/copy-image-items.js +62 -0
  605. package/lib/transfer/copy-inventory-source-lists.d.ts +30 -0
  606. package/lib/transfer/copy-inventory-source-lists.js +61 -0
  607. package/lib/transfer/copy-journal-tables.d.ts +30 -0
  608. package/lib/transfer/copy-journal-tables.js +56 -0
  609. package/lib/transfer/copy-page-console-logs.d.ts +16 -0
  610. package/lib/transfer/copy-page-console-logs.js +27 -0
  611. package/lib/transfer/copy-page-html-blobs.d.ts +31 -0
  612. package/lib/transfer/copy-page-html-blobs.js +43 -0
  613. package/lib/transfer/copy-page-meta.d.ts +27 -0
  614. package/lib/transfer/copy-page-meta.js +68 -0
  615. package/lib/transfer/copy-page-template-clusters.d.ts +31 -0
  616. package/lib/transfer/copy-page-template-clusters.js +56 -0
  617. package/lib/transfer/copy-page-template-labels.d.ts +34 -0
  618. package/lib/transfer/copy-page-template-labels.js +88 -0
  619. package/lib/transfer/copy-resource-items.d.ts +29 -0
  620. package/lib/transfer/copy-resource-items.js +89 -0
  621. package/lib/transfer/copy-resource-ref-edges.d.ts +20 -0
  622. package/lib/transfer/copy-resource-ref-edges.js +33 -0
  623. package/lib/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  624. package/lib/transfer/copy-simple-page-scoped-tables.js +34 -0
  625. package/lib/transfer/count-external-pages-in-scope.d.ts +26 -0
  626. package/lib/transfer/count-external-pages-in-scope.js +40 -0
  627. package/lib/transfer/create-transfer-temp-tables.d.ts +30 -0
  628. package/lib/transfer/create-transfer-temp-tables.js +59 -0
  629. package/lib/transfer/dictionary-copy-specs.d.ts +32 -0
  630. package/lib/transfer/dictionary-copy-specs.js +28 -0
  631. package/lib/transfer/drop-transfer-temp-tables.d.ts +9 -0
  632. package/lib/transfer/drop-transfer-temp-tables.js +18 -0
  633. package/lib/transfer/flatten-redirect-chains.d.ts +44 -0
  634. package/lib/transfer/flatten-redirect-chains.js +74 -0
  635. package/lib/transfer/insert-content-items.d.ts +35 -0
  636. package/lib/transfer/insert-content-items.js +116 -0
  637. package/lib/transfer/list-transfer-columns.d.ts +35 -0
  638. package/lib/transfer/list-transfer-columns.js +45 -0
  639. package/lib/transfer/mark-in-scope-content-items.d.ts +31 -0
  640. package/lib/transfer/mark-in-scope-content-items.js +54 -0
  641. package/lib/transfer/merge-archive-configs.d.ts +51 -0
  642. package/lib/transfer/merge-archive-configs.js +85 -0
  643. package/lib/transfer/plan-content-items-for-concat.d.ts +33 -0
  644. package/lib/transfer/plan-content-items-for-concat.js +51 -0
  645. package/lib/transfer/plan-content-items-for-split.d.ts +42 -0
  646. package/lib/transfer/plan-content-items-for-split.js +83 -0
  647. package/lib/transfer/plan-resource-items.d.ts +40 -0
  648. package/lib/transfer/plan-resource-items.js +69 -0
  649. package/lib/transfer/quote-transfer-identifier.d.ts +18 -0
  650. package/lib/transfer/quote-transfer-identifier.js +20 -0
  651. package/lib/transfer/reclassify-resource-externality.d.ts +37 -0
  652. package/lib/transfer/reclassify-resource-externality.js +66 -0
  653. package/lib/transfer/remap-redirect-dest-ids.d.ts +34 -0
  654. package/lib/transfer/remap-redirect-dest-ids.js +51 -0
  655. package/lib/transfer/replace-content-items.d.ts +39 -0
  656. package/lib/transfer/replace-content-items.js +83 -0
  657. package/lib/transfer/simple-page-scoped-tables.d.ts +25 -0
  658. package/lib/transfer/simple-page-scoped-tables.js +38 -0
  659. package/lib/transfer/split-archive.d.ts +55 -0
  660. package/lib/transfer/split-archive.js +98 -0
  661. package/lib/transfer/split-source-transfer-phases.d.ts +11 -0
  662. package/lib/transfer/split-source-transfer-phases.js +18 -0
  663. package/lib/transfer/transfer-action.d.ts +34 -0
  664. package/lib/transfer/transfer-action.js +32 -0
  665. package/lib/transfer/transfer-archive-rows.d.ts +65 -0
  666. package/lib/transfer/transfer-archive-rows.js +156 -0
  667. package/lib/transfer/transfer-dictionary-tables.d.ts +12 -0
  668. package/lib/transfer/transfer-dictionary-tables.js +22 -0
  669. package/lib/transfer/transfer-post-phases.d.ts +10 -0
  670. package/lib/transfer/transfer-post-phases.js +13 -0
  671. package/lib/transfer/transfer-source-alias.d.ts +9 -0
  672. package/lib/transfer/transfer-source-alias.js +9 -0
  673. package/lib/transfer/types.d.ts +111 -0
  674. package/lib/transfer/types.js +35 -0
  675. package/lib/types.d.ts +772 -0
  676. package/lib/types.js +1 -0
  677. package/lib/url-alias/compute-tier-a-alias-key.d.ts +44 -0
  678. package/lib/url-alias/compute-tier-a-alias-key.js +47 -0
  679. package/lib/url-alias/compute-tier-b-alias-key.d.ts +23 -0
  680. package/lib/url-alias/compute-tier-b-alias-key.js +26 -0
  681. package/lib/url-alias/group-alias-candidates.d.ts +27 -0
  682. package/lib/url-alias/group-alias-candidates.js +29 -0
  683. package/lib/url-alias/types.d.ts +12 -0
  684. package/lib/url-alias/types.js +1 -0
  685. package/lib/url-pattern/compute-shape-key.d.ts +58 -0
  686. package/lib/url-pattern/compute-shape-key.js +129 -0
  687. package/lib/url-pattern/decompose-url.d.ts +33 -0
  688. package/lib/url-pattern/decompose-url.js +79 -0
  689. package/lib/url-pattern/reconstruct-url.d.ts +15 -0
  690. package/lib/url-pattern/reconstruct-url.js +33 -0
  691. package/lib/url-sort/compute-url-sort-ranks.d.ts +30 -0
  692. package/lib/url-sort/compute-url-sort-ranks.js +33 -0
  693. package/lib/utils/array/each-splitted.d.ts +10 -0
  694. package/lib/utils/array/each-splitted.js +14 -0
  695. package/lib/utils/debug.d.ts +8 -0
  696. package/lib/utils/debug.js +8 -0
  697. package/lib/utils/error/emit-error-with-retry.d.ts +40 -0
  698. package/lib/utils/error/emit-error-with-retry.js +44 -0
  699. package/lib/utils/error/emit-error.d.ts +39 -0
  700. package/lib/utils/error/emit-error.js +41 -0
  701. package/lib/utils/object/parse-response-headers.d.ts +12 -0
  702. package/lib/utils/object/parse-response-headers.js +26 -0
  703. package/lib/utils/object/redact-request-headers.d.ts +15 -0
  704. package/lib/utils/object/redact-request-headers.js +27 -0
  705. package/lib/utils/types/types.d.ts +383 -0
  706. package/lib/utils/types/types.js +1 -0
  707. package/lib/verify-migration/capture-rejection.d.ts +24 -0
  708. package/lib/verify-migration/capture-rejection.js +31 -0
  709. package/lib/verify-migration/check-anchor-edges-count.d.ts +34 -0
  710. package/lib/verify-migration/check-anchor-edges-count.js +72 -0
  711. package/lib/verify-migration/check-anchor-edges-sum.d.ts +13 -0
  712. package/lib/verify-migration/check-anchor-edges-sum.js +27 -0
  713. package/lib/verify-migration/check-content-items-count.d.ts +16 -0
  714. package/lib/verify-migration/check-content-items-count.js +30 -0
  715. package/lib/verify-migration/check-content-type-preservation.d.ts +22 -0
  716. package/lib/verify-migration/check-content-type-preservation.js +40 -0
  717. package/lib/verify-migration/check-foreign-key-integrity.d.ts +31 -0
  718. package/lib/verify-migration/check-foreign-key-integrity.js +47 -0
  719. package/lib/verify-migration/check-image-items-count.d.ts +12 -0
  720. package/lib/verify-migration/check-image-items-count.js +26 -0
  721. package/lib/verify-migration/check-page-meta-count.d.ts +15 -0
  722. package/lib/verify-migration/check-page-meta-count.js +31 -0
  723. package/lib/verify-migration/check-reader-parity.d.ts +23 -0
  724. package/lib/verify-migration/check-reader-parity.js +182 -0
  725. package/lib/verify-migration/check-resource-items-count.d.ts +17 -0
  726. package/lib/verify-migration/check-resource-items-count.js +33 -0
  727. package/lib/verify-migration/check-url-round-trip.d.ts +43 -0
  728. package/lib/verify-migration/check-url-round-trip.js +112 -0
  729. package/lib/verify-migration/types.d.ts +70 -0
  730. package/lib/verify-migration/types.js +63 -0
  731. package/lib/verify-migration/verify-migration.d.ts +41 -0
  732. package/lib/verify-migration/verify-migration.js +120 -0
  733. package/lib/with-bulk-write-pragmas.d.ts +51 -0
  734. package/lib/with-bulk-write-pragmas.js +132 -0
  735. package/lib/write-queue.d.ts +32 -0
  736. package/lib/write-queue.js +55 -0
  737. package/package.json +360 -5
package/lib/archive.js ADDED
@@ -0,0 +1,1056 @@
1
+ import path from 'node:path';
2
+ import { ArchiveAccessor } from './archive-accessor.js';
3
+ import { acquireArchiveLock } from './archive-lock.js';
4
+ import { computeArchiveCacheKey } from './cache/compute-archive-cache-key.js';
5
+ import { extractArchiveToCache } from './cache/extract-archive-to-cache.js';
6
+ import { getArchiveCacheRoot } from './cache/get-archive-cache-root.js';
7
+ import { resolveArchiveCacheDir } from './cache/resolve-archive-cache-dir.js';
8
+ import { Database } from './database.js';
9
+ import { dbLog, log, saveLog } from './debug.js';
10
+ import { appendText } from './filesystem/append-text.js';
11
+ import { exists } from './filesystem/exists.js';
12
+ import { isDir } from './filesystem/is-dir.js';
13
+ import { outputBinary } from './filesystem/output-binary.js';
14
+ import { peekTarTopDir } from './filesystem/peek-tar-top-dir.js';
15
+ import { remove } from './filesystem/remove.js';
16
+ import { rename } from './filesystem/rename.js';
17
+ import { tar } from './filesystem/tar.js';
18
+ import { untar } from './filesystem/untar.js';
19
+ import { safePath } from './safe-path.js';
20
+ import { redactRequestHeaders } from './utils/object/redact-request-headers.js';
21
+ /**
22
+ * Main archive class for creating, opening, resuming, and writing Nitpicker
23
+ * archive files (`.nitpicker`).
24
+ *
25
+ * An Archive wraps a SQLite database into a tar archive. HTML bodies live
26
+ * inside the same DB as zstd-compressed BLOBs (see #75), so `db.sqlite` is
27
+ * normally the tar's only entry — but it is not the only entry the format
28
+ * allows: {@link Archive.saveInventorySourceList} (a saved `--inventory`
29
+ * source list) adds plain files alongside it. It extends
30
+ * {@link ArchiveAccessor} to provide read access to stored data.
31
+ *
32
+ * Use the static factory methods ({@link Archive.create}, {@link Archive.open},
33
+ * {@link Archive.resume}, {@link Archive.connect}) to obtain instances.
34
+ * The constructor is private. Implements `Symbol.asyncDispose` (inherited
35
+ * from {@link ArchiveAccessor}) so callers can use `await using` instead of
36
+ * a manual `try`/`finally` around {@link close}.
37
+ * @example
38
+ * await using archive = await Archive.create({ filePath: '/path/to/site.nitpicker' });
39
+ * await archive.setConfig(config);
40
+ * const pageId = await archive.setPage(pageData);
41
+ * // Writes the `.nitpicker` tar (if absent), removes tmpDir, releases the
42
+ * // lock — all on scope exit, whether by fallthrough or thrown error.
43
+ */
44
+ export default class Archive extends ArchiveAccessor {
45
+ /**
46
+ * Promise tracking an in-progress {@link Archive.close} (or
47
+ * {@link Archive.releaseHandle}). Acts as the override's idempotency
48
+ * guard so a second call — e.g. from a signal handler racing the
49
+ * primary teardown — does not re-enter the destructive prologue
50
+ * (write/remove) on a half-mutated state.
51
+ */
52
+ #closeOnce = null;
53
+ /** The SQLite database instance for reading and writing crawl data. */
54
+ #db;
55
+ /** Absolute path to the output `.nitpicker` archive file. */
56
+ #filePath;
57
+ /** Lock release function held while the writer owns the archive. */
58
+ #releaseLock;
59
+ /** Absolute path to the temporary working directory containing the SQLite DB. */
60
+ #tmpDir;
61
+ /**
62
+ * The absolute file path of the archive (`.nitpicker` file).
63
+ */
64
+ get filePath() {
65
+ return this.#filePath;
66
+ }
67
+ /**
68
+ * The intermediate directory `Archive.write()` produces by renaming
69
+ * `tmpDir` before tarring (`{cwd}/{archiveName}`). Exposed so the
70
+ * manager can include it in its cleanup-on-failure path: if `tar()`
71
+ * fails after the rename, this directory is orphaned and would
72
+ * otherwise be invisible to a `rmSync(tmpDir)` recovery.
73
+ */
74
+ get renamedDir() {
75
+ return path.resolve(path.dirname(this.#filePath), path.basename(this.#filePath, path.extname(this.#filePath)));
76
+ }
77
+ // eslint-disable-next-line no-restricted-syntax
78
+ constructor(filePath, tmpDir, db, releaseLock) {
79
+ super(tmpDir, db);
80
+ this.#filePath = filePath;
81
+ this.#tmpDir = tmpDir;
82
+ this.#db = db;
83
+ this.#releaseLock = releaseLock;
84
+ log('create instance: %O', {
85
+ filePath,
86
+ tmpDir,
87
+ });
88
+ this.#db.on('error', (e) => {
89
+ void this.emit('error', e);
90
+ });
91
+ }
92
+ /**
93
+ * @deprecated This method is no longer functional.
94
+ */
95
+ abort() { }
96
+ /**
97
+ * Adds onto the `rejected_count` of a shape's `dedupe_cap_events` row,
98
+ * looked up by `shape_key` rather than `id` — used for a shape that
99
+ * capped in an earlier session (preloaded into `DedupeCapTracker`'s
100
+ * sticky set) and so has no event id from the current session.
101
+ *
102
+ * Thin facade over {@link Database.accumulateDedupeCapRejectedCount}.
103
+ * @param shapeKey - The capped shape whose rejection count to accumulate.
104
+ * @param rejectedCount - Additional anchors rejected for this shape in the current session.
105
+ */
106
+ async accumulateDedupeCapRejectedCount(shapeKey, rejectedCount) {
107
+ dbLog('Accumulate dedupe cap rejected count shapeKey=%s rejectedCount=%d', shapeKey, rejectedCount);
108
+ return await this.#db.accumulateDedupeCapRejectedCount(shapeKey, rejectedCount);
109
+ }
110
+ /**
111
+ * Records a crawler-level error to both the human-readable `error.log` (full
112
+ * stack, for debugging) and the structured `crawl_errors` table (queryable,
113
+ * for the `error-kinds` analysis). The cause is not classified here — it is
114
+ * derived on read. `error.log` keeps the full stack while `crawl_errors`
115
+ * stores `error.message`; both normally carry the same cause token (e.g.
116
+ * `ENOTFOUND`), so classification agrees across the two — only an error whose
117
+ * cause lives solely in deeper stack frames could differ.
118
+ * @param error - The crawler error object containing process and URL information.
119
+ */
120
+ async addError(error) {
121
+ const logFile = path.resolve(this.#tmpDir, 'error.log');
122
+ await appendText(logFile, `[${error.pid}(${error.isMainProcess ? 'main' : 'sub'})] ${error.url} ${error.error.stack ?? error.error}`);
123
+ await this.#db.insertCrawlError(error.url, error.error.message, error.isExternal);
124
+ }
125
+ /**
126
+ * Records a partial scrape failure against the page identified by `url`.
127
+ *
128
+ * The corresponding `pages` row is created on demand (or matched if it
129
+ * already exists), so the call works even if the page's normal data has
130
+ * not been written yet.
131
+ * @param url - URL of the affected page.
132
+ * @param phase - Scrape phase name (typically `'retryExhausted'`).
133
+ * @param message - Human-readable failure message.
134
+ * @param isExternal - Whether the URL is external. Defaults to `false`.
135
+ */
136
+ async addPageError(url, phase, message, isExternal = false) {
137
+ dbLog('Add page error: %s [%s]', url, phase);
138
+ await this.#db.insertPageError(url, phase, message, isExternal);
139
+ }
140
+ /**
141
+ * Closes an outage row by stamping `ended_at` — a no-op if already closed.
142
+ *
143
+ * Thin facade over {@link Database.closeNetworkOutage}.
144
+ * @param id - The `network_outages.id` to close.
145
+ * @param endedAt - Epoch ms the outage is considered to have ended.
146
+ */
147
+ async closeNetworkOutage(id, endedAt) {
148
+ dbLog('Close network outage id=%d endedAt=%d', id, endedAt);
149
+ return await this.#db.closeNetworkOutage(id, endedAt);
150
+ }
151
+ /**
152
+ * Finalizes a `dedupe_cap_events` row by stamping `rejected_count` — a
153
+ * no-op if already finalized.
154
+ *
155
+ * Thin facade over {@link Database.finalizeDedupeCapEvent}.
156
+ * @param id - The `dedupe_cap_events.id` to finalize.
157
+ * @param rejectedCount - Number of anchors rejected for this shape after it capped.
158
+ */
159
+ async finalizeDedupeCapEvent(id, rejectedCount) {
160
+ dbLog('Finalize dedupe cap event id=%d rejectedCount=%d', id, rejectedCount);
161
+ return await this.#db.finalizeDedupeCapEvent(id, rejectedCount);
162
+ }
163
+ /**
164
+ * Retrieves the current crawling state, including lists of scraped and pending URLs.
165
+ * @returns An object with `scraped`, `pending`, and `pendingMetadataOnly` URL arrays.
166
+ */
167
+ async getCrawlingState() {
168
+ return this.#db.getCrawlingState();
169
+ }
170
+ /**
171
+ * Retrieves the `info.createdCwd` value stamped when this stub was
172
+ * created — see {@link Archive.resume} for how it is used.
173
+ * @returns The recorded cwd, or `null` if never stamped.
174
+ */
175
+ async getCreatedCwd() {
176
+ return this.#db.getCreatedCwd();
177
+ }
178
+ /**
179
+ * Return the subset of `urls` that already exist as `pages.url`. Used by
180
+ * `CrawlerOrchestrator.inventory` to filter the user-supplied URL list
181
+ * down to "URLs that are NOT yet in the archive" — only those reach the
182
+ * HEAD / scrape pipeline. Existing URLs are skipped to keep the second
183
+ * (and N-th) `--inventory` pass non-destructive.
184
+ * @param urls - Candidate URLs in `withoutHashAndAuth` form.
185
+ * @returns URLs already present in `pages`.
186
+ */
187
+ async getExistingPageUrls(urls) {
188
+ return this.#db.getExistingPageUrls(urls);
189
+ }
190
+ /**
191
+ * Return the subset of `urls` that already exist as `resources.url`. See
192
+ * {@link Archive.getExistingPageUrls} — the resource-side counterpart used
193
+ * by inventory mode to skip URLs that are already tracked as
194
+ * sub-resources.
195
+ * @param urls - Candidate URLs.
196
+ * @returns URLs already present in `resources`.
197
+ */
198
+ async getExistingResourceUrls(urls) {
199
+ return this.#db.getExistingResourceUrls(urls);
200
+ }
201
+ /**
202
+ * Look up the `source` column of a single page row by its URL key. Thin
203
+ * facade over {@link Database.getPageSourceByUrl} — exposes the lookup
204
+ * to the orchestrator so it can inject a `PageSourceLookup` into the
205
+ * Crawler for sub-resource lineage propagation on `--resume` /
206
+ * `--retry-failed` sessions.
207
+ * @param url - URL key in `url.withoutHashAndAuth` form.
208
+ * @returns The recorded `source`, or `undefined` when no row exists.
209
+ */
210
+ async getPageSourceByUrl(url) {
211
+ return this.#db.getPageSourceByUrl(url);
212
+ }
213
+ /**
214
+ * Retrieves a single recorded sub-resource by its URL.
215
+ * @param urls - URL candidates to match against the stored resource URL.
216
+ * @returns The raw resource row, or `null` if none match.
217
+ */
218
+ async getResourceByUrl(urls) {
219
+ return this.#db.getResourceByUrl(urls);
220
+ }
221
+ /**
222
+ * Counts the number of pages already scraped as crawl targets in the archive.
223
+ *
224
+ * Lets the crawler initialize its session-progress counter on resume so the
225
+ * displayed HTML-page count accounts for previously-rendered pages.
226
+ * @returns The count of pages with `isTarget = 1` and `scraped = 1`.
227
+ */
228
+ async getScrapedHtmlPageCount() {
229
+ return this.#db.getScrapedHtmlPageCount();
230
+ }
231
+ /**
232
+ * Retrieves the base URL of the crawl session from the archive database.
233
+ * @returns The base URL string.
234
+ */
235
+ async getUrl() {
236
+ return this.#db.getBaseUrl();
237
+ }
238
+ /**
239
+ * Appends one row (`rejected_count = NULL`) to the `dedupe_cap_events`
240
+ * journal.
241
+ *
242
+ * Thin facade over {@link Database.insertDedupeCapEvent}.
243
+ * @param params - The newly-capped shape's fields to record.
244
+ * @returns The autoincremented `id` of the inserted row.
245
+ */
246
+ async insertDedupeCapEvent(params) {
247
+ dbLog('Insert dedupe cap event: shapeKey=%s', params.shapeKey);
248
+ return await this.#db.insertDedupeCapEvent(params);
249
+ }
250
+ /**
251
+ * Pre-insert inventory non-HTML URLs as `source='inventory-seed'`
252
+ * placeholders in the `resources` table — the non-HTML counterpart of
253
+ * {@link Archive.insertInventorySeeds}. Rows are committed in chunked
254
+ * bulk inserts (500 per round-trip) rather than per-URL awaits — a
255
+ * per-URL loop would keep a 50k-URL inventory list inside the `.bak`
256
+ * window for minutes instead of seconds.
257
+ *
258
+ * Thin facade over {@link Database.insertInventoryResources}.
259
+ * `ExURL.href` is the storage key for `resources.url` (matches what
260
+ * `insertResource` writes for the per-URL path); we normalise here so
261
+ * the orchestrator stays decoupled from the storage form.
262
+ * @param urls - Non-HTML inventory URLs to record. No-op when empty.
263
+ */
264
+ async insertInventoryResources(urls) {
265
+ if (urls.length === 0) {
266
+ return;
267
+ }
268
+ dbLog('Insert inventory resources: %d URL(s)', urls.length);
269
+ await this.#db.insertInventoryResources(urls.map((u) => u.href));
270
+ }
271
+ /**
272
+ * Pre-insert inventory HTML seeds as `scraped=0`, `source='inventory-seed'`
273
+ * placeholder pages so the URL is durably tracked in the archive **before**
274
+ * the scrape phase starts. Thin facade over
275
+ * {@link Database.insertInventorySeeds} — see that method's JSDoc for the
276
+ * Ctrl+C-tolerance rationale and the `getCrawlingState` interaction.
277
+ *
278
+ * `ExURL` inputs are normalised to `withoutHashAndAuth` here so the storage
279
+ * key matches what `resolveContentItemId` writes for crawled rows, keeping the
280
+ * crawled-wins downgrade and the existing-URL filter (`getExistingPageUrls`)
281
+ * lookups consistent.
282
+ * @param urls - HTML seed URLs to pre-insert. No-op when empty.
283
+ */
284
+ async insertInventorySeeds(urls) {
285
+ if (urls.length === 0) {
286
+ return;
287
+ }
288
+ dbLog('Insert inventory seeds: %d URL(s)', urls.length);
289
+ await this.#db.insertInventorySeeds(urls.map((u) => u.withoutHashAndAuth));
290
+ }
291
+ /**
292
+ * Records exclude-matched inventory URLs as terminal skipped pages —
293
+ * the same `is_skipped=1, skip_reason='excluded'` state the normal
294
+ * crawl's fetch-time gate writes for link-discovered excluded URLs,
295
+ * labelled `source='inventory-seed'`. Thin facade over
296
+ * {@link Database.insertInventorySkippedPages} — see the underlying
297
+ * op's JSDoc for the parity rationale and crawled-wins safety.
298
+ *
299
+ * `ExURL` inputs are normalised to `withoutHashAndAuth` here for the
300
+ * same storage-key consistency reason as {@link insertInventorySeeds}.
301
+ * @param urls - Exclude-matched URLs to record. No-op when empty.
302
+ */
303
+ async insertInventorySkippedPages(urls) {
304
+ if (urls.length === 0) {
305
+ return;
306
+ }
307
+ dbLog('Insert inventory skipped pages: %d URL(s)', urls.length);
308
+ await this.#db.insertInventorySkippedPages(urls.map((u) => u.withoutHashAndAuth));
309
+ }
310
+ /**
311
+ * Appends one open row to the `network_outages` journal.
312
+ *
313
+ * Thin facade over {@link Database.insertNetworkOutage} — see
314
+ * {@link recordListReconcileRun}'s docstring for why this indirection exists.
315
+ * @param params - The confirmed-outage fields to record.
316
+ * @returns The autoincremented `id` of the inserted row.
317
+ */
318
+ async insertNetworkOutage(params) {
319
+ dbLog('Insert network outage: startedAt=%d probeHost=%s', params.startedAt, params.probeHost);
320
+ return await this.#db.insertNetworkOutage(params);
321
+ }
322
+ /**
323
+ * Every previously-scraped internal page's raw fields, in the shape
324
+ * `buildDedupeCapObservation` needs to replay this archive's prior
325
+ * `DedupeCapTracker` observations (not just its confirmed-capped
326
+ * shapes — see {@link listDedupeCapShapeKeys}) into a fresh tracker
327
+ * instance on `--resume` / `--append` / `--retry-failed` /
328
+ * `--inventory` / `--recrawl`. Without this, every not-yet-capped
329
+ * shape's Misra-Gries counter restarts at 0 each session, even one
330
+ * that was one observation away from confirming a trap.
331
+ * @param onProgress - Called after each internal chunk read, with the
332
+ * highest `content_items.id` scanned so far and the max id in the
333
+ * table. Omit for no reporting.
334
+ * @returns Every qualifying page's raw fields, in discovery order.
335
+ */
336
+ async listDedupeCapObservations(onProgress) {
337
+ return this.#db.listDedupeCapObservations(onProgress);
338
+ }
339
+ /**
340
+ * Every distinct `dedupe_cap_events.shape_key` recorded in this archive.
341
+ * Consumed by `CrawlerOrchestrator` to preload `DedupeCapTracker`'s
342
+ * sticky set on `--resume` / `--append` / `--retry-failed` /
343
+ * `--inventory`, mirroring {@link listDnsBurnedHostCandidates}'s
344
+ * writer-only exposure.
345
+ * @returns Distinct shape keys already confirmed capped.
346
+ */
347
+ async listDedupeCapShapeKeys() {
348
+ return this.#db.listDedupeCapShapeKeys();
349
+ }
350
+ /**
351
+ * Hostnames whose `crawl_errors` history is consistently DNS failures and
352
+ * for which no recent 2xx/3xx page or resource is recorded. Consumed by
353
+ * `CrawlerOrchestrator.#preloadDnsBurnedHostCache` to seed the DNS-burned
354
+ * host cache at re-open (append / inventory / retryFailed / resume), so
355
+ * the next crawl skips HEAD pre-flight on hosts the previous crawl
356
+ * already proved unreachable.
357
+ *
358
+ * Deliberately exposed only on `Archive` (writer-side) — read-only
359
+ * `ArchiveAccessor` (stub viewer) does not see this method so the
360
+ * stub's no-migration contract is preserved.
361
+ * @returns Lower-cased hostnames safe to short-circuit.
362
+ */
363
+ async listDnsBurnedHostCandidates() {
364
+ return this.#db.listDnsBurnedHostCandidates();
365
+ }
366
+ /**
367
+ * Lists every recorded outage as a resolved {@link OutageWindow}.
368
+ *
369
+ * Thin facade over {@link Database.listNetworkOutages}.
370
+ * @returns Resolved outage windows, or `[]` if none have been recorded.
371
+ */
372
+ async listNetworkOutages() {
373
+ return await this.#db.listNetworkOutages();
374
+ }
375
+ /**
376
+ * Appends one row to the `list_reconcile_runs` audit log.
377
+ *
378
+ * Thin facade over {@link Database.recordListReconcileRun} — keeps the
379
+ * orchestrator decoupled from the knex layer and gives a single
380
+ * write entry point that future Archive-level concerns (locking,
381
+ * mirror sync, etc.) can hook into without touching every caller.
382
+ * @param meta - The run metadata. Only `ran_at` is required.
383
+ * @returns The autoincremented `id` of the inserted row.
384
+ */
385
+ async recordListReconcileRun(meta) {
386
+ dbLog('Record list reconcile run: %s', meta.list_label ?? meta.ran_at);
387
+ return await this.#db.recordListReconcileRun(meta);
388
+ }
389
+ /**
390
+ * Releases the SQLite handle and the advisory lock **without** writing
391
+ * the archive or removing `tmpDir`.
392
+ *
393
+ * Use this when you need to detach from a freshly-created `Archive`
394
+ * without finalising it — fixtures producing a stub state for tests,
395
+ * tooling that wants to leave the tmpDir alive for `crawl --resume`,
396
+ * or any non-orchestrator caller that owns the lifecycle externally.
397
+ * Shares the same idempotency guard as {@link close}, so the two paths
398
+ * are mutually exclusive (the first one called wins).
399
+ */
400
+ async releaseHandle() {
401
+ if (this.#closeOnce) {
402
+ return this.#closeOnce;
403
+ }
404
+ this.#closeOnce = this.#runReleaseHandle();
405
+ return this.#closeOnce;
406
+ }
407
+ /**
408
+ * Replaces the archive's DOM-structure template classification
409
+ * with a fresh SQL-backed set.
410
+ *
411
+ * Thin facade over {@link Database.replacePageTemplates}; kept on
412
+ * `Archive` so the crawl-end classification step
413
+ * (`classifyArchivePageTemplates`) can persist template keys without
414
+ * reaching into the low-level database class directly.
415
+ * @param templateKeysByUrl - Page URL → template key, as produced by
416
+ * `classifyPageTemplates`.
417
+ * @param clusterReasonsByTemplateKey - Template key → cluster-selection
418
+ * evidence, if the caller captured it. Omitting this always clears the
419
+ * previously-stored reasons too — "no reason" means "not captured for
420
+ * this run", never "carry over the previous run's reasons".
421
+ */
422
+ async replacePageTemplates(templateKeysByUrl, clusterReasonsByTemplateKey) {
423
+ await this.#db.replacePageTemplates(templateKeysByUrl, clusterReasonsByTemplateKey);
424
+ }
425
+ /**
426
+ * Promote previously-external pages that now fall under the (possibly extended)
427
+ * scope back to a pending state so that the crawler re-scrapes them as fully
428
+ * internal pages on the next pass.
429
+ * @param scopes - Hostname-indexed scope map representing the new scope.
430
+ * @param options - URL parsing options forwarded to the scope-entry lookup.
431
+ * @param onProgress - Forwarded to {@link Database.repromoteExternalPages}
432
+ * — see that method's docs.
433
+ * @returns The URLs that were repromoted.
434
+ */
435
+ async repromoteExternalPages(scopes, options, onProgress) {
436
+ dbLog('Repromote external pages with %d hostnames in scope', scopes.size);
437
+ return this.#db.repromoteExternalPages(scopes, options, onProgress);
438
+ }
439
+ /**
440
+ * Reset previously-failed pages back to pending so a follow-up crawl re-fetches them.
441
+ *
442
+ * Delegates to {@link Database.resetFailedPages}. See that method for the
443
+ * exact failure criteria (missing status / content type, or a 5xx status).
444
+ * @param onProgress - Forwarded to {@link Database.resetFailedPages} —
445
+ * see that method's docs.
446
+ * @returns The URLs of the pages that were reset to pending.
447
+ */
448
+ async resetFailedPages(onProgress) {
449
+ dbLog('Reset failed pages back to pending');
450
+ return this.#db.resetFailedPages(onProgress);
451
+ }
452
+ /**
453
+ * Reset pages matching an operator-supplied URL list back to pending so a
454
+ * follow-up crawl re-fetches them from scratch.
455
+ *
456
+ * Delegates to {@link Database.resetPagesByUrls}. See that method for the
457
+ * conservative exclusion rules (redirect sources / intentionally-skipped /
458
+ * external pages are matched but not reset).
459
+ * @param urls - URL strings to match, already in `withoutHashAndAuth` form.
460
+ * @param onProgress - Forwarded to {@link Database.resetPagesByUrls} — see
461
+ * that method's docs.
462
+ * @returns The reset URLs plus the excluded URLs grouped by reason.
463
+ */
464
+ async resetPagesByUrls(urls, onProgress) {
465
+ dbLog('Reset %d URL-list-matched page(s) back to pending', urls.length);
466
+ return this.#db.resetPagesByUrls(urls, onProgress);
467
+ }
468
+ /**
469
+ * Persists the raw bytes of an `--inventory` source URL list into the
470
+ * archive's tar payload, at `inventory/<sha256>.txt`.
471
+ *
472
+ * The file name is the content hash rather than the original file name:
473
+ * re-applying the same list is then a no-op write (`fs.writeFile`
474
+ * overwrites identical bytes), and the original name — which may embed a
475
+ * client/project identifier — is never retained (the archive already
476
+ * omits the source file's absolute path for the same reason; see
477
+ * `CrawlerOrchestrator.inventory`'s `source` param).
478
+ *
479
+ * The file always lands under the fixed `inventory/` prefix. Callers that
480
+ * need to read the saved list back can use the inherited
481
+ * `getData(`inventory/${sha256}`, 'txt')`, which resolves to the same
482
+ * path under tmpDir.
483
+ *
484
+ * No entry is ever removed here — same accepted gap as `page_html_blobs`
485
+ * (a future #23 GC pass will sweep unreachable hashes across both). A
486
+ * source list that differs byte-for-byte on every run (e.g. a
487
+ * regenerated doc-root export with fresh timestamps) adds one entry per
488
+ * run with no pruning of superseded ones.
489
+ * @param sha256 - Lower-case hex SHA-256 digest of `bytes` (used as the file name).
490
+ * @param bytes - The exact bytes of the source list file, written verbatim.
491
+ */
492
+ async saveInventorySourceList(sha256, bytes) {
493
+ const filePath = safePath(this.tmpDir, 'inventory', `${sha256}.txt`);
494
+ await outputBinary(filePath, bytes);
495
+ }
496
+ /**
497
+ * Stores the crawl configuration into the archive database.
498
+ * @param config - The configuration object to store.
499
+ */
500
+ async setConfig(config) {
501
+ dbLog('Set config: %O', redactRequestHeaders(config));
502
+ return this.#db.setConfig(config);
503
+ }
504
+ /**
505
+ * Replaces one page's captured console messages / page errors in the
506
+ * archive database.
507
+ * @param pageUrl - The originally-requested URL, normalised (`withoutHashAndAuth` form).
508
+ * @param redirectPaths - The redirect chain hops captured during fetch, in order.
509
+ * @param entries - The console log entries to persist.
510
+ */
511
+ async setConsoleLogs(pageUrl, redirectPaths, entries) {
512
+ dbLog('Set console logs: %d entries on %s', entries.length, pageUrl);
513
+ await this.#db.replaceConsoleLogs(pageUrl, redirectPaths, entries);
514
+ }
515
+ /**
516
+ * Stores an external page's data in the archive database without storing
517
+ * an HTML snapshot. External-page rows carry only metadata (status, title,
518
+ * content-type), never a rendered body.
519
+ * @param pageInfo - The page data to store.
520
+ * @param source - Provenance label for new rows. `undefined` leaves the DB DEFAULT (`'crawled'`).
521
+ * @param recursive - The crawl session's `recursive` option, forwarded so
522
+ * `is_metadata_only` on any newly-discovered anchor is computed
523
+ * correctly (#369). Defaults to `true` (never persist an anchor as
524
+ * metadata-only) since an external page's `anchorList` is always
525
+ * empty — this only matters for callers that pass one anyway.
526
+ * @example
527
+ * await archive.setExternalPage(externalPageData, undefined, options.recursive);
528
+ */
529
+ async setExternalPage(pageInfo, source, recursive) {
530
+ dbLog('Set external page: %s', pageInfo.url.href);
531
+ await this.#db.updatePage(pageInfo, false, false, source, undefined, recursive);
532
+ }
533
+ /**
534
+ * Stores a crawled page's data in the archive database, persisting the
535
+ * rendered HTML body as a zstd-compressed BLOB inside the same SQLite
536
+ * transaction. Storage is content-addressable: identical bodies across
537
+ * pages share a single `page_html_blobs` row.
538
+ * @param pageInfo - The page data to store.
539
+ * @param source - Provenance label for new rows. `undefined` leaves the DB DEFAULT (`'crawled'`).
540
+ * @param bodyHash - Precomputed body hash for the page's HTML (see
541
+ * `CrawlerEventTypes.page.bodyHash`). `undefined`/`null` falls back to
542
+ * computing it from the HTML instead.
543
+ * @param recursive - The crawl session's `recursive` option, forwarded so
544
+ * any anchor discovered on this page gets the correct
545
+ * `is_metadata_only` value (#369). Defaults to `true` (never persist
546
+ * an anchor as metadata-only) for callers that do not track the
547
+ * option.
548
+ * @returns The database ID of the stored page.
549
+ * @example
550
+ * const pageId = await archive.setPage(pageData, undefined, undefined, options.recursive);
551
+ */
552
+ async setPage(pageInfo, source, bodyHash, recursive) {
553
+ dbLog('Set page: %s', pageInfo.url.href);
554
+ return await this.#db.updatePage(pageInfo, true, pageInfo.isTarget, source, bodyHash, recursive);
555
+ }
556
+ /**
557
+ * Records a redirect edge without re-storing the destination's content.
558
+ *
559
+ * The crawler calls this (instead of {@link setPage}) when a URL redirects to
560
+ * a destination that has already been rendered (#73): only the source →
561
+ * destination edge is written, leaving the destination's stored title / meta /
562
+ * anchors / images untouched.
563
+ * @param pageInfo - The HEAD-resolved page data carrying the redirect chain.
564
+ * @param source - Inventory provenance for a brand-new destination row.
565
+ * Forwarded to `recordRedirect` so the destination's `source` (and the
566
+ * chain-intermediate `source` derived from it) lands on the inventory
567
+ * label instead of the DB DEFAULT `'crawled'` when the orchestrator is
568
+ * running an inventory pass. `undefined` keeps the DB DEFAULT.
569
+ */
570
+ async setRedirect(pageInfo, source) {
571
+ dbLog('Set redirect: %s', pageInfo.url.href);
572
+ await this.#db.recordRedirect(pageInfo, source);
573
+ }
574
+ /**
575
+ * Stores a sub-resource (CSS, JS, image, etc.) in the archive database.
576
+ * @param resource - The resource data to store.
577
+ * @param source - Provenance label for new rows. `undefined` leaves the DB DEFAULT (`'crawled'`).
578
+ */
579
+ async setResources(resource, source) {
580
+ dbLog('Set resource: %s', resource.url.href);
581
+ await this.#db.insertResource(resource, source);
582
+ }
583
+ /**
584
+ * Stores the referrer relationship between a resource and the page that references it.
585
+ * @param params - An object containing `url` (the page URL) and `src` (the resource URL).
586
+ * @param params.url
587
+ * @param params.src
588
+ */
589
+ async setResourcesReferrers({ url, src }) {
590
+ dbLog("Set resource's referrers: %s on %s", src, url);
591
+ await this.#db.insertResourceReferrers(src, url);
592
+ }
593
+ /**
594
+ * Marks a page as skipped in the archive database with the given reason.
595
+ * @param url - The URL of the page to mark as skipped.
596
+ * @param reason - The reason the page was skipped.
597
+ * @param isExternal - Whether the page is on an external domain. Defaults to `false`.
598
+ */
599
+ async setSkippedPage(url, reason, isExternal = false) {
600
+ dbLog('Set skipped page: %s', url);
601
+ await this.#db.setSkippedPage(url, reason, isExternal);
602
+ }
603
+ /**
604
+ * Assigns natural URL sort order values to all pages in the database
605
+ * that do not yet have an `order` field set.
606
+ * @param onProgress - Forwarded to {@link Database.setUrlOrder} — see that
607
+ * method's docs.
608
+ */
609
+ async setUrlOrder(onProgress) {
610
+ dbLog("Pages didn't have `order` field. So set URL order.");
611
+ await this.#db.setUrlOrder(onProgress);
612
+ }
613
+ /**
614
+ * Updates a subset of fields on the archive's `info` row. Used by the append
615
+ * flow to extend `roots` / `scope` without rewriting the entire config.
616
+ * @param patch - Partial {@link Config} fields to overwrite. `undefined` values are ignored.
617
+ */
618
+ async updateConfig(patch) {
619
+ dbLog('Update config: %O', redactRequestHeaders(patch));
620
+ await this.#db.updateConfig(patch);
621
+ }
622
+ /**
623
+ * Writes the archive to disk as a `.nitpicker` tar file.
624
+ *
625
+ * Checkpoints the SQLite WAL so the database is self-contained inside
626
+ * `db.sqlite`, renames the temporary working directory to the archive's
627
+ * basename, and tars the **entire tmpDir**. `db.sqlite` is normally the
628
+ * only entry (HTML lives as BLOBs in the DB, not a `snapshot-html.zip`),
629
+ * but `saveInventorySourceList` (a saved `--inventory` source list) adds
630
+ * extra files under tmpDir that get tarred right alongside it.
631
+ *
632
+ * This is why every writer path that reaches `write()` must open with
633
+ * `openPluginData: true` — `Archive.open`'s default extracts only
634
+ * `db.sqlite`, so a re-crawl (`append` / `inventory` / `retryFailed`)
635
+ * opened without it would tar back a tmpDir missing those extra files,
636
+ * silently dropping them from the rewritten archive.
637
+ * @param options - Optional write settings.
638
+ * @param options.onTarProgress - Called as archive bytes are written
639
+ * during the tar step, with the bytes written so far and the estimated
640
+ * total (issue #294: tarring a large archive takes minutes, and
641
+ * without this the CLI shows nothing until `write` returns). Omit for
642
+ * a silent write (the default).
643
+ * @param options.onStep - Called once at the start of each of this
644
+ * method's four steps (issue #294): `checkpoint` (WAL fold-back —
645
+ * single synchronous PRAGMA, no countable progress) and `remove`
646
+ * (deleting the tarred-away tmpDir) have no progress signal of their
647
+ * own, so without this a large archive's write looks frozen between
648
+ * the `tar` step's byte updates and completion. `rename` is nearly
649
+ * instant (same-filesystem directory move) but included for
650
+ * completeness — a caller displaying phase labels shouldn't have a
651
+ * gap where the operation is silently between named steps.
652
+ */
653
+ async write(options) {
654
+ saveLog('Starts: %s', this.#filePath);
655
+ // `.nitpicker` files are routinely shared between users — scrub the
656
+ // stub-local `createdCwd` (see `Config.createdCwd`'s JSDoc) before it
657
+ // gets folded into `db.sqlite` and tarred, so a packaged archive never
658
+ // carries another user's local absolute path. Bundled into the
659
+ // `checkpoint` step below (a single UPDATE ahead of the WAL fold-back)
660
+ // rather than its own `onStep` phase — both are near-instant and
661
+ // reporting them separately would add a phase label for no visible
662
+ // wait.
663
+ await this.#db.updateConfig({ createdCwd: null });
664
+ options?.onStep?.('checkpoint');
665
+ await this.#db.checkpoint();
666
+ const filePathWithoutExt = path.resolve(path.dirname(this.#filePath), path.basename(this.#filePath, path.extname(this.#filePath)));
667
+ saveLog('Rename temporary dir: %s to %s', this.#tmpDir, filePathWithoutExt);
668
+ options?.onStep?.('rename');
669
+ await rename(this.#tmpDir, filePathWithoutExt, true);
670
+ saveLog('Tar temporary dir to file: %s to %s', filePathWithoutExt, this.#filePath);
671
+ options?.onStep?.('tar');
672
+ await tar(filePathWithoutExt, this.#filePath, options?.onTarProgress);
673
+ saveLog('Remove temporary dir: %s', filePathWithoutExt);
674
+ options?.onStep?.('remove');
675
+ await remove(filePathWithoutExt);
676
+ saveLog('Done: %s', this.#filePath);
677
+ }
678
+ /**
679
+ * Worker for {@link close}. Performs the destructive prologue
680
+ * (write or remove), drops the DB handle via the base class, then
681
+ * releases the lock in a `finally` so the lock never leaks even on
682
+ * partial failure.
683
+ * @param options - See {@link close}.
684
+ * @param options.timeoutMs
685
+ * @param options.onRecoveryStart
686
+ * @param options.onTarProgress
687
+ * @param options.onStep
688
+ */
689
+ async #runFullClose(options) {
690
+ log('Closing');
691
+ try {
692
+ if (!exists(this.#filePath)) {
693
+ log("Save the file because it doesn't exist");
694
+ options?.onRecoveryStart?.();
695
+ await this.write(options);
696
+ }
697
+ else if (exists(this.#tmpDir)) {
698
+ log('Remove temporary dir');
699
+ await remove(this.#tmpDir);
700
+ }
701
+ await super.close({ timeoutMs: options?.timeoutMs });
702
+ }
703
+ finally {
704
+ await this.#releaseLock();
705
+ }
706
+ log('Closing done');
707
+ }
708
+ /**
709
+ * Worker for {@link releaseHandle}. Drops the SQLite handle and the
710
+ * advisory lock with no filesystem mutation.
711
+ */
712
+ async #runReleaseHandle() {
713
+ log('Releasing handle (no write, no remove)');
714
+ try {
715
+ await super.close();
716
+ }
717
+ finally {
718
+ await this.#releaseLock();
719
+ }
720
+ }
721
+ /** The file extension for Nitpicker archive files (without the leading dot). */
722
+ static FILE_EXTENSION = 'nitpicker';
723
+ /** The filename of the SQLite database within the archive. */
724
+ static SQLITE_DB_FILE_NAME = 'db.sqlite';
725
+ /** The prefix used for temporary working directories during archive operations. */
726
+ static TMP_DIR_PREFIX = '._nitpicker-';
727
+ /**
728
+ * Opens a connection to an existing archive's database, defaulting to
729
+ * read-only.
730
+ *
731
+ * Returns an {@link ArchiveAccessor} that provides query methods. In the
732
+ * default read-only mode, no schema migrations run and the connection
733
+ * refuses to resurrect a missing parent directory or db file (so a
734
+ * TOCTOU window between source classification and this call cannot
735
+ * silently produce an empty phantom tmpDir); the returned accessor is
736
+ * also marked read-only so consumer-facing helpers (e.g.
737
+ * {@link ArchiveAccessor.getHtmlOfPage}) avoid any filesystem mutation
738
+ * on the user's tmpDir.
739
+ *
740
+ * `options.readOnly: false` is a narrow escape hatch for opening a
741
+ * second, writable connection to a `tmpDir` the caller's own process
742
+ * already owns and extracted itself. The one production caller is the
743
+ * viewer-read-model worker thread (`@nitpicker/query`'s
744
+ * `viewer-read-model-worker-entry.ts`, issue #294): the parent thread
745
+ * holds the archive via `Archive.open` (lock included — worker threads
746
+ * share the parent's PID, so the PID-based `acquireArchiveLock` guard
747
+ * stays valid), sits idle awaiting the worker, and re-tars the tmpDir
748
+ * afterward. What this hatch must NEVER target is a live/interrupted
749
+ * crawl tmpDir owned by a *different* process (the stub-mode
750
+ * `ArchiveManager.open` path attaches to exactly such directories, and
751
+ * must stay read-only): writable connects run the self-healing
752
+ * migrations, and mutating a directory out from under its owner is how
753
+ * archives corrupt. A read-only open (`Archive.openCached`/
754
+ * `ArchiveManager.open`) must never take this path itself — blocking or
755
+ * writing during what must be a read-only open is forbidden (issue
756
+ * #177). Any new caller is responsible for its own coordination with
757
+ * the tmpDir's owner (see `acquireArchiveLock` for the cross-process
758
+ * case) — this method does not acquire any lock itself.
759
+ * @param tmpDir - The path to the temporary directory containing the database.
760
+ * @param options - Connection options.
761
+ * @param options.readOnly - Defaults to `true`. Pass `false` to obtain a
762
+ * writable accessor against a tmpDir the calling process itself owns.
763
+ * @returns An ArchiveAccessor instance for querying the archive data.
764
+ * @example
765
+ * // Default (read-only) — safe for stub mode and cache reads:
766
+ * const accessor = await Archive.connect(tmpDir);
767
+ * @example
768
+ * // Writable escape hatch — only against a tmpDir this process owns
769
+ * // (e.g. the viewer-read-model worker thread reconnecting to the
770
+ * // parent's Archive.open extraction):
771
+ * const writable = await Archive.connect(ownTmpDir, { readOnly: false });
772
+ */
773
+ static async connect(tmpDir, options = {}) {
774
+ const readOnly = options.readOnly ?? true;
775
+ const db = await Archive.#connectDB(tmpDir, { readOnly });
776
+ const archive = new ArchiveAccessor(tmpDir, db, { readOnly });
777
+ return archive;
778
+ }
779
+ /**
780
+ * Open a `.nitpicker` archive through the read-only tar cache.
781
+ *
782
+ * This is the fast path for read-only consumers (viewer, MCP, query
783
+ * CLI). It diverges from {@link Archive.open} in two important ways:
784
+ *
785
+ * 1. The extracted contents land in an OS-temp-scoped cache directory
786
+ * keyed by the archive's `size + mtime_ns + ctime_ns` (see
787
+ * {@link computeArchiveCacheKey}). Subsequent opens of the same
788
+ * unchanged archive skip the untar entirely. A fresh 10 GB archive
789
+ * pays the ~10 s untar cost once; reopens are instant.
790
+ * 2. The returned value is an {@link ArchiveAccessor} (read-only), not
791
+ * an `Archive` (writer). Closing it tears down the DB handle but
792
+ * leaves the cache directory in place for the next reader. The
793
+ * OS's own temp-directory cleanup (macOS reboot, Linux
794
+ * `systemd-tmpfiles`, Windows Disk Cleanup) reclaims stale
795
+ * entries — we do not own eviction.
796
+ *
797
+ * Migrations: the writer-side migration stack
798
+ * (`initSchema` / `migrate*`) runs once at cache-miss extraction, so
799
+ * the cache directory always lands on the current schema before the
800
+ * read-only re-open. Cache hits then skip migrations entirely.
801
+ *
802
+ * Override the cache location with `NITPICKER_TAR_CACHE_DIR`. The
803
+ * disable switch (`NITPICKER_DISABLE_TAR_CACHE=1`) is honoured by
804
+ * the caller (`ArchiveManager.open` falls back to {@link Archive.open}
805
+ * in that case); this function itself always goes through the cache.
806
+ *
807
+ * Writer entry points (`crawl --append`, `crawl --retry-failed`) must
808
+ * NOT use this path — they need the lock + write-back semantics of
809
+ * {@link Archive.open}.
810
+ * @param filePath - Absolute path to the `.nitpicker` file.
811
+ * @param onExtractProgress - Forwarded to {@link extractArchiveToCache} —
812
+ * see that function's docs for the cache-hit/miss contract.
813
+ * @param onLog - Forwarded to the cache-miss migration pass (issue #294)
814
+ * — a legacy archive's self-healing schema migrations otherwise fall
815
+ * back to a bare `console.error`, which can print mid-redraw of a
816
+ * caller's `Lanes`/`TaskList` display. Omit for that fallback
817
+ * (existing callers — the viewer, MCP, query CLI — do not pass this;
818
+ * only callers driving a `TaskList` row for the extraction, like
819
+ * `concat`/`split`, need to).
820
+ * @returns A read-only {@link ArchiveAccessor} backed by the cache directory.
821
+ * @example
822
+ * ```ts
823
+ * await using accessor = await Archive.openCached('/path/to/site.nitpicker');
824
+ * const summary = await getSummary(accessor);
825
+ * // tears down DB handle on scope exit; cacheDir persists.
826
+ * ```
827
+ */
828
+ static async openCached(filePath, onExtractProgress, onLog) {
829
+ const cacheRoot = getArchiveCacheRoot();
830
+ const cacheKey = await computeArchiveCacheKey(filePath);
831
+ const cacheDir = resolveArchiveCacheDir(cacheRoot, cacheKey, filePath);
832
+ log('Open cached: %s (cacheDir=%s)', filePath, cacheDir);
833
+ await extractArchiveToCache(filePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog);
834
+ return await Archive.connect(cacheDir);
835
+ }
836
+ /**
837
+ * Creates a new archive at the specified file path.
838
+ * Initializes a temporary working directory and a fresh SQLite database.
839
+ * @param options - Options including the file path and optional working directory.
840
+ * @returns A new Archive instance ready for writing crawl data.
841
+ */
842
+ static async create(options) {
843
+ const { filePath } = options;
844
+ const cwd = options.cwd ?? process.cwd();
845
+ log('Create: %O', {
846
+ filePath,
847
+ cwd,
848
+ });
849
+ const fileName = path.basename(filePath, path.extname(filePath));
850
+ const tmpDir = path.resolve(cwd, Archive.TMP_DIR_PREFIX + fileName);
851
+ const releaseLock = await acquireArchiveLock(tmpDir);
852
+ try {
853
+ return await Archive.#init(filePath, tmpDir, releaseLock);
854
+ }
855
+ catch (error) {
856
+ await releaseLock();
857
+ throw error;
858
+ }
859
+ }
860
+ /**
861
+ * Joins path segments into an absolute path.
862
+ * @param pathes - The path segments to join.
863
+ * @returns The resolved absolute path.
864
+ */
865
+ static joinPath(...pathes) {
866
+ return path.resolve(...pathes);
867
+ }
868
+ /**
869
+ * Opens an existing archive file (`.nitpicker`) by extracting it to a temporary directory.
870
+ * @param options - Options including the file path, optional working directory,
871
+ * and whether to extract non-db tar entries.
872
+ * @returns An Archive instance with the extracted data loaded.
873
+ */
874
+ static async open(options) {
875
+ const { filePath, openPluginData, onExtractProgress, onLog } = options;
876
+ const cwd = options.cwd ?? process.cwd();
877
+ log('Open: %O', {
878
+ filePath,
879
+ cwd,
880
+ openPluginData,
881
+ });
882
+ // Read the tar's actual top-level directory name instead of deriving
883
+ // it from the outer file's basename. `.nitpicker` files are plain
884
+ // tar archives and users routinely rename them (`mv X.nitpicker
885
+ // Y.nitpicker`) — that operation must not break `open`. The inner
886
+ // directory keeps whatever name `Archive.write()` baked in at write
887
+ // time, and `tmpDir` mirrors the OUTER basename (so concurrent
888
+ // crawls on differently-named copies of the same archive don't
889
+ // collide on the lockfile).
890
+ const outerBasename = path.basename(filePath, path.extname(filePath));
891
+ const innerDirName = await peekTarTopDir(filePath);
892
+ const tmpDir = path.resolve(cwd, Archive.TMP_DIR_PREFIX + outerBasename);
893
+ const releaseLock = await acquireArchiveLock(tmpDir);
894
+ try {
895
+ const openFiles = [];
896
+ if (!openPluginData) {
897
+ const relDdPath = path.join(innerDirName, Archive.SQLITE_DB_FILE_NAME);
898
+ openFiles.push(relDdPath);
899
+ }
900
+ log('Unzip file: %s (%O)', filePath, openFiles);
901
+ await untar(filePath, {
902
+ cwd,
903
+ fileList: openFiles.length > 0 ? openFiles : undefined,
904
+ onProgress: onExtractProgress,
905
+ });
906
+ const extractedDir = path.resolve(cwd, innerDirName);
907
+ log('Move directory: %s to %s', extractedDir, tmpDir);
908
+ await rename(extractedDir, tmpDir, true);
909
+ return await Archive.#init(filePath, tmpDir, releaseLock, onLog);
910
+ }
911
+ catch (error) {
912
+ await releaseLock();
913
+ throw error;
914
+ }
915
+ }
916
+ /**
917
+ * Resumes an archive from an existing temporary directory
918
+ * (e.g., after an interrupted crawl session).
919
+ * @param targetPath - The path to the temporary directory to resume from.
920
+ * @param onLog - Forwarded to {@link Database.connect} — see
921
+ * {@link ArchiveOpenOptions.onLog}'s docs (this writable reconnect
922
+ * runs the same self-healing migrations `Archive.open` does).
923
+ * @returns An Archive instance reconnected to the existing data.
924
+ * @throws {Error} If the specified path is not a directory.
925
+ */
926
+ static async resume(targetPath, onLog) {
927
+ log('Resume: %s', targetPath);
928
+ if (await isDir(targetPath)) {
929
+ const tmpDir = targetPath;
930
+ const releaseLock = await acquireArchiveLock(tmpDir);
931
+ try {
932
+ const db = await Archive.#connectDB(tmpDir, { onLog });
933
+ const name = (await db.getName()) ||
934
+ path.basename(targetPath).replace(Archive.TMP_DIR_PREFIX, '');
935
+ // Reconstruct the output path from the cwd the interrupted
936
+ // session was originally started from (see `Config.createdCwd`),
937
+ // not this invocation's own `process.cwd()` — `crawl --resume
938
+ // <stub>` is routinely run from a different directory than the
939
+ // original `crawl`/`--append`/etc. call. Falls back to this
940
+ // invocation's cwd for a stub that predates this column.
941
+ const createdCwd = await db.getCreatedCwd();
942
+ const filePath = path.resolve(createdCwd ?? process.cwd(), name + '.' + Archive.FILE_EXTENSION);
943
+ return new Archive(filePath, tmpDir, db, releaseLock);
944
+ }
945
+ catch (error) {
946
+ await releaseLock();
947
+ throw error;
948
+ }
949
+ }
950
+ throw new Error('The specified path is not a directory. Please ensure the path points to a valid directory.');
951
+ }
952
+ /**
953
+ * Generates a timestamp string in the format `YYYYMMDDHHmmssSSS`
954
+ * suitable for use in file names.
955
+ * @returns A formatted timestamp string.
956
+ */
957
+ static timestamp() {
958
+ const now = new Date();
959
+ const year = now.getFullYear().toString();
960
+ const month = (now.getMonth() + 1).toLocaleString('en-US', {
961
+ minimumIntegerDigits: 2,
962
+ });
963
+ const date = now.getDate().toLocaleString('en-US', { minimumIntegerDigits: 2 });
964
+ const hours = now.getHours().toLocaleString('en-US', { minimumIntegerDigits: 2 });
965
+ const minutes = now.getMinutes().toLocaleString('en-US', { minimumIntegerDigits: 2 });
966
+ const seconds = now.getSeconds().toLocaleString('en-US', { minimumIntegerDigits: 2 });
967
+ const ms = now.getMilliseconds().toLocaleString('en-US', { minimumIntegerDigits: 3 });
968
+ return year + month + date + hours + minutes + seconds + ms;
969
+ }
970
+ /**
971
+ * Connects to (or creates) the SQLite database in the given directory.
972
+ * @param tmpDir - Directory containing `db.sqlite`
973
+ * @param options - Optional connection flags forwarded to
974
+ * {@link Database.connect}. Used by {@link Archive.connect} to pass
975
+ * `readOnly: true` so no migrations run and a missing tmpDir is not
976
+ * resurrected.
977
+ * @param options.readOnly
978
+ * @param options.onLog
979
+ */
980
+ static async #connectDB(tmpDir, options) {
981
+ const dbPath = path.resolve(tmpDir, Archive.SQLITE_DB_FILE_NAME);
982
+ dbLog('connects database: %s (readOnly=%s)', dbPath, options?.readOnly ?? false);
983
+ return await Database.connect({
984
+ filename: dbPath,
985
+ readOnly: options?.readOnly,
986
+ onLog: options?.onLog,
987
+ });
988
+ }
989
+ /**
990
+ * Initializes an Archive instance by connecting to the database.
991
+ *
992
+ * The advisory lock must already be acquired by the caller; this helper just
993
+ * threads the release function through to the resulting `Archive` so that
994
+ * {@link Archive.close} can drop the lock when work is done.
995
+ * @param filePath - Output `.nitpicker` file path
996
+ * @param tmpDir - Temporary working directory path
997
+ * @param releaseLock - Function returned by {@link acquireArchiveLock}.
998
+ * @param onLog - Forwarded to {@link Database.connect} — see
999
+ * {@link ArchiveOpenOptions.onLog}'s docs.
1000
+ */
1001
+ static async #init(filePath, tmpDir, releaseLock, onLog) {
1002
+ const db = await Archive.#connectDB(tmpDir, { onLog });
1003
+ const archive = new Archive(filePath, tmpDir, db, releaseLock);
1004
+ return archive;
1005
+ }
1006
+ /**
1007
+ * Closes the archive. If the archive file does not yet exist on disk,
1008
+ * it writes the archive first. If the temporary directory still exists,
1009
+ * it is removed. The database connection is then closed via
1010
+ * {@link ArchiveAccessor.close} (the base class owns the SQLite handle),
1011
+ * and finally the archive's advisory lock is released.
1012
+ *
1013
+ * **Idempotent**: the first invocation captures the close promise;
1014
+ * subsequent invocations (signal handlers, parallel teardowns, retried
1015
+ * orchestrator paths) await the same promise instead of re-entering
1016
+ * the destructive prologue on a half-mutated state. If the first
1017
+ * close fails (e.g. ENOSPC during tar), the rejection propagates to
1018
+ * all awaiters and the archive stays latched closed — there is no
1019
+ * safe way to retry `write()` once `tmpDir` has been renamed.
1020
+ *
1021
+ * **Read-only consumers must not reach this override.** Anything that
1022
+ * obtains an archive view via {@link Archive.connect} receives an
1023
+ * {@link ArchiveAccessor} (not an `Archive`), so `close()` resolves to
1024
+ * the safe base implementation — no `write()`, no `remove()`, no lock
1025
+ * release — leaving the tmpDir intact for the live crawler.
1026
+ * @param options - Optional close settings. `timeoutMs` is accepted for
1027
+ * compatibility with {@link ArchiveAccessor.close}'s signature (forwarded
1028
+ * to the base `super.close()` call below); the rest are progress
1029
+ * callbacks (issue #294) forwarded to {@link write} when this call ends
1030
+ * up taking the recovery-write branch (the archive file doesn't exist
1031
+ * yet).
1032
+ * @param options.timeoutMs - See {@link ArchiveAccessor.close}.
1033
+ * @param options.onRecoveryStart - Called once, only when this `close()`
1034
+ * is about to write the archive because the file doesn't exist on
1035
+ * disk yet — e.g. a caller's own explicit `write()` threw before
1036
+ * finishing, or was never called at all. Without this, a listener
1037
+ * that already tore down its display after that earlier failure has
1038
+ * no way to know a second, recovery write is happening.
1039
+ * @param options.onTarProgress - See {@link write}.
1040
+ * @param options.onStep - See {@link write}.
1041
+ */
1042
+ async close(options) {
1043
+ if (this.#closeOnce) {
1044
+ return this.#closeOnce;
1045
+ }
1046
+ this.#closeOnce = this.#runFullClose(options);
1047
+ return this.#closeOnce;
1048
+ }
1049
+ /**
1050
+ * Retrieves the crawl configuration stored in the archive database.
1051
+ * @returns The configuration object.
1052
+ */
1053
+ async getConfig() {
1054
+ return this.#db.getConfig();
1055
+ }
1056
+ }