polite-crawler 0.5.0 → 0.5.1
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.
- package/README.md +1 -0
- package/build/{browser-56dBBLec.mjs → browser-Cp5W-dmj.mjs} +5 -10
- package/build/{browser-56dBBLec.mjs.map → browser-Cp5W-dmj.mjs.map} +1 -1
- package/build/classify.d.mts +0 -2
- package/build/classify.mjs +1 -2
- package/build/{cli-daemon-kNj07eYU.mjs → cli-daemon-oSJWogkA.mjs} +3 -4
- package/build/{cli-daemon-kNj07eYU.mjs.map → cli-daemon-oSJWogkA.mjs.map} +1 -1
- package/build/{cli-recipes-DB3PgVig.mjs → cli-recipes-DVTMTQLx.mjs} +4 -5
- package/build/{cli-recipes-DB3PgVig.mjs.map → cli-recipes-DVTMTQLx.mjs.map} +1 -1
- package/build/cli.mjs +16 -19
- package/build/cli.mjs.map +1 -1
- package/build/{daemon-DePmNqn9.mjs → daemon-DNGSr4hR.mjs} +7 -13
- package/build/{daemon-DePmNqn9.mjs.map → daemon-DNGSr4hR.mjs.map} +1 -1
- package/build/{diff-Db1AmXuk.mjs → diff-ChsL3yux.mjs} +5 -12
- package/build/{diff-Db1AmXuk.mjs.map → diff-ChsL3yux.mjs.map} +1 -1
- package/build/{extract-D4J0D0IZ.mjs → extract-DO-NFOmF.mjs} +7 -12
- package/build/{extract-D4J0D0IZ.mjs.map → extract-DO-NFOmF.mjs.map} +1 -1
- package/build/hours.d.mts +0 -2
- package/build/hours.mjs +1 -2
- package/build/{html-Dir5QEi0.mjs → html-CawWTgMQ.mjs} +4 -6
- package/build/{html-Dir5QEi0.mjs.map → html-CawWTgMQ.mjs.map} +1 -1
- package/build/{html-o5bDHjNi.d.mts → html-oS_ueu9U.d.mts} +2 -20
- package/build/html.d.mts +2 -1
- package/build/html.mjs +2 -2
- package/build/index.d.mts +5 -72
- package/build/index.mjs +20 -19
- package/build/{log-CmBWcyQm.mjs → log-CB5bADmd.mjs} +3 -5
- package/build/{log-CmBWcyQm.mjs.map → log-CB5bADmd.mjs.map} +1 -1
- package/build/{mcp-package-Y0bREnOS.mjs → mcp-package-D9ACY0Ux.mjs} +2 -3
- package/build/{mcp-package-Y0bREnOS.mjs.map → mcp-package-D9ACY0Ux.mjs.map} +1 -1
- package/build/{ollama-D1xRh3hY.mjs → ollama-BDZjLDOK.mjs} +4 -10
- package/build/{ollama-D1xRh3hY.mjs.map → ollama-BDZjLDOK.mjs.map} +1 -1
- package/build/{open-EuCYPZVC.mjs → open-DOgE033K.mjs} +23 -40
- package/build/{open-EuCYPZVC.mjs.map → open-DOgE033K.mjs.map} +1 -1
- package/build/politeness.d.mts +0 -2
- package/build/politeness.mjs +1 -2
- package/build/{recipe-uLu2GLkr.mjs → recipe-BsGOZJyi.mjs} +5 -6
- package/build/{recipe-uLu2GLkr.mjs.map → recipe-BsGOZJyi.mjs.map} +1 -1
- package/build/{recipe-product-C_zv5j3z.mjs → recipe-product-DEDPKMY5.mjs} +7 -9
- package/build/{recipe-product-C_zv5j3z.mjs.map → recipe-product-DEDPKMY5.mjs.map} +1 -1
- package/build/{render-CKE2LILH.mjs → render-CZaqvjQh.mjs} +2 -3
- package/build/{render-CKE2LILH.mjs.map → render-CZaqvjQh.mjs.map} +1 -1
- package/build/robots.d.mts +0 -2
- package/build/robots.mjs +1 -2
- package/build/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
- package/build/{runtime-ByOn76mm.mjs → runtime-NyweI69B.mjs} +13 -20
- package/build/{runtime-ByOn76mm.mjs.map → runtime-NyweI69B.mjs.map} +1 -1
- package/build/signals.d.mts +0 -2
- package/build/signals.mjs +1 -2
- package/build/{transformers-BNiuiLxT.mjs → transformers-C_ziG8yf.mjs} +4 -9
- package/build/{transformers-BNiuiLxT.mjs.map → transformers-C_ziG8yf.mjs.map} +1 -1
- package/build/urls.d.mts +28 -0
- package/build/{urls-BHFeSyEK.mjs → urls.mjs} +3 -4
- package/build/urls.mjs.map +1 -0
- package/build/{version-D4u8ScwH.mjs → version-hVv3n9O6.mjs} +4 -6
- package/build/{version-D4u8ScwH.mjs.map → version-hVv3n9O6.mjs.map} +1 -1
- package/build/{wacz-DlGT0YXp.mjs → wacz-Blvh5qwS.mjs} +7 -9
- package/build/{wacz-DlGT0YXp.mjs.map → wacz-Blvh5qwS.mjs.map} +1 -1
- package/build/{warc-Cq3gO3NK.mjs → warc-DiE1M5le.mjs} +7 -17
- package/build/{warc-Cq3gO3NK.mjs.map → warc-DiE1M5le.mjs.map} +1 -1
- package/build/{webbotauth-Dq_dA_u3.mjs → webbotauth-W3GXY3dy.mjs} +4 -11
- package/build/{webbotauth-Dq_dA_u3.mjs.map → webbotauth-W3GXY3dy.mjs.map} +1 -1
- package/package.json +5 -1
- package/build/urls-BHFeSyEK.mjs.map +0 -1
package/build/index.d.mts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { Outcome } from "./classify.mjs";
|
|
2
|
-
import { DAYS, Day, Hours, HoursComparison, Interval, Week, compareHours, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText, toHoursWeek } from "./hours.mjs";
|
|
3
|
-
import { c as bodyEncoding, i as extractPage, l as decodeBody, n as PageExtract, o as typesOf, r as PageLink, u as ScopeOptions } from "./html-o5bDHjNi.mjs";
|
|
4
2
|
import { AiInput, Signals } from "./signals.mjs";
|
|
5
3
|
import { Clock, DEFAULT_POLICY, HostCounts, HostResult, HostStateStore, HostStop, MemoryHostStateStore, PolicyOptions, PolitenessPolicy, VALIDATOR_MEMO, ValidatorAnswer, ValidatorLimits, ValidatorMemo, ValidatorReport, ValidatorVerdict, nextValidatorMemo, realClock } from "./politeness.mjs";
|
|
6
4
|
import { ALLOW_ALL, Robots, RobotsDecision, RobotsGroup, RobotsRule, RobotsSignal, decide, parseRobots } from "./robots.mjs";
|
|
5
|
+
import { ScopeOptions, cacheKeyOf, canonicalUrl, siteOf } from "./urls.mjs";
|
|
6
|
+
import { DAYS, Day, Hours, HoursComparison, Interval, Week, compareHours, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText, toHoursWeek } from "./hours.mjs";
|
|
7
|
+
import { c as bodyEncoding, i as extractPage, l as decodeBody, n as PageExtract, o as typesOf, r as PageLink } from "./html-oS_ueu9U.mjs";
|
|
7
8
|
import { JsonWebKeyInput, KeyObject } from "node:crypto";
|
|
8
9
|
import { Dispatcher } from "undici";
|
|
9
10
|
import { LookupAddress, LookupAllOptions } from "node:dns";
|
|
10
11
|
import { LookupFunction } from "node:net";
|
|
11
|
-
//#region src/blobs.d.ts
|
|
12
12
|
/**
|
|
13
13
|
* A blob store keeps the bytes of each response, and the hash of the bytes is the key. The crawler
|
|
14
14
|
* needs only these two operations, so an application can give its own store.
|
|
@@ -57,8 +57,6 @@ export declare class FileBlobStore implements BlobStore {
|
|
|
57
57
|
private write;
|
|
58
58
|
get(hash: string): Promise<Uint8Array | undefined>;
|
|
59
59
|
}
|
|
60
|
-
//#endregion
|
|
61
|
-
//#region src/render.d.ts
|
|
62
60
|
/**
|
|
63
61
|
* The renderer opens the headless browser only for a page that shows almost nothing without
|
|
64
62
|
* JavaScript. The settings:
|
|
@@ -170,8 +168,6 @@ export declare const playwrightRenderer: (options?: {
|
|
|
170
168
|
*/
|
|
171
169
|
readonly launch?: (() => Promise<object>) | undefined;
|
|
172
170
|
}) => PlaywrightRenderer;
|
|
173
|
-
//#endregion
|
|
174
|
-
//#region src/browser.d.ts
|
|
175
171
|
/**
|
|
176
172
|
* This function tells if the default renderer can start a browser. It gives no value when it can,
|
|
177
173
|
* and the reason when it cannot. The command line and the MCP server use it one time at start.
|
|
@@ -188,8 +184,6 @@ export declare const browserMissing: (load?: () => Promise<{
|
|
|
188
184
|
executablePath(): string;
|
|
189
185
|
};
|
|
190
186
|
}>) => Promise<string | undefined>;
|
|
191
|
-
//#endregion
|
|
192
|
-
//#region src/duration.d.ts
|
|
193
187
|
/** A duration is a count of milliseconds, or a text, for example `"30m"`, `"24h"` or `"7d"`. */
|
|
194
188
|
type Duration = number | string;
|
|
195
189
|
/**
|
|
@@ -203,8 +197,6 @@ type Duration = number | string;
|
|
|
203
197
|
* @beta
|
|
204
198
|
*/
|
|
205
199
|
export declare const durationMs: (duration: Duration) => number;
|
|
206
|
-
//#endregion
|
|
207
|
-
//#region src/record.d.ts
|
|
208
200
|
/**
|
|
209
201
|
* A capture record is one line of the capture log. Each fetch decision makes one record, and a
|
|
210
202
|
* fetch that the crawler declines makes one too.
|
|
@@ -259,8 +251,6 @@ interface RecordInput {
|
|
|
259
251
|
* @beta
|
|
260
252
|
*/
|
|
261
253
|
export declare const makeRecord: (input: RecordInput) => CaptureRecord;
|
|
262
|
-
//#endregion
|
|
263
|
-
//#region src/log.d.ts
|
|
264
254
|
/** A scan filter selects the records of one source, one kind, or the records after one time. */
|
|
265
255
|
interface CaptureFilter {
|
|
266
256
|
readonly source?: string | undefined;
|
|
@@ -347,8 +337,6 @@ export declare class CaptureLog implements CaptureReader {
|
|
|
347
337
|
/** This method writes the appends in progress, then closes the files. A later append opens them again. */
|
|
348
338
|
close(): Promise<void>;
|
|
349
339
|
}
|
|
350
|
-
//#endregion
|
|
351
|
-
//#region src/runtime.d.ts
|
|
352
340
|
/**
|
|
353
341
|
* An extractor changes one captured body into the documents that it holds. It has no side effects,
|
|
354
342
|
* so `reindex` can replay each capture through it and build the index again with no request. It can
|
|
@@ -748,8 +736,6 @@ interface CatchUpResult extends ReindexResult {
|
|
|
748
736
|
* @beta
|
|
749
737
|
*/
|
|
750
738
|
export declare const catchUpIndex: (runtime: CrawlRuntime) => Promise<CatchUpResult | undefined>;
|
|
751
|
-
//#endregion
|
|
752
|
-
//#region src/fallback.d.ts
|
|
753
739
|
/**
|
|
754
740
|
* The archived fallback. When a site refuses a page, or is down, the crawler can give a copy from a
|
|
755
741
|
* public web archive: the Wayback Machine, then Common Crawl. The crawler does not show the copy as a fresh fetch:
|
|
@@ -801,8 +787,6 @@ export declare const archivedDocId: (url: string) => string;
|
|
|
801
787
|
* @beta
|
|
802
788
|
*/
|
|
803
789
|
export declare const archiveExtractor: Extractor;
|
|
804
|
-
//#endregion
|
|
805
|
-
//#region src/fold.d.ts
|
|
806
790
|
/** @beta */
|
|
807
791
|
interface Verified {
|
|
808
792
|
readonly found: boolean;
|
|
@@ -822,8 +806,6 @@ interface Verified {
|
|
|
822
806
|
* @beta
|
|
823
807
|
*/
|
|
824
808
|
export declare const locate: (text: string, quote: string) => Verified;
|
|
825
|
-
//#endregion
|
|
826
|
-
//#region src/docs.d.ts
|
|
827
809
|
/** This is one document, as an extractor gives it. */
|
|
828
810
|
interface ExtractedDoc {
|
|
829
811
|
readonly doc: string;
|
|
@@ -1280,8 +1262,6 @@ export declare class DocIndex implements ReadingIndex {
|
|
|
1280
1262
|
/** This method closes the file. A second close does nothing. */
|
|
1281
1263
|
close(): void;
|
|
1282
1264
|
}
|
|
1283
|
-
//#endregion
|
|
1284
|
-
//#region src/egress.d.ts
|
|
1285
1265
|
/**
|
|
1286
1266
|
* The egress policy keeps the crawler on the public internet. A page or an agent can ask for an
|
|
1287
1267
|
* internal address. Examples are a loopback service, a router on the LAN and the metadata
|
|
@@ -1330,8 +1310,6 @@ type EgressResolve = (host: string, options: LookupAllOptions, callback: (error:
|
|
|
1330
1310
|
* @beta
|
|
1331
1311
|
*/
|
|
1332
1312
|
export declare const egressLookup: (policy: EgressOptions, resolve?: EgressResolve) => LookupFunction;
|
|
1333
|
-
//#endregion
|
|
1334
|
-
//#region src/webbotauth.d.ts
|
|
1335
1313
|
/**
|
|
1336
1314
|
* Signed requests: HTTP Message Signatures (RFC 9421), as the IETF Web Bot Auth profile tells
|
|
1337
1315
|
* (`draft-ietf-webbotauth-httpsig-protocol-00`, 1 September 2026). A signature lets a site verify that
|
|
@@ -1456,8 +1434,6 @@ export declare const createWebBotAuthSigner: (options: WebBotAuthOptions) => Web
|
|
|
1456
1434
|
export declare const verifySignature: (request: SignedRequest, directory: KeyDirectory, options?: {
|
|
1457
1435
|
readonly now?: number | undefined;
|
|
1458
1436
|
}) => SignatureCheck;
|
|
1459
|
-
//#endregion
|
|
1460
|
-
//#region src/crawler.d.ts
|
|
1461
1437
|
/**
|
|
1462
1438
|
* The crawler is a polite fetcher. It sends one request at a time to each host, and it obeys
|
|
1463
1439
|
* robots.txt for web pages. Its `User-Agent` header tells what it is. It asks again with the
|
|
@@ -1914,8 +1890,6 @@ export declare class Crawler {
|
|
|
1914
1890
|
*/
|
|
1915
1891
|
close(): Promise<void>;
|
|
1916
1892
|
}
|
|
1917
|
-
//#endregion
|
|
1918
|
-
//#region src/diff.d.ts
|
|
1919
1893
|
/**
|
|
1920
1894
|
* A diff compares two versions of a stored document. It gives the changes of the text as a line
|
|
1921
1895
|
* diff, with a word diff inside each changed line. It gives the changes of the title, the URL and
|
|
@@ -2107,8 +2081,6 @@ export declare const diffDocument: (runtime: CrawlRuntime, id: string, options?:
|
|
|
2107
2081
|
* @beta
|
|
2108
2082
|
*/
|
|
2109
2083
|
export declare const formatDiff: (diff: Pick<DiffResult, "summary" | "hunks" | "meta">) => string;
|
|
2110
|
-
//#endregion
|
|
2111
|
-
//#region src/sitemaps.d.ts
|
|
2112
2084
|
/**
|
|
2113
2085
|
* The sitemap reader reads the files that list the pages of a site. These are an XML sitemap, a
|
|
2114
2086
|
* sitemap index, an RSS 2.0 or RSS 1.0 feed and an Atom feed. A text sitemap with one URL on each
|
|
@@ -2194,8 +2166,6 @@ export declare const feedDate: (value: string) => string | null;
|
|
|
2194
2166
|
* @beta
|
|
2195
2167
|
*/
|
|
2196
2168
|
export declare const readSitemap: (text: string, base: string, limits?: SitemapLimits) => SitemapRead;
|
|
2197
|
-
//#endregion
|
|
2198
|
-
//#region src/discover.d.ts
|
|
2199
2169
|
/**
|
|
2200
2170
|
* Discovery finds the pages of a site from its sitemaps and its feeds. Each file is a fetch of the
|
|
2201
2171
|
* crawler, so each polite rule applies to it. These rules are robots.txt, one request at a time for
|
|
@@ -2342,8 +2312,6 @@ interface DiscoverResult {
|
|
|
2342
2312
|
* @beta
|
|
2343
2313
|
*/
|
|
2344
2314
|
export declare const discoverSite: (runtime: CrawlRuntime, site: string, options?: DiscoverRunOptions) => Promise<DiscoverResult>;
|
|
2345
|
-
//#endregion
|
|
2346
|
-
//#region src/embed.d.ts
|
|
2347
2315
|
/**
|
|
2348
2316
|
* The parts of hybrid search that need no store: the embedder interface, the chunks of a text, and
|
|
2349
2317
|
* the fusion of ranked lists.
|
|
@@ -2486,8 +2454,6 @@ interface FusedRank {
|
|
|
2486
2454
|
* @beta
|
|
2487
2455
|
*/
|
|
2488
2456
|
export declare const fuseRanks: (lists: ReadonlyArray<readonly string[]>, k?: number) => FusedRank[];
|
|
2489
|
-
//#endregion
|
|
2490
|
-
//#region src/extract.d.ts
|
|
2491
2457
|
/**
|
|
2492
2458
|
* The field check takes the values that a caller proposes for the fields of a stored page. It finds
|
|
2493
2459
|
* each value in the stored text or in the JSON-LD. A model or a person gives the values. The check
|
|
@@ -2663,8 +2629,6 @@ export declare const checkFields: (source: ExtractSource, fields: Readonly<Recor
|
|
|
2663
2629
|
* @beta
|
|
2664
2630
|
*/
|
|
2665
2631
|
export declare const extractDocument: (runtime: CrawlRuntime, id: string, fields: Readonly<Record<string, FieldClaim>>, options?: ExtractOptions) => Promise<ExtractResult>;
|
|
2666
|
-
//#endregion
|
|
2667
|
-
//#region src/frontier.d.ts
|
|
2668
2632
|
/**
|
|
2669
2633
|
* The frontier is a small crawl of a site. It starts at the seeds. It follows the links of each page
|
|
2670
2634
|
* that it fetched, to a maximum of pages, a maximum depth and a maximum time.
|
|
@@ -2806,8 +2770,6 @@ interface CrawlRun extends AsyncIterable<CrawlPage> {
|
|
|
2806
2770
|
* @beta
|
|
2807
2771
|
*/
|
|
2808
2772
|
export declare const crawlSite: (runtime: CrawlRuntime, seeds: string | readonly string[], options?: CrawlRunOptions) => CrawlRun;
|
|
2809
|
-
//#endregion
|
|
2810
|
-
//#region src/vectors.d.ts
|
|
2811
2773
|
/**
|
|
2812
2774
|
* The vector store keeps the vectors of hybrid search in `vectors.sqlite`, beside the index. It is
|
|
2813
2775
|
* a projection, as the index is. Delete the file, and the next hybrid search or `embed` makes the
|
|
@@ -2954,8 +2916,6 @@ export declare class VectorStore {
|
|
|
2954
2916
|
/** This method closes the file. A second close does nothing. */
|
|
2955
2917
|
close(): void;
|
|
2956
2918
|
}
|
|
2957
|
-
//#endregion
|
|
2958
|
-
//#region src/hybrid.d.ts
|
|
2959
2919
|
/**
|
|
2960
2920
|
* Hybrid search ranks the stored documents two times and fuses the two lists:
|
|
2961
2921
|
*
|
|
@@ -3052,8 +3012,6 @@ interface HybridSearchOptions {
|
|
|
3052
3012
|
* @beta
|
|
3053
3013
|
*/
|
|
3054
3014
|
export declare const createHybridSearch: (runtime: CrawlRuntime, options: HybridSearchOptions) => HybridSearch;
|
|
3055
|
-
//#endregion
|
|
3056
|
-
//#region src/recipe.d.ts
|
|
3057
3015
|
/** The capture that an extractor reads: the final URL of the response and its content type. */
|
|
3058
3016
|
interface RecipeCapture {
|
|
3059
3017
|
readonly url: string;
|
|
@@ -3249,8 +3207,6 @@ type RecipeTarget = CrawlRuntime | {
|
|
|
3249
3207
|
* captures. Thus its documents do not mix a live answer and an old copy of a third party.
|
|
3250
3208
|
*/
|
|
3251
3209
|
export declare const runRecipe: <Input>(target: RecipeTarget, recipe: Recipe<Input>, input: Input, options?: RecipeRunOptions) => Promise<RecipeResult>;
|
|
3252
|
-
//#endregion
|
|
3253
|
-
//#region src/watch.d.ts
|
|
3254
3210
|
/**
|
|
3255
3211
|
* A watch list keeps the pages that the crawler checks again on a schedule. `watch.run` fetches the
|
|
3256
3212
|
* pages that are due through the normal fetch, so each polite rule applies. It gives an event for
|
|
@@ -3612,16 +3568,12 @@ export declare class WatchStore {
|
|
|
3612
3568
|
* @beta
|
|
3613
3569
|
*/
|
|
3614
3570
|
export declare const runWatch: (runtime: CrawlRuntime, source: WatchStore | (() => Promise<WatchStore>), options?: WatchRunnerOptions) => WatchRun;
|
|
3615
|
-
//#endregion
|
|
3616
|
-
//#region src/version.d.ts
|
|
3617
3571
|
/** This is the version of the package. A test makes sure that it agrees with `package.json`. */
|
|
3618
|
-
export declare const VERSION = "0.5.
|
|
3572
|
+
export declare const VERSION = "0.5.1";
|
|
3619
3573
|
/** This is the product token that robots.txt rules match when an application gives no token. */
|
|
3620
3574
|
export declare const DEFAULT_TOKEN = "PoliteCrawler";
|
|
3621
3575
|
/** This page tells a site owner what the crawler is and how to control it. */
|
|
3622
3576
|
export declare const BOT_PAGE = "https://mark1russell7.github.io/crawler/bot/";
|
|
3623
|
-
//#endregion
|
|
3624
|
-
//#region src/open.d.ts
|
|
3625
3577
|
/**
|
|
3626
3578
|
* This function gives the default `User-Agent` header. The header names the crawler, its version
|
|
3627
3579
|
* and the page about it, so a site owner can find out what made each request.
|
|
@@ -3917,8 +3869,6 @@ interface HybridCrawler extends OpenedCrawler {
|
|
|
3917
3869
|
* rejects.
|
|
3918
3870
|
*/
|
|
3919
3871
|
export declare const openCrawler: (options: OpenOptions) => HybridCrawler;
|
|
3920
|
-
//#endregion
|
|
3921
|
-
//#region src/daemon.d.ts
|
|
3922
3872
|
/** These are the defaults of the daemon. */
|
|
3923
3873
|
export declare const DAEMON_DEFAULTS: {
|
|
3924
3874
|
/** The longest wait between two ticks: 1 minute. A tick comes sooner when an entry is due sooner. */
|
|
@@ -4230,8 +4180,6 @@ interface Daemon {
|
|
|
4230
4180
|
* stops cleanly (`stop`). A second signal aborts the checks at once.
|
|
4231
4181
|
*/
|
|
4232
4182
|
export declare const startDaemon: (options: DaemonOptions) => Promise<Daemon>;
|
|
4233
|
-
//#endregion
|
|
4234
|
-
//#region src/ollama.d.ts
|
|
4235
4183
|
/**
|
|
4236
4184
|
* The Ollama embedder sends texts to the local HTTP API of Ollama (`POST /api/embed`). The package
|
|
4237
4185
|
* has no dependency for it: you install Ollama, start it (`ollama serve`) and pull a model
|
|
@@ -4290,8 +4238,6 @@ export declare const isLoopback: (host: string) => boolean;
|
|
|
4290
4238
|
* there. A `baseUrl` on a different computer throws a `RangeError`, unless `allowRemote` is true.
|
|
4291
4239
|
*/
|
|
4292
4240
|
export declare const ollamaEmbedder: (options?: OllamaEmbedderOptions) => Embedder;
|
|
4293
|
-
//#endregion
|
|
4294
|
-
//#region src/transformers.d.ts
|
|
4295
4241
|
/**
|
|
4296
4242
|
* The transformers embedder uses an embedding model in this process, with transformers.js
|
|
4297
4243
|
* (`@huggingface/transformers`). The package is an optional peer: the embedder loads it at its
|
|
@@ -4367,8 +4313,6 @@ interface TransformersModule {
|
|
|
4367
4313
|
* between two batches.
|
|
4368
4314
|
*/
|
|
4369
4315
|
export declare const transformersEmbedder: (options?: TransformersEmbedderOptions, load?: () => Promise<TransformersModule>) => Embedder;
|
|
4370
|
-
//#endregion
|
|
4371
|
-
//#region src/hoststate.d.ts
|
|
4372
4316
|
/**
|
|
4373
4317
|
* These options change a SQLite host state store.
|
|
4374
4318
|
*
|
|
@@ -4433,8 +4377,6 @@ export declare class SqliteHostStateStore implements HostStateStore {
|
|
|
4433
4377
|
/** This method closes the file. A second close does nothing. */
|
|
4434
4378
|
close(): void;
|
|
4435
4379
|
}
|
|
4436
|
-
//#endregion
|
|
4437
|
-
//#region src/pdf.d.ts
|
|
4438
4380
|
/**
|
|
4439
4381
|
* The crawler reads the text of a PDF. Restaurant menus are often PDFs: 29 of 231 surveyed
|
|
4440
4382
|
* restaurant sites link one. A menu that the crawler reads one time stays searchable. A paper in a
|
|
@@ -4482,8 +4424,6 @@ interface PdfOptions {
|
|
|
4482
4424
|
export declare const isPdf: (body: Uint8Array, contentType: string | null) => boolean;
|
|
4483
4425
|
/** @beta */
|
|
4484
4426
|
export declare const readPdf: (bytes: Uint8Array, options?: PdfOptions) => Promise<PdfText>;
|
|
4485
|
-
//#endregion
|
|
4486
|
-
//#region src/recipe-venue.d.ts
|
|
4487
4427
|
/**
|
|
4488
4428
|
* These are the limits of the venue recipe.
|
|
4489
4429
|
*
|
|
@@ -4704,8 +4644,6 @@ interface VenueResult {
|
|
|
4704
4644
|
* the application.
|
|
4705
4645
|
*/
|
|
4706
4646
|
export declare const readVenue: (target: RecipeTarget, url: string, options?: VenueOptions) => Promise<VenueResult>;
|
|
4707
|
-
//#endregion
|
|
4708
|
-
//#region src/recipe-product.d.ts
|
|
4709
4647
|
/** This is a JSON object, for example a schema.org record of a page. */
|
|
4710
4648
|
type JsonRecord = Readonly<Record<string, unknown>>;
|
|
4711
4649
|
/**
|
|
@@ -4868,8 +4806,6 @@ interface ProductResult extends Omit<ProductRead, "steps" | "notes"> {
|
|
|
4868
4806
|
* capture log. `extract` can check each value against the stored page.
|
|
4869
4807
|
*/
|
|
4870
4808
|
export declare const readProduct: (target: RecipeTarget, url: string, options?: ProductOptions) => Promise<ProductResult>;
|
|
4871
|
-
//#endregion
|
|
4872
|
-
//#region src/warc.d.ts
|
|
4873
4809
|
/** The source of an export: the folder of a store, or the capture log and the blob store of a runtime. */
|
|
4874
4810
|
type ArchiveSource = string | {
|
|
4875
4811
|
readonly captures: CaptureReader;
|
|
@@ -4933,8 +4869,6 @@ interface WarcResult extends ArchiveCounts {
|
|
|
4933
4869
|
* (`crawler.runtime`). The export only reads the store.
|
|
4934
4870
|
*/
|
|
4935
4871
|
export declare const exportWarc: (source: ArchiveSource, options: ArchiveOptions) => Promise<WarcResult>;
|
|
4936
|
-
//#endregion
|
|
4937
|
-
//#region src/wacz.d.ts
|
|
4938
4872
|
/** This is the result of `exportWacz`. */
|
|
4939
4873
|
interface WaczResult extends ArchiveCounts {
|
|
4940
4874
|
readonly format: "wacz";
|
|
@@ -4957,6 +4891,5 @@ interface WaczResult extends ArchiveCounts {
|
|
|
4957
4891
|
* The export writes temporary files beside `out` and removes them at the end.
|
|
4958
4892
|
*/
|
|
4959
4893
|
export declare const exportWacz: (source: ArchiveSource, options: ArchiveOptions) => Promise<WaczResult>;
|
|
4960
|
-
|
|
4961
|
-
export { ALLOW_ALL, type AiInput, type ArchiveCounts, type ArchiveFilter, type ArchiveOptions, type ArchiveSource, type Archived, type BlobStore, type CacheEntry, type CacheIndex, type CaptureFilter, type CaptureLogOptions, type CapturePayload, type CaptureReader, type CaptureRecord, type CaptureWriter, type CatchUpResult, type ChangeCommandOptions, type Changefreq, type ChunkOptions, type Clock, type CrawlEvent, type CrawlOptions, type CrawlPage, type CrawlRun, type CrawlRunOptions, type CrawlRuntime, type CrawlStop, type CrawlSummary, type CrawlerOptions, DAYS, DEFAULT_POLICY, type Daemon, type DaemonDue, type DaemonMcpHooks, type DaemonMcpHost, type DaemonMcpOptions, type DaemonMcpService, type DaemonOptions, type DaemonState, type DaemonStatus, type DaemonTask, type DaemonTick, type DamagedLine, type Day, type DiffHunk, type DiffInput, type DiffLimits, type DiffLine, type DiffOptions, type DiffResult, type DiffSide, type DiffSummary, type DigestOptions, type DirectoryKey, type DiscoverOptions, type DiscoverResult, type DiscoverRunOptions, type DiscoverSource, type DiscoverStop, type DiscoveredUrl, type Doc, type DocDigest, type DocIndexOptions, type DocInput, type DocVersion, type Duration, type EgressOptions, type EgressResolve, type EmbedCallOptions, type EmbedOptions, type EmbedResult, type EmbedStop, type Embedder, type EmbeddingModel, type ExtractOptions, type ExtractResult, type ExtractSource, type ExtractSummary, type ExtractedDoc, type Extractor, type FeatureExtractor, type FetchOptions, type FetchOutcome, type FetchRequest, type Fetched, type FieldCandidate, type FieldCheck, type FieldClaim, type FieldKind, type FieldResult, type FieldSpan, type FieldStatus, type FieldsChecked, type FileBlobStoreOptions, type FindIndexOptions, type FindOptions, type Found, type FusedRank, type HostCounts, type HostResult, type HostStateStore, type HostStop, type Hours, type HoursComparison, type HybridCrawler, type HybridFindOptions, type HybridOptions, type HybridSearch, type HybridSearchOptions, type IndexBuild, type IndexCounts, type Indexed, type Interval, type JsonRecord, type JwkInput, type KeyDirectory, type KeyInput, type Latest, MemoryHostStateStore, type MetaChange, type Money, type OllamaEmbedderOptions, type OpenOptions, type OpenedCrawler, type Outcome, type PageExtract, type PageLink, type PageOptions, type PageResult, type Passage, type PdfOptions, type PdfText, type PlaywrightRenderer, type PolicyOptions, type PoliteCrawler, type PolitenessPolicy, type Pooling, type ProductOptions, type ProductRead, type ProductResult, type ProductVariant, type RankMode, type RankOptions, type Ranked, type ReadOptions, type ReadResult, type ReadingIndex, type Recipe, type RecipeCapture, type RecipeDefinition, type RecipeDoc, type RecipeExtract, type RecipeRequest, type RecipeRequestOptions, type RecipeResult, type RecipeRunOptions, type RecipeTarget, type RecordInput, type RefusedReason, type ReindexResult, type RenderOptions, type RenderRequest, type Rendered, type Renderer, type RequestSigner, type Robots, type RobotsDecision, type RobotsGroup, type RobotsRule, type RobotsSignal, type RuntimeOptions, type ScanOptions, type ScheduleOptions, type ScheduleResult, type ScopeOptions, type SearchOptions, type SearchRank, type Signals, type SignatureAgentType, type SignatureCheck, type SignedRequest, type SitemapEntry, type SitemapKind, type SitemapLimits, type SitemapRead, type SqliteHostStateOptions, type StoreRuntime, type StoredChunk, type TextChunk, type TextDiff, type TransformersEmbedderOptions, type TransformersModule, type UrlPattern, VALIDATOR_MEMO, type ValidatorAnswer, type ValidatorLimits, type ValidatorMemo, type ValidatorReport, type ValidatorVerdict, type Variant, type VectorCounts, type VectorHit, type VectorStoreOptions, type VectorWrite, type VenueLink, type VenueLocation, type VenueOptions, type VenueOsm, type VenuePage, type VenueRead, type VenueReading, type VenueResult, type VenueSource, type Verified, type VerifyOptions, type VerifyResult, type VersionAt, type VersionChoice, type VersionText, type WaczResult, type WarcResult, type WatchEntry, type WatchEvent, type WatchKind, type WatchList, type WatchOptions, type WatchPending, type WatchRescheduleOptions, type WatchRow, type WatchRun, type WatchRunOptions, type WatchRunnerOptions, type WatchSchedule, type WatchState, type WatchStop, type WatchStoreOptions, type WatchSummary, type WatchUpdate, type WebArchive, type WebBotAuthOptions, type WebBotAuthSigner, type Week, type WordPart, bodyEncoding, compareHours, decide, decodeBody, describeWeek, disagreements, extractPage, fromCompact, fromSchemaOrg, fromText, nextValidatorMemo, parseRobots, realClock, toHoursWeek, typesOf };
|
|
4894
|
+
export { ALLOW_ALL, type AiInput, type ArchiveCounts, type ArchiveFilter, type ArchiveOptions, type ArchiveSource, type Archived, type BlobStore, type CacheEntry, type CacheIndex, type CaptureFilter, type CaptureLogOptions, type CapturePayload, type CaptureReader, type CaptureRecord, type CaptureWriter, type CatchUpResult, type ChangeCommandOptions, type Changefreq, type ChunkOptions, type Clock, type CrawlEvent, type CrawlOptions, type CrawlPage, type CrawlRun, type CrawlRunOptions, type CrawlRuntime, type CrawlStop, type CrawlSummary, type CrawlerOptions, DAYS, DEFAULT_POLICY, type Daemon, type DaemonDue, type DaemonMcpHooks, type DaemonMcpHost, type DaemonMcpOptions, type DaemonMcpService, type DaemonOptions, type DaemonState, type DaemonStatus, type DaemonTask, type DaemonTick, type DamagedLine, type Day, type DiffHunk, type DiffInput, type DiffLimits, type DiffLine, type DiffOptions, type DiffResult, type DiffSide, type DiffSummary, type DigestOptions, type DirectoryKey, type DiscoverOptions, type DiscoverResult, type DiscoverRunOptions, type DiscoverSource, type DiscoverStop, type DiscoveredUrl, type Doc, type DocDigest, type DocIndexOptions, type DocInput, type DocVersion, type Duration, type EgressOptions, type EgressResolve, type EmbedCallOptions, type EmbedOptions, type EmbedResult, type EmbedStop, type Embedder, type EmbeddingModel, type ExtractOptions, type ExtractResult, type ExtractSource, type ExtractSummary, type ExtractedDoc, type Extractor, type FeatureExtractor, type FetchOptions, type FetchOutcome, type FetchRequest, type Fetched, type FieldCandidate, type FieldCheck, type FieldClaim, type FieldKind, type FieldResult, type FieldSpan, type FieldStatus, type FieldsChecked, type FileBlobStoreOptions, type FindIndexOptions, type FindOptions, type Found, type FusedRank, type HostCounts, type HostResult, type HostStateStore, type HostStop, type Hours, type HoursComparison, type HybridCrawler, type HybridFindOptions, type HybridOptions, type HybridSearch, type HybridSearchOptions, type IndexBuild, type IndexCounts, type Indexed, type Interval, type JsonRecord, type JwkInput, type KeyDirectory, type KeyInput, type Latest, MemoryHostStateStore, type MetaChange, type Money, type OllamaEmbedderOptions, type OpenOptions, type OpenedCrawler, type Outcome, type PageExtract, type PageLink, type PageOptions, type PageResult, type Passage, type PdfOptions, type PdfText, type PlaywrightRenderer, type PolicyOptions, type PoliteCrawler, type PolitenessPolicy, type Pooling, type ProductOptions, type ProductRead, type ProductResult, type ProductVariant, type RankMode, type RankOptions, type Ranked, type ReadOptions, type ReadResult, type ReadingIndex, type Recipe, type RecipeCapture, type RecipeDefinition, type RecipeDoc, type RecipeExtract, type RecipeRequest, type RecipeRequestOptions, type RecipeResult, type RecipeRunOptions, type RecipeTarget, type RecordInput, type RefusedReason, type ReindexResult, type RenderOptions, type RenderRequest, type Rendered, type Renderer, type RequestSigner, type Robots, type RobotsDecision, type RobotsGroup, type RobotsRule, type RobotsSignal, type RuntimeOptions, type ScanOptions, type ScheduleOptions, type ScheduleResult, type ScopeOptions, type SearchOptions, type SearchRank, type Signals, type SignatureAgentType, type SignatureCheck, type SignedRequest, type SitemapEntry, type SitemapKind, type SitemapLimits, type SitemapRead, type SqliteHostStateOptions, type StoreRuntime, type StoredChunk, type TextChunk, type TextDiff, type TransformersEmbedderOptions, type TransformersModule, type UrlPattern, VALIDATOR_MEMO, type ValidatorAnswer, type ValidatorLimits, type ValidatorMemo, type ValidatorReport, type ValidatorVerdict, type Variant, type VectorCounts, type VectorHit, type VectorStoreOptions, type VectorWrite, type VenueLink, type VenueLocation, type VenueOptions, type VenueOsm, type VenuePage, type VenueRead, type VenueReading, type VenueResult, type VenueSource, type Verified, type VerifyOptions, type VerifyResult, type VersionAt, type VersionChoice, type VersionText, type WaczResult, type WarcResult, type WatchEntry, type WatchEvent, type WatchKind, type WatchList, type WatchOptions, type WatchPending, type WatchRescheduleOptions, type WatchRow, type WatchRun, type WatchRunOptions, type WatchRunnerOptions, type WatchSchedule, type WatchState, type WatchStop, type WatchStoreOptions, type WatchSummary, type WatchUpdate, type WebArchive, type WebBotAuthOptions, type WebBotAuthSigner, type Week, type WordPart, bodyEncoding, cacheKeyOf, canonicalUrl, compareHours, decide, decodeBody, describeWeek, disagreements, extractPage, fromCompact, fromSchemaOrg, fromText, nextValidatorMemo, parseRobots, realClock, siteOf, toHoursWeek, typesOf };
|
|
4962
4895
|
//# sourceMappingURL=index.d.mts.map
|
package/build/index.mjs
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
|
-
import { n as FileBlobStore, t as CaptureLog } from "./log-
|
|
2
|
-
import {
|
|
3
|
-
import { t as
|
|
4
|
-
import { i as
|
|
5
|
-
import {
|
|
1
|
+
import { n as FileBlobStore, t as CaptureLog } from "./log-CB5bADmd.mjs";
|
|
2
|
+
import { t as browserMissing } from "./browser-Cp5W-dmj.mjs";
|
|
3
|
+
import { c as startDaemon, i as daemonStateFile, n as DAEMON_STATE_SCHEMA, o as readDaemonState, r as changeCommand, s as scheduleWatches, t as DAEMON_DEFAULTS } from "./daemon-DNGSr4hR.mjs";
|
|
4
|
+
import { A as DEADLINE_NOTE, F as EgressRefused, I as egressLookup, M as makeRecord, O as CAPTURE_SCHEMA, S as readPdf, T as locate, _ as archivedDocId, a as fetchPage, c as isHeldBack, d as recordOverride, f as reindex, h as archiveExtractor, i as fetchAndIndex, j as DEFAULT_SECRET_PARAMS, k as Crawler, l as isoTime, m as versionAtTime, n as HELD_BACK, o as findDocuments, p as verifyQuote, r as catchUpIndex, s as heldBackMeta, t as Extractors, u as readDocument, x as isPdf } from "./runtime-NyweI69B.mjs";
|
|
5
|
+
import { a as formatDiff, n as diffDocument, r as diffTexts, t as DIFF_LIMITS } from "./diff-ChsL3yux.mjs";
|
|
6
|
+
import { A as NO_EMBEDDER, C as DISCOVER_LIMITS, D as readSitemap, E as feedDate, O as DocIndex, S as crawlSite, T as SITEMAP_LIMITS, _ as estimateTokens, b as SqliteHostStateStore, c as WatchStore, d as VectorStore, f as createHybridSearch, g as chunkTokensOf, h as chunkText, i as openCrawler, k as FAST_RANK_SHARE, l as runWatch, m as HYBRID_DEFAULTS, n as defaultUserAgent, o as WATCH_LIMITS, p as CHUNK_LIMITS, r as isMailbox, s as WATCH_SCHEMA, t as createRuntime, u as VECTORS_SCHEMA, v as fuseRanks, w as discoverSite, x as CRAWL_LIMITS, y as unitVector } from "./open-DOgE033K.mjs";
|
|
7
|
+
import { i as ollamaEmbedder, n as OLLAMA_MODELS, r as isLoopback, t as NO_OLLAMA } from "./ollama-BDZjLDOK.mjs";
|
|
8
|
+
import { n as TRANSFORMERS_MODELS, r as transformersEmbedder, t as NO_TRANSFORMERS } from "./transformers-C_ziG8yf.mjs";
|
|
9
|
+
import { n as checkFields, r as extractDocument, t as FIELD_KINDS } from "./extract-DO-NFOmF.mjs";
|
|
10
|
+
import { DAYS, compareHours, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText, toHoursWeek } from "./hours.mjs";
|
|
11
|
+
import { a as bodyEncoding, o as decodeBody, r as typesOf, t as extractPage } from "./html-CawWTgMQ.mjs";
|
|
6
12
|
import { DEFAULT_POLICY, MemoryHostStateStore, VALIDATOR_MEMO, nextValidatorMemo, realClock } from "./politeness.mjs";
|
|
13
|
+
import { a as readJson, i as defineRecipe, n as RESERVED_RECIPES, o as registerRecipe, s as runRecipe, t as RECIPE_LIMITS } from "./recipe-BsGOZJyi.mjs";
|
|
14
|
+
import { a as readAmount, c as locationMatches, d as readVenue, f as venueReadingsOf, i as productOf, l as namesVenue, n as pickProduct, o as readProduct, r as pickVariant, s as VENUE_LIMITS, t as PRODUCT_LIMITS, u as rankHoursLinks } from "./recipe-product-DEDPKMY5.mjs";
|
|
15
|
+
import { n as RenderRefused, r as playwrightRenderer, t as NO_PLAYWRIGHT } from "./render-CZaqvjQh.mjs";
|
|
7
16
|
import { ALLOW_ALL, decide, parseRobots } from "./robots.mjs";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { n as
|
|
13
|
-
|
|
14
|
-
import { c as startDaemon, i as daemonStateFile, n as DAEMON_STATE_SCHEMA, o as readDaemonState, r as changeCommand, s as scheduleWatches, t as DAEMON_DEFAULTS } from "./daemon-DePmNqn9.mjs";
|
|
15
|
-
import { i as ollamaEmbedder, n as OLLAMA_MODELS, r as isLoopback, t as NO_OLLAMA } from "./ollama-D1xRh3hY.mjs";
|
|
16
|
-
import { n as TRANSFORMERS_MODELS, r as transformersEmbedder, t as NO_TRANSFORMERS } from "./transformers-BNiuiLxT.mjs";
|
|
17
|
-
import { DAYS, compareHours, describeWeek, disagreements, fromCompact, fromSchemaOrg, fromText, toHoursWeek } from "./hours.mjs";
|
|
18
|
-
import { a as readAmount, c as locationMatches, d as readVenue, f as venueReadingsOf, i as productOf, l as namesVenue, n as pickProduct, o as readProduct, r as pickVariant, s as VENUE_LIMITS, t as PRODUCT_LIMITS, u as rankHoursLinks } from "./recipe-product-C_zv5j3z.mjs";
|
|
19
|
-
import { t as exportWacz } from "./wacz-DlGT0YXp.mjs";
|
|
20
|
-
import { n as exportWarc } from "./warc-Cq3gO3NK.mjs";
|
|
21
|
-
export { ALLOW_ALL, BOT_PAGE, CAPTURE_SCHEMA, CHUNK_LIMITS, CRAWL_LIMITS, CaptureLog, Crawler, DAEMON_DEFAULTS, DAEMON_STATE_SCHEMA, DAYS, DEADLINE_NOTE, DEFAULT_POLICY, DEFAULT_SECRET_PARAMS, DEFAULT_TOKEN, DIFF_LIMITS, DISCOVER_LIMITS, DocIndex, EgressRefused, Extractors, FAST_RANK_SHARE, FIELD_KINDS, FileBlobStore, HELD_BACK, HYBRID_DEFAULTS, KEY_DIRECTORY_PATH, KEY_DIRECTORY_TYPE, MemoryHostStateStore, NO_EMBEDDER, NO_OLLAMA, NO_PLAYWRIGHT, NO_TRANSFORMERS, OLLAMA_MODELS, PRODUCT_LIMITS, RECIPE_LIMITS, RESERVED_RECIPES, RenderRefused, SITEMAP_LIMITS, SqliteHostStateStore, TRANSFORMERS_MODELS, VALIDATOR_MEMO, VECTORS_SCHEMA, VENUE_LIMITS, VERSION, VectorStore, WATCH_LIMITS, WATCH_SCHEMA, WatchStore, archiveExtractor, archivedDocId, bodyEncoding, browserMissing, catchUpIndex, changeCommand, checkFields, chunkText, chunkTokensOf, compareHours, crawlSite, createHybridSearch, createRuntime, createWebBotAuthSigner, daemonStateFile, decide, decodeBody, defaultUserAgent, defineRecipe, describeWeek, diffDocument, diffTexts, disagreements, discoverSite, durationMs, egressLookup, estimateTokens, exportWacz, exportWarc, extractDocument, extractPage, feedDate, fetchAndIndex, fetchPage, findDocuments, formatDiff, fromCompact, fromSchemaOrg, fromText, fuseRanks, heldBackMeta, isHeldBack, isLoopback, isMailbox, isPdf, isoTime, keyDirectory, locate, locationMatches, makeRecord, namesVenue, nextValidatorMemo, ollamaEmbedder, openCrawler, parseRobots, pickProduct, pickVariant, playwrightRenderer, productOf, rankHoursLinks, readAmount, readDaemonState, readDocument, readJson, readPdf, readProduct, readSitemap, readVenue, realClock, recordOverride, registerRecipe, reindex, runRecipe, runWatch, scheduleWatches, startDaemon, toHoursWeek, transformersEmbedder, typesOf, unitVector, venueReadingsOf, verifyQuote, verifySignature, versionAtTime };
|
|
17
|
+
import { cacheKeyOf, canonicalUrl, siteOf } from "./urls.mjs";
|
|
18
|
+
import { i as durationMs, n as DEFAULT_TOKEN, r as VERSION, t as BOT_PAGE } from "./version-hVv3n9O6.mjs";
|
|
19
|
+
import { i as keyDirectory, n as KEY_DIRECTORY_TYPE, o as verifySignature, r as createWebBotAuthSigner, t as KEY_DIRECTORY_PATH } from "./webbotauth-W3GXY3dy.mjs";
|
|
20
|
+
import { t as exportWacz } from "./wacz-Blvh5qwS.mjs";
|
|
21
|
+
import { n as exportWarc } from "./warc-DiE1M5le.mjs";
|
|
22
|
+
export { ALLOW_ALL, BOT_PAGE, CAPTURE_SCHEMA, CHUNK_LIMITS, CRAWL_LIMITS, CaptureLog, Crawler, DAEMON_DEFAULTS, DAEMON_STATE_SCHEMA, DAYS, DEADLINE_NOTE, DEFAULT_POLICY, DEFAULT_SECRET_PARAMS, DEFAULT_TOKEN, DIFF_LIMITS, DISCOVER_LIMITS, DocIndex, EgressRefused, Extractors, FAST_RANK_SHARE, FIELD_KINDS, FileBlobStore, HELD_BACK, HYBRID_DEFAULTS, KEY_DIRECTORY_PATH, KEY_DIRECTORY_TYPE, MemoryHostStateStore, NO_EMBEDDER, NO_OLLAMA, NO_PLAYWRIGHT, NO_TRANSFORMERS, OLLAMA_MODELS, PRODUCT_LIMITS, RECIPE_LIMITS, RESERVED_RECIPES, RenderRefused, SITEMAP_LIMITS, SqliteHostStateStore, TRANSFORMERS_MODELS, VALIDATOR_MEMO, VECTORS_SCHEMA, VENUE_LIMITS, VERSION, VectorStore, WATCH_LIMITS, WATCH_SCHEMA, WatchStore, archiveExtractor, archivedDocId, bodyEncoding, browserMissing, cacheKeyOf, canonicalUrl, catchUpIndex, changeCommand, checkFields, chunkText, chunkTokensOf, compareHours, crawlSite, createHybridSearch, createRuntime, createWebBotAuthSigner, daemonStateFile, decide, decodeBody, defaultUserAgent, defineRecipe, describeWeek, diffDocument, diffTexts, disagreements, discoverSite, durationMs, egressLookup, estimateTokens, exportWacz, exportWarc, extractDocument, extractPage, feedDate, fetchAndIndex, fetchPage, findDocuments, formatDiff, fromCompact, fromSchemaOrg, fromText, fuseRanks, heldBackMeta, isHeldBack, isLoopback, isMailbox, isPdf, isoTime, keyDirectory, locate, locationMatches, makeRecord, namesVenue, nextValidatorMemo, ollamaEmbedder, openCrawler, parseRobots, pickProduct, pickVariant, playwrightRenderer, productOf, rankHoursLinks, readAmount, readDaemonState, readDocument, readJson, readPdf, readProduct, readSitemap, readVenue, realClock, recordOverride, registerRecipe, reindex, runRecipe, runWatch, scheduleWatches, siteOf, startDaemon, toHoursWeek, transformersEmbedder, typesOf, unitVector, venueReadingsOf, verifyQuote, verifySignature, versionAtTime };
|
|
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { mkdir, open, readFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { createReadStream, existsSync } from "node:fs";
|
|
5
|
-
|
|
5
|
+
// src/blobs.ts
|
|
6
6
|
const HASH = /^[0-9a-f]{64}$/;
|
|
7
7
|
/** A rename can fail with these codes when a different writer puts the same blob at the same time. */
|
|
8
8
|
const RACE_CODES = /* @__PURE__ */ new Set([
|
|
@@ -122,8 +122,7 @@ var FileBlobStore = class FileBlobStore {
|
|
|
122
122
|
return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
123
123
|
}
|
|
124
124
|
};
|
|
125
|
-
|
|
126
|
-
//#region src/log.ts
|
|
125
|
+
// src/log.ts
|
|
127
126
|
const MONTH_FILE = /^(\d{2})(?:\.[^.]+)?\.ndjson$/;
|
|
128
127
|
const YEAR_DIR = /^\d{4}$/;
|
|
129
128
|
const NEWLINE = 10;
|
|
@@ -340,7 +339,6 @@ var CaptureLog = class CaptureLog {
|
|
|
340
339
|
for (const handle of handles) await handle.close();
|
|
341
340
|
}
|
|
342
341
|
};
|
|
343
|
-
//#endregion
|
|
344
342
|
export { FileBlobStore as n, CaptureLog as t };
|
|
345
343
|
|
|
346
|
-
//# sourceMappingURL=log-
|
|
344
|
+
//# sourceMappingURL=log-CB5bADmd.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-CmBWcyQm.mjs","names":[],"sources":["../src/blobs.ts","../src/log.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport { mkdir, open, readFile, rename, rm, stat } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * A blob store keeps the bytes of each response, and the hash of the bytes is the key. The crawler\n * needs only these two operations, so an application can give its own store.\n */\nexport interface BlobStore {\n put(bytes: Uint8Array): Promise<{ readonly hash: string }>;\n get(hash: string): Promise<Uint8Array | undefined>;\n}\n\n/**\n * These options change a file blob store.\n *\n * @beta\n */\nexport interface FileBlobStoreOptions {\n /** When this value is true (the default), a blob is on the disk (`fsync`) before `put` finishes. */\n readonly sync?: boolean | undefined;\n}\n\nconst HASH = /^[0-9a-f]{64}$/;\n\n/** A rename can fail with these codes when a different writer puts the same blob at the same time. */\nconst RACE_CODES: ReadonlySet<string> = new Set([\n \"EPERM\",\n \"EEXIST\",\n \"EBUSY\",\n \"EACCES\",\n \"ENOTEMPTY\",\n]);\n\nconst blobPath = (root: string, hash: string): string =>\n join(root, hash.slice(0, 2), hash.slice(2, 4), hash);\n\nconst hashOf = (bytes: Uint8Array): string => createHash(\"sha256\").update(bytes).digest(\"hex\");\n\nconst codeOf = (error: unknown): string =>\n typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n\nconst statOf = (path: string): Promise<Stats | undefined> => stat(path).catch(() => undefined);\n\n/** This function writes a folder to the disk, so a rename in it stays after a power cut. Windows cannot open a folder, so it skips this step. */\nconst syncFolder = async (path: string): Promise<void> => {\n if (process.platform === \"win32\") return;\n try {\n const handle = await open(path, \"r\");\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n } catch {\n // a file system that cannot sync a folder keeps the blob in any case\n }\n};\n\n/**\n * This store keeps each blob in a file: `<dir>/ab/cd/abcd…`, where the name is the SHA-256 hash\n * of the bytes. These are its rules:\n *\n * - Equal bytes are written one time only. A file of the wrong size (a write that a crash cut) is\n * written again.\n * - A write goes to a temporary file with a random name, goes to the disk, and then gets its name.\n * A crash thus cannot leave half a blob under its name.\n * - Two writers can put the same bytes at the same time. When the rename of one fails because the\n * other was first, the put succeeds if the stored file has the same hash.\n * - The method `get` examines the hash of the bytes. A damaged file gets a new name\n * (`.damaged`), and `get` gives no bytes, so the crawler fetches the body again.\n *\n * @beta\n */\nexport class FileBlobStore implements BlobStore {\n private readonly writing = new Map<\n string,\n Promise<{ readonly hash: string; readonly existed: boolean }>\n >();\n private readonly sync: boolean;\n\n constructor(\n readonly dir: string,\n options: FileBlobStoreOptions = {},\n ) {\n this.sync = options.sync ?? true;\n }\n\n put(bytes: Uint8Array): Promise<{ readonly hash: string; readonly existed: boolean }> {\n const hash = hashOf(bytes);\n const running = this.writing.get(hash);\n if (running !== undefined) return running;\n const work = this.write(hash, bytes).finally(() => this.writing.delete(hash));\n this.writing.set(hash, work);\n return work;\n }\n\n /** This method tells if a file holds exactly the bytes of a hash. */\n private static async holds(path: string, hash: string): Promise<boolean> {\n try {\n return hashOf(await readFile(path)) === hash;\n } catch {\n return false;\n }\n }\n\n private async write(\n hash: string,\n bytes: Uint8Array,\n ): Promise<{ readonly hash: string; readonly existed: boolean }> {\n const target = blobPath(this.dir, hash);\n const existing = await statOf(target);\n if (existing?.isFile() === true && existing.size === bytes.length)\n return { hash, existed: true };\n const folder = dirname(target);\n await mkdir(folder, { recursive: true, mode: 0o700 });\n const temporary = `${target}.${randomUUID()}.tmp`;\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n await handle.writeFile(bytes);\n if (this.sync) await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await rename(temporary, target);\n } catch (error) {\n // a different writer put the same bytes first, and Windows does not replace a file in use\n if (!RACE_CODES.has(codeOf(error)) || !(await FileBlobStore.holds(target, hash)))\n throw error;\n return { hash, existed: true };\n }\n if (this.sync) await syncFolder(folder);\n return { hash, existed: false };\n } finally {\n await rm(temporary, { force: true }).catch(() => undefined);\n }\n }\n\n async get(hash: string): Promise<Uint8Array | undefined> {\n if (!HASH.test(hash)) return undefined;\n const target = blobPath(this.dir, hash);\n let bytes: Buffer;\n try {\n bytes = await readFile(target);\n } catch {\n return undefined;\n }\n if (hashOf(bytes) !== hash) {\n // a torn or damaged file is never the body: it moves away, and the next put writes it again\n await rename(target, `${target}.${randomUUID()}.damaged`).catch(() => undefined);\n return undefined;\n }\n return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n}\n","import { createReadStream, existsSync } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { mkdir, open, readdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { CaptureRecord } from \"./record.ts\";\n\n/** A scan filter selects the records of one source, one kind, or the records after one time. */\nexport interface CaptureFilter {\n readonly source?: string | undefined;\n readonly kind?: string | undefined;\n /** This value is an ISO 8601 time. The scan gives the records received at this time or later. */\n readonly since?: string | undefined;\n}\n\n/** A damaged line is a line of the log that is not a record: a torn append, or bytes that a crash left. */\nexport interface DamagedLine {\n /** This value is the path of the file. */\n readonly path: string;\n /** This value is the number of the line in the file, from 1. */\n readonly line: number;\n}\n\n/** These options change a scan. */\nexport interface ScanOptions {\n /** The scan skips a damaged line, and it gives the line to this function. */\n readonly onDamaged?: ((damaged: DamagedLine) => void) | undefined;\n}\n\n/** The read side of the capture log is what `reindex` replays. */\nexport interface CaptureReader {\n scan(filter?: CaptureFilter, options?: ScanOptions): AsyncIterable<CaptureRecord>;\n}\n\n/**\n * These options change a capture log.\n *\n * @beta\n */\nexport interface CaptureLogOptions {\n /**\n * When this value is true (the default), the log writes each batch of appends to the disk\n * (`fdatasync`) before the appends finish. Thus a power cut does not lose a record that the\n * crawler reported.\n */\n readonly sync?: boolean | undefined;\n}\n\ninterface Pending {\n readonly path: string;\n readonly line: string;\n readonly resolve: () => void;\n readonly reject: (error: unknown) => void;\n}\n\nconst MONTH_FILE = /^(\\d{2})(?:\\.[^.]+)?\\.ndjson$/;\nconst YEAR_DIR = /^\\d{4}$/;\nconst NEWLINE = 0x0a;\n\n/** This function writes the whole buffer. A write to a file can write less than the buffer, and the loop writes the rest. */\nconst writeAll = async (handle: FileHandle, bytes: Buffer): Promise<void> => {\n let at = 0;\n while (at < bytes.length) {\n const { bytesWritten } = await handle.write(bytes, at, bytes.length - at);\n at += bytesWritten;\n }\n};\n\n/**\n * This function reads a file line by line, as bytes, so a long file does not become one string. It\n * gives each line and tells if a line break ends it.\n */\nasync function* linesOf(\n path: string,\n): AsyncGenerator<{ readonly text: string; readonly complete: boolean }> {\n const decoder = new TextDecoder(\"utf-8\");\n let rest: Buffer | undefined;\n for await (const chunk of createReadStream(path) as AsyncIterable<Buffer>) {\n const data = rest === undefined ? chunk : Buffer.concat([rest, chunk]);\n rest = undefined;\n let start = 0;\n for (;;) {\n const end = data.indexOf(NEWLINE, start);\n if (end === -1) break;\n yield { text: decoder.decode(data.subarray(start, end)), complete: true };\n start = end + 1;\n }\n if (start < data.length) rest = Buffer.from(data.subarray(start));\n }\n if (rest !== undefined && rest.length > 0) yield { text: decoder.decode(rest), complete: false };\n}\n\nconst monthKey = (year: string, file: string): string =>\n `${year}-${MONTH_FILE.exec(file)?.[1] ?? \"00\"}`;\n\n/**\n * The capture log keeps each fetch decision as one line of JSON in\n * `<dir>/<source>/<yyyy>/<mm>.ndjson`. It is the record of each access that the crawler makes.\n *\n * These are the rules of the log:\n *\n * - The log appends a batch of records with one write, and it writes the batch to the disk before\n * the appends finish.\n * - An append always starts on a new line. After a crash leaves a partial line, the next append\n * starts after a line break. The partial line stays as a damaged line, and the record is good.\n * - A scan reads each file as a stream. It skips a damaged line, counts it, and continues.\n * - The log does not remove or change a line.\n *\n * Two processes can append to one log, because each batch is one write to a file in append mode.\n *\n * @beta\n */\nexport class CaptureLog implements CaptureReader {\n private readonly handles = new Map<string, FileHandle>();\n private readonly pending: Pending[] = [];\n private draining: Promise<void> | undefined;\n private readonly sync: boolean;\n\n constructor(\n readonly dir: string,\n options: CaptureLogOptions = {},\n ) {\n this.sync = options.sync ?? true;\n }\n\n private pathOf(record: CaptureRecord): string {\n return join(\n this.dir,\n record.source,\n record.received_at.slice(0, 4),\n `${record.received_at.slice(5, 7)}.ndjson`,\n );\n }\n\n private async handleFor(path: string): Promise<FileHandle> {\n const known = this.handles.get(path);\n if (known !== undefined) return known;\n // the folders and the files are for the owner only, where the system has modes\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const handle = await open(path, \"a+\", 0o600);\n this.handles.set(path, handle);\n return handle;\n }\n\n /** This method tells if the last byte of a file is not a line break: a partial line that a crash left. */\n private static async needsBreak(handle: FileHandle): Promise<boolean> {\n const { size } = await handle.stat();\n if (size === 0) return false;\n const last = Buffer.alloc(1);\n await handle.read(last, 0, 1, size - 1);\n return last[0] !== NEWLINE;\n }\n\n append(record: CaptureRecord): Promise<void> {\n let line: string;\n try {\n line = `${JSON.stringify(record)}\\n`;\n } catch (error) {\n return Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n return new Promise<void>((resolve, reject) => {\n this.pending.push({ path: this.pathOf(record), line, resolve, reject });\n this.kick();\n });\n }\n\n /** This method starts the writer when it is not in progress. A record that comes as the writer stops starts it again. */\n private kick(): void {\n if (this.draining !== undefined) return;\n this.draining = this.drain().finally(() => {\n this.draining = undefined;\n if (this.pending.length > 0) this.kick();\n });\n }\n\n /** This method writes the waiting records in batches: one write and one sync for each file. */\n private async drain(): Promise<void> {\n while (this.pending.length > 0) {\n const batch = this.pending.splice(0);\n const byPath = new Map<string, Pending[]>();\n for (const item of batch) {\n const list = byPath.get(item.path);\n if (list === undefined) byPath.set(item.path, [item]);\n else list.push(item);\n }\n for (const [path, items] of byPath) {\n try {\n const handle = await this.handleFor(path);\n const lead = (await CaptureLog.needsBreak(handle)) ? \"\\n\" : \"\";\n await writeAll(\n handle,\n Buffer.from(`${lead}${items.map((item) => item.line).join(\"\")}`, \"utf8\"),\n );\n if (this.sync) await handle.datasync();\n for (const item of items) item.resolve();\n } catch (error) {\n // a handle that failed is opened again for the next append\n const handle = this.handles.get(path);\n this.handles.delete(path);\n await handle?.close().catch(() => undefined);\n for (const item of items) item.reject(error);\n }\n }\n }\n }\n\n /** This method waits until each append in progress is on the disk. */\n async flush(): Promise<void> {\n while (this.draining !== undefined) await this.draining;\n }\n\n /** This method gives the record files of one source, in the sequence of time. It skips the months before `since`. */\n private async filesOf(source: string, since: string | undefined): Promise<string[]> {\n const sourceDir = join(this.dir, source);\n if (!existsSync(sourceDir)) return [];\n const from = since?.slice(0, 7);\n const years = (await readdir(sourceDir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory() && YEAR_DIR.test(entry.name))\n .map((entry) => entry.name)\n .sort();\n const files: string[] = [];\n for (const year of years) {\n if (from !== undefined && year < from.slice(0, 4)) continue;\n const months = (await readdir(join(sourceDir, year)))\n .filter((name) => MONTH_FILE.test(name))\n .sort();\n for (const month of months) {\n if (from !== undefined && monthKey(year, month) < from) continue;\n files.push(join(sourceDir, year, month));\n }\n }\n return files;\n }\n\n /** This method reads the records of one source in the sequence of the files. */\n private async *readSource(\n source: string,\n filter: CaptureFilter | undefined,\n options: ScanOptions | undefined,\n ): AsyncGenerator<CaptureRecord> {\n for (const path of await this.filesOf(source, filter?.since)) {\n let number = 0;\n for await (const { text, complete } of linesOf(path)) {\n number += 1;\n const trimmed = text.trim();\n if (trimmed.length === 0) continue;\n let row: CaptureRecord;\n try {\n row = JSON.parse(trimmed) as CaptureRecord;\n if (typeof row !== \"object\" || row === null || typeof row.received_at !== \"string\") {\n throw new Error(\"not a record\");\n }\n } catch {\n // the append of a different process can be in progress at the end of the file\n if (complete) options?.onDamaged?.({ path, line: number });\n continue;\n }\n if (filter?.kind !== undefined && row.kind !== filter.kind) continue;\n if (filter?.since !== undefined && row.received_at < filter.since) continue;\n yield row;\n }\n }\n }\n\n /**\n * This method reads the records that agree with the filter. It first waits for the appends that\n * are in progress. It reads each file as a stream, so its memory does not grow with the log.\n *\n * The records of one source come in the sequence of the files. The records of two or more sources\n * merge in the sequence of `received_at`.\n */\n async *scan(filter?: CaptureFilter, options?: ScanOptions): AsyncIterable<CaptureRecord> {\n await this.flush();\n const sources =\n filter?.source !== undefined\n ? [filter.source]\n : existsSync(this.dir)\n ? (await readdir(this.dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort()\n : [];\n if (sources.length === 1) {\n yield* this.readSource(sources[0]!, filter, options);\n return;\n }\n // a merge of the sources: the next record is the earliest head\n const streams = sources.map((source) =>\n this.readSource(source, filter, options)[Symbol.asyncIterator](),\n );\n const heads: Array<CaptureRecord | undefined> = [];\n for (const stream of streams)\n heads.push((await stream.next()).value as CaptureRecord | undefined);\n for (;;) {\n let pick = -1;\n for (const [index, head] of heads.entries()) {\n if (head !== undefined && (pick === -1 || head.received_at < heads[pick]!.received_at)) {\n pick = index;\n }\n }\n if (pick === -1) return;\n yield heads[pick]!;\n heads[pick] = (await streams[pick]!.next()).value as CaptureRecord | undefined;\n }\n }\n\n /** This method writes the appends in progress, then closes the files. A later append opens them again. */\n async close(): Promise<void> {\n await this.flush();\n const handles = [...this.handles.values()];\n this.handles.clear();\n for (const handle of handles) await handle.close();\n }\n}\n"],"mappings":";;;;;AAwBA,MAAM,OAAO;;AAGb,MAAM,6BAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,YAAY,MAAc,SAC9B,KAAK,MAAM,KAAK,MAAM,GAAG,CAAC,GAAG,KAAK,MAAM,GAAG,CAAC,GAAG,IAAI;AAErD,MAAM,UAAU,UAA8B,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAE7F,MAAM,UAAU,UACd,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,OAAO,MAAM,IAAI,IAAI;AAExF,MAAM,UAAU,SAA6C,KAAK,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;;AAG7F,MAAM,aAAa,OAAO,SAAgC;CACxD,IAAI,QAAQ,aAAa,SAAS;CAClC,IAAI;EACF,MAAM,SAAS,MAAM,KAAK,MAAM,GAAG;EACnC,IAAI;GACF,MAAM,OAAO,KAAK;EACpB,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF,QAAQ,CAER;AACF;;;;;;;;;;;;;;;;AAiBA,IAAa,gBAAb,MAAa,cAAmC;CAQnC;CAPX,0BAA2B,IAAI,IAG7B;CACF;CAEA,YACE,KACA,UAAgC,CAAC,GACjC;EAFS,KAAA,MAAA;EAGT,KAAK,OAAO,QAAQ,QAAQ;CAC9B;CAEA,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AU,CAAC,GAAG,KAAK,QAAQ,OAAO,CAAC;EACzC,KAAK,QAAQ,MAAM;EACnB,KAAK,MAAM,UAAU,SAAS,MAAM,OAAO,MAAM;CACnD;AACF"}
|
|
1
|
+
{"version":3,"file":"log-CB5bADmd.mjs","names":[],"sources":["../src/blobs.ts","../src/log.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport { mkdir, open, readFile, rename, rm, stat } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * A blob store keeps the bytes of each response, and the hash of the bytes is the key. The crawler\n * needs only these two operations, so an application can give its own store.\n */\nexport interface BlobStore {\n put(bytes: Uint8Array): Promise<{ readonly hash: string }>;\n get(hash: string): Promise<Uint8Array | undefined>;\n}\n\n/**\n * These options change a file blob store.\n *\n * @beta\n */\nexport interface FileBlobStoreOptions {\n /** When this value is true (the default), a blob is on the disk (`fsync`) before `put` finishes. */\n readonly sync?: boolean | undefined;\n}\n\nconst HASH = /^[0-9a-f]{64}$/;\n\n/** A rename can fail with these codes when a different writer puts the same blob at the same time. */\nconst RACE_CODES: ReadonlySet<string> = new Set([\n \"EPERM\",\n \"EEXIST\",\n \"EBUSY\",\n \"EACCES\",\n \"ENOTEMPTY\",\n]);\n\nconst blobPath = (root: string, hash: string): string =>\n join(root, hash.slice(0, 2), hash.slice(2, 4), hash);\n\nconst hashOf = (bytes: Uint8Array): string => createHash(\"sha256\").update(bytes).digest(\"hex\");\n\nconst codeOf = (error: unknown): string =>\n typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n\nconst statOf = (path: string): Promise<Stats | undefined> => stat(path).catch(() => undefined);\n\n/** This function writes a folder to the disk, so a rename in it stays after a power cut. Windows cannot open a folder, so it skips this step. */\nconst syncFolder = async (path: string): Promise<void> => {\n if (process.platform === \"win32\") return;\n try {\n const handle = await open(path, \"r\");\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n } catch {\n // a file system that cannot sync a folder keeps the blob in any case\n }\n};\n\n/**\n * This store keeps each blob in a file: `<dir>/ab/cd/abcd…`, where the name is the SHA-256 hash\n * of the bytes. These are its rules:\n *\n * - Equal bytes are written one time only. A file of the wrong size (a write that a crash cut) is\n * written again.\n * - A write goes to a temporary file with a random name, goes to the disk, and then gets its name.\n * A crash thus cannot leave half a blob under its name.\n * - Two writers can put the same bytes at the same time. When the rename of one fails because the\n * other was first, the put succeeds if the stored file has the same hash.\n * - The method `get` examines the hash of the bytes. A damaged file gets a new name\n * (`.damaged`), and `get` gives no bytes, so the crawler fetches the body again.\n *\n * @beta\n */\nexport class FileBlobStore implements BlobStore {\n private readonly writing = new Map<\n string,\n Promise<{ readonly hash: string; readonly existed: boolean }>\n >();\n private readonly sync: boolean;\n\n constructor(\n readonly dir: string,\n options: FileBlobStoreOptions = {},\n ) {\n this.sync = options.sync ?? true;\n }\n\n put(bytes: Uint8Array): Promise<{ readonly hash: string; readonly existed: boolean }> {\n const hash = hashOf(bytes);\n const running = this.writing.get(hash);\n if (running !== undefined) return running;\n const work = this.write(hash, bytes).finally(() => this.writing.delete(hash));\n this.writing.set(hash, work);\n return work;\n }\n\n /** This method tells if a file holds exactly the bytes of a hash. */\n private static async holds(path: string, hash: string): Promise<boolean> {\n try {\n return hashOf(await readFile(path)) === hash;\n } catch {\n return false;\n }\n }\n\n private async write(\n hash: string,\n bytes: Uint8Array,\n ): Promise<{ readonly hash: string; readonly existed: boolean }> {\n const target = blobPath(this.dir, hash);\n const existing = await statOf(target);\n if (existing?.isFile() === true && existing.size === bytes.length)\n return { hash, existed: true };\n const folder = dirname(target);\n await mkdir(folder, { recursive: true, mode: 0o700 });\n const temporary = `${target}.${randomUUID()}.tmp`;\n try {\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n await handle.writeFile(bytes);\n if (this.sync) await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await rename(temporary, target);\n } catch (error) {\n // a different writer put the same bytes first, and Windows does not replace a file in use\n if (!RACE_CODES.has(codeOf(error)) || !(await FileBlobStore.holds(target, hash)))\n throw error;\n return { hash, existed: true };\n }\n if (this.sync) await syncFolder(folder);\n return { hash, existed: false };\n } finally {\n await rm(temporary, { force: true }).catch(() => undefined);\n }\n }\n\n async get(hash: string): Promise<Uint8Array | undefined> {\n if (!HASH.test(hash)) return undefined;\n const target = blobPath(this.dir, hash);\n let bytes: Buffer;\n try {\n bytes = await readFile(target);\n } catch {\n return undefined;\n }\n if (hashOf(bytes) !== hash) {\n // a torn or damaged file is never the body: it moves away, and the next put writes it again\n await rename(target, `${target}.${randomUUID()}.damaged`).catch(() => undefined);\n return undefined;\n }\n return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n}\n","import { createReadStream, existsSync } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport { mkdir, open, readdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { CaptureRecord } from \"./record.ts\";\n\n/** A scan filter selects the records of one source, one kind, or the records after one time. */\nexport interface CaptureFilter {\n readonly source?: string | undefined;\n readonly kind?: string | undefined;\n /** This value is an ISO 8601 time. The scan gives the records received at this time or later. */\n readonly since?: string | undefined;\n}\n\n/** A damaged line is a line of the log that is not a record: a torn append, or bytes that a crash left. */\nexport interface DamagedLine {\n /** This value is the path of the file. */\n readonly path: string;\n /** This value is the number of the line in the file, from 1. */\n readonly line: number;\n}\n\n/** These options change a scan. */\nexport interface ScanOptions {\n /** The scan skips a damaged line, and it gives the line to this function. */\n readonly onDamaged?: ((damaged: DamagedLine) => void) | undefined;\n}\n\n/** The read side of the capture log is what `reindex` replays. */\nexport interface CaptureReader {\n scan(filter?: CaptureFilter, options?: ScanOptions): AsyncIterable<CaptureRecord>;\n}\n\n/**\n * These options change a capture log.\n *\n * @beta\n */\nexport interface CaptureLogOptions {\n /**\n * When this value is true (the default), the log writes each batch of appends to the disk\n * (`fdatasync`) before the appends finish. Thus a power cut does not lose a record that the\n * crawler reported.\n */\n readonly sync?: boolean | undefined;\n}\n\ninterface Pending {\n readonly path: string;\n readonly line: string;\n readonly resolve: () => void;\n readonly reject: (error: unknown) => void;\n}\n\nconst MONTH_FILE = /^(\\d{2})(?:\\.[^.]+)?\\.ndjson$/;\nconst YEAR_DIR = /^\\d{4}$/;\nconst NEWLINE = 0x0a;\n\n/** This function writes the whole buffer. A write to a file can write less than the buffer, and the loop writes the rest. */\nconst writeAll = async (handle: FileHandle, bytes: Buffer): Promise<void> => {\n let at = 0;\n while (at < bytes.length) {\n const { bytesWritten } = await handle.write(bytes, at, bytes.length - at);\n at += bytesWritten;\n }\n};\n\n/**\n * This function reads a file line by line, as bytes, so a long file does not become one string. It\n * gives each line and tells if a line break ends it.\n */\nasync function* linesOf(\n path: string,\n): AsyncGenerator<{ readonly text: string; readonly complete: boolean }> {\n const decoder = new TextDecoder(\"utf-8\");\n let rest: Buffer | undefined;\n for await (const chunk of createReadStream(path) as AsyncIterable<Buffer>) {\n const data = rest === undefined ? chunk : Buffer.concat([rest, chunk]);\n rest = undefined;\n let start = 0;\n for (;;) {\n const end = data.indexOf(NEWLINE, start);\n if (end === -1) break;\n yield { text: decoder.decode(data.subarray(start, end)), complete: true };\n start = end + 1;\n }\n if (start < data.length) rest = Buffer.from(data.subarray(start));\n }\n if (rest !== undefined && rest.length > 0) yield { text: decoder.decode(rest), complete: false };\n}\n\nconst monthKey = (year: string, file: string): string =>\n `${year}-${MONTH_FILE.exec(file)?.[1] ?? \"00\"}`;\n\n/**\n * The capture log keeps each fetch decision as one line of JSON in\n * `<dir>/<source>/<yyyy>/<mm>.ndjson`. It is the record of each access that the crawler makes.\n *\n * These are the rules of the log:\n *\n * - The log appends a batch of records with one write, and it writes the batch to the disk before\n * the appends finish.\n * - An append always starts on a new line. After a crash leaves a partial line, the next append\n * starts after a line break. The partial line stays as a damaged line, and the record is good.\n * - A scan reads each file as a stream. It skips a damaged line, counts it, and continues.\n * - The log does not remove or change a line.\n *\n * Two processes can append to one log, because each batch is one write to a file in append mode.\n *\n * @beta\n */\nexport class CaptureLog implements CaptureReader {\n private readonly handles = new Map<string, FileHandle>();\n private readonly pending: Pending[] = [];\n private draining: Promise<void> | undefined;\n private readonly sync: boolean;\n\n constructor(\n readonly dir: string,\n options: CaptureLogOptions = {},\n ) {\n this.sync = options.sync ?? true;\n }\n\n private pathOf(record: CaptureRecord): string {\n return join(\n this.dir,\n record.source,\n record.received_at.slice(0, 4),\n `${record.received_at.slice(5, 7)}.ndjson`,\n );\n }\n\n private async handleFor(path: string): Promise<FileHandle> {\n const known = this.handles.get(path);\n if (known !== undefined) return known;\n // the folders and the files are for the owner only, where the system has modes\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const handle = await open(path, \"a+\", 0o600);\n this.handles.set(path, handle);\n return handle;\n }\n\n /** This method tells if the last byte of a file is not a line break: a partial line that a crash left. */\n private static async needsBreak(handle: FileHandle): Promise<boolean> {\n const { size } = await handle.stat();\n if (size === 0) return false;\n const last = Buffer.alloc(1);\n await handle.read(last, 0, 1, size - 1);\n return last[0] !== NEWLINE;\n }\n\n append(record: CaptureRecord): Promise<void> {\n let line: string;\n try {\n line = `${JSON.stringify(record)}\\n`;\n } catch (error) {\n return Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n return new Promise<void>((resolve, reject) => {\n this.pending.push({ path: this.pathOf(record), line, resolve, reject });\n this.kick();\n });\n }\n\n /** This method starts the writer when it is not in progress. A record that comes as the writer stops starts it again. */\n private kick(): void {\n if (this.draining !== undefined) return;\n this.draining = this.drain().finally(() => {\n this.draining = undefined;\n if (this.pending.length > 0) this.kick();\n });\n }\n\n /** This method writes the waiting records in batches: one write and one sync for each file. */\n private async drain(): Promise<void> {\n while (this.pending.length > 0) {\n const batch = this.pending.splice(0);\n const byPath = new Map<string, Pending[]>();\n for (const item of batch) {\n const list = byPath.get(item.path);\n if (list === undefined) byPath.set(item.path, [item]);\n else list.push(item);\n }\n for (const [path, items] of byPath) {\n try {\n const handle = await this.handleFor(path);\n const lead = (await CaptureLog.needsBreak(handle)) ? \"\\n\" : \"\";\n await writeAll(\n handle,\n Buffer.from(`${lead}${items.map((item) => item.line).join(\"\")}`, \"utf8\"),\n );\n if (this.sync) await handle.datasync();\n for (const item of items) item.resolve();\n } catch (error) {\n // a handle that failed is opened again for the next append\n const handle = this.handles.get(path);\n this.handles.delete(path);\n await handle?.close().catch(() => undefined);\n for (const item of items) item.reject(error);\n }\n }\n }\n }\n\n /** This method waits until each append in progress is on the disk. */\n async flush(): Promise<void> {\n while (this.draining !== undefined) await this.draining;\n }\n\n /** This method gives the record files of one source, in the sequence of time. It skips the months before `since`. */\n private async filesOf(source: string, since: string | undefined): Promise<string[]> {\n const sourceDir = join(this.dir, source);\n if (!existsSync(sourceDir)) return [];\n const from = since?.slice(0, 7);\n const years = (await readdir(sourceDir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory() && YEAR_DIR.test(entry.name))\n .map((entry) => entry.name)\n .sort();\n const files: string[] = [];\n for (const year of years) {\n if (from !== undefined && year < from.slice(0, 4)) continue;\n const months = (await readdir(join(sourceDir, year)))\n .filter((name) => MONTH_FILE.test(name))\n .sort();\n for (const month of months) {\n if (from !== undefined && monthKey(year, month) < from) continue;\n files.push(join(sourceDir, year, month));\n }\n }\n return files;\n }\n\n /** This method reads the records of one source in the sequence of the files. */\n private async *readSource(\n source: string,\n filter: CaptureFilter | undefined,\n options: ScanOptions | undefined,\n ): AsyncGenerator<CaptureRecord> {\n for (const path of await this.filesOf(source, filter?.since)) {\n let number = 0;\n for await (const { text, complete } of linesOf(path)) {\n number += 1;\n const trimmed = text.trim();\n if (trimmed.length === 0) continue;\n let row: CaptureRecord;\n try {\n row = JSON.parse(trimmed) as CaptureRecord;\n if (typeof row !== \"object\" || row === null || typeof row.received_at !== \"string\") {\n throw new Error(\"not a record\");\n }\n } catch {\n // the append of a different process can be in progress at the end of the file\n if (complete) options?.onDamaged?.({ path, line: number });\n continue;\n }\n if (filter?.kind !== undefined && row.kind !== filter.kind) continue;\n if (filter?.since !== undefined && row.received_at < filter.since) continue;\n yield row;\n }\n }\n }\n\n /**\n * This method reads the records that agree with the filter. It first waits for the appends that\n * are in progress. It reads each file as a stream, so its memory does not grow with the log.\n *\n * The records of one source come in the sequence of the files. The records of two or more sources\n * merge in the sequence of `received_at`.\n */\n async *scan(filter?: CaptureFilter, options?: ScanOptions): AsyncIterable<CaptureRecord> {\n await this.flush();\n const sources =\n filter?.source !== undefined\n ? [filter.source]\n : existsSync(this.dir)\n ? (await readdir(this.dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort()\n : [];\n if (sources.length === 1) {\n yield* this.readSource(sources[0]!, filter, options);\n return;\n }\n // a merge of the sources: the next record is the earliest head\n const streams = sources.map((source) =>\n this.readSource(source, filter, options)[Symbol.asyncIterator](),\n );\n const heads: Array<CaptureRecord | undefined> = [];\n for (const stream of streams)\n heads.push((await stream.next()).value as CaptureRecord | undefined);\n for (;;) {\n let pick = -1;\n for (const [index, head] of heads.entries()) {\n if (head !== undefined && (pick === -1 || head.received_at < heads[pick]!.received_at)) {\n pick = index;\n }\n }\n if (pick === -1) return;\n yield heads[pick]!;\n heads[pick] = (await streams[pick]!.next()).value as CaptureRecord | undefined;\n }\n }\n\n /** This method writes the appends in progress, then closes the files. A later append opens them again. */\n async close(): Promise<void> {\n await this.flush();\n const handles = [...this.handles.values()];\n this.handles.clear();\n for (const handle of handles) await handle.close();\n }\n}\n"],"mappings":";;;;;AAwBA,MAAM,OAAO;;AAGb,MAAM,6BAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,YAAY,MAAc,SAC9B,KAAK,MAAM,KAAK,MAAM,GAAG,CAAC,GAAG,KAAK,MAAM,GAAG,CAAC,GAAG,IAAI;AAErD,MAAM,UAAU,UAA8B,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAE7F,MAAM,UAAU,U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A,MAAM,UAAU,QAAQ,KAAK,WAC3B,KAAK,WAAW,QAAQ,QAAQ,OAAO,CAAC,CAAC,OAAO,cAAc,CAAC,CACjE;EACA,MAAM,QAA0C,CAAC;EACjD,KAAK,MAAM,UAAU,SACnB,MAAM,MAAM,MAAM,OAAO,KAAK,EAAA,CAAG,KAAkC;EACrE,SAAS;GACP,IAAI,OAAO;GACX,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GACxC,IAAI,SAAS,KAAA,MAAc,SAAS,MAAM,KAAK,cAAc,MAAM,KAAK,CAAE,cACxE,OAAO;GAGX,IAAI,SAAS,IAAI;GACjB,MAAM,MAAM;GACZ,MAAM,SAAS,MAAM,QAAQ,KAAK,CAAE,KAAK,EAAA,CAAG;EAC9C;CACF;;CAGA,MAAM,QAAuB;EAC3B,MAAM,KAAK,MAAM;EACjB,MAAM,UAAU,CAAC,GAAG,KAAK,QAAQ,OAAO,CAAC;EACzC,KAAK,QAAQ,MAAM;EACnB,KAAK,MAAM,UAAU,SAAS,MAAM,OAAO,MAAM;CACnD;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import { pathToFileURL } from "node:url";
|
|
3
|
-
|
|
3
|
+
// src/mcp-package.ts
|
|
4
4
|
/** The name of the package of the MCP server. */
|
|
5
5
|
const MCP_PACKAGE = "polite-crawler-mcp";
|
|
6
6
|
/** This text tells where the MCP server is. */
|
|
@@ -34,7 +34,6 @@ const loadMcpPackage = async (places = mcpPackagePlaces(), name = MCP_PACKAGE) =
|
|
|
34
34
|
}
|
|
35
35
|
throw new McpPackageMissing();
|
|
36
36
|
};
|
|
37
|
-
//#endregion
|
|
38
37
|
export { McpPackageMissing, loadMcpPackage };
|
|
39
38
|
|
|
40
|
-
//# sourceMappingURL=mcp-package-
|
|
39
|
+
//# sourceMappingURL=mcp-package-D9ACY0Ux.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-package-
|
|
1
|
+
{"version":3,"file":"mcp-package-D9ACY0Ux.mjs","names":[],"sources":["../src/mcp-package.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport type { DaemonMcpHost } from \"./daemon.ts\";\nimport type { OpenOptions } from \"./open.ts\";\n\n/*\n * The MCP server of polite-crawler is the package polite-crawler-mcp since polite-crawler 0.2.0.\n * polite-crawler does not depend on it, so the library loads no MCP SDK and no zod. The command\n * `polite-crawler mcp` and the MCP server of the daemon load the package when it is there: next to\n * polite-crawler. They do not look in the working folder: an MCP client can start the command in any\n * project, and the code of that project must not start.\n */\n\n/** The name of the package of the MCP server. */\nexport const MCP_PACKAGE = \"polite-crawler-mcp\";\n\n/** This text tells where the MCP server is. */\nexport const MCP_POINTER =\n \"The MCP server of polite-crawler is the package polite-crawler-mcp since 0.2.0. Start it with npx polite-crawler-mcp, or install polite-crawler-mcp next to polite-crawler.\";\n\n/** The parts of polite-crawler-mcp that polite-crawler uses. */\nexport interface McpPackage {\n startMcpServer(\n options: OpenOptions & {\n readonly allowUserProvided?: boolean | undefined;\n readonly log?: ((line: string) => void) | undefined;\n },\n ): Promise<void>;\n readonly mcpHttpHost: DaemonMcpHost;\n}\n\n/** This error tells that polite-crawler-mcp is not there. Its message is the pointer. */\nexport class McpPackageMissing extends Error {\n constructor() {\n super(MCP_POINTER);\n this.name = \"McpPackageMissing\";\n }\n}\n\n/**\n * This function gives the places where polite-crawler looks for polite-crawler-mcp, as file URLs:\n * only next to polite-crawler.\n */\nexport const mcpPackagePlaces = (): string[] => [import.meta.url];\n\n/**\n * This function loads polite-crawler-mcp from the first place that has it. It throws\n * `McpPackageMissing` when no place has it. A test gives another `name`: Node.js also looks in the\n * folders of `NODE_PATH`, and pnpm sets it to the packages of the workspace.\n */\nexport const loadMcpPackage = async (\n places: readonly string[] = mcpPackagePlaces(),\n name: string = MCP_PACKAGE,\n): Promise<McpPackage> => {\n for (const from of places) {\n let path: string;\n try {\n path = createRequire(from).resolve(name);\n } catch {\n continue;\n }\n return (await import(pathToFileURL(path).href)) as McpPackage;\n }\n throw new McpPackageMissing();\n};\n"],"mappings":";;;;AAcA,MAAa,cAAc;;AAG3B,MAAa,cACX;;AAcF,IAAa,oBAAb,cAAuC,MAAM;CAC3C,cAAc;EACZ,MAAM,WAAW;EACjB,KAAK,OAAO;CACd;AACF;;;;;AAMA,MAAa,yBAAmC,CAAC,YAAY,GAAG;;;;;;AAOhE,MAAa,iBAAiB,OAC5B,SAA4B,iBAAiB,GAC7C,OAAe,gBACS;CACxB,KAAK,MAAM,QAAQ,QAAQ;EACzB,IAAI;EACJ,IAAI;GACF,OAAO,cAAc,IAAI,CAAC,CAAC,QAAQ,IAAI;EACzC,QAAQ;GACN;EACF;EACA,OAAQ,MAAM,OAAO,cAAc,IAAI,CAAC,CAAC;CAC3C;CACA,MAAM,IAAI,kBAAkB;AAC9B"}
|
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
-
|
|
4
|
-
var ollama_exports = /* @__PURE__ */ __exportAll({
|
|
5
|
-
NO_OLLAMA: () => NO_OLLAMA,
|
|
6
|
-
OLLAMA_MODELS: () => OLLAMA_MODELS,
|
|
7
|
-
isLoopback: () => isLoopback,
|
|
8
|
-
ollamaEmbedder: () => ollamaEmbedder
|
|
9
|
-
});
|
|
3
|
+
// src/ollama.ts
|
|
4
|
+
var ollama_exports = /* @__PURE__ */ __exportAll({ ollamaEmbedder: () => ollamaEmbedder });
|
|
10
5
|
/** These are the facts of three embedding models of Ollama. The name has no tag (`nomic-embed-text`, not `nomic-embed-text:latest`). */
|
|
11
6
|
const OLLAMA_MODELS = {
|
|
12
7
|
"nomic-embed-text": {
|
|
@@ -158,7 +153,6 @@ const ollamaEmbedder = (options = {}) => {
|
|
|
158
153
|
}
|
|
159
154
|
};
|
|
160
155
|
};
|
|
161
|
-
//#endregion
|
|
162
156
|
export { ollama_exports as a, ollamaEmbedder as i, OLLAMA_MODELS as n, isLoopback as r, NO_OLLAMA as t };
|
|
163
157
|
|
|
164
|
-
//# sourceMappingURL=ollama-
|
|
158
|
+
//# sourceMappingURL=ollama-BDZjLDOK.mjs.map
|