searchfetch 3.3.3 → 4.0.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.
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Template loading, validation, lookup and URL resolution.
3
+ *
4
+ * Templates are shared JSON documents in `templates/`; the Python runtime implements the same
5
+ * rules in `searchfetch/templates.py`.
6
+ */
7
+ import { readdirSync, readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ export const TEMPLATES_DIR = fileURLToPath(new URL("../templates/", import.meta.url));
12
+
13
+ export const FORMATS = new Set(["text", "markdown", "attribute", "html"]);
14
+ export const TRANSFORMS = new Set([
15
+ "strip",
16
+ "decode_google_url",
17
+ "decode_ddg_url",
18
+ "json_parse",
19
+ "resolve_href",
20
+ ]);
21
+
22
+ /** Short engine names accepted by `websearch` in addition to template names. */
23
+ export const ENGINE_ALIASES = { duckduckgo: "duckduckgo-search", google: "google-search" };
24
+
25
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
26
+
27
+ function validateSection(section, where) {
28
+ if (!isObject(section) || typeof section.name !== "string" || !section.name) {
29
+ throw new Error(`${where}: every section needs a non-empty "name".`);
30
+ }
31
+ const label = `${where} section '${section.name}'`;
32
+ if (section.selector != null && typeof section.selector !== "string") {
33
+ throw new Error(`${label}: "selector" must be a string.`);
34
+ }
35
+ const format = section.format ?? "text";
36
+ if (!FORMATS.has(format)) {
37
+ throw new Error(`${label}: unknown format '${format}'.`);
38
+ }
39
+ if (format === "attribute" && (typeof section.attribute !== "string" || !section.attribute)) {
40
+ throw new Error(`${label}: format "attribute" requires an "attribute" name.`);
41
+ }
42
+ if (
43
+ section.max_items != null &&
44
+ !(Number.isInteger(section.max_items) && section.max_items > 0)
45
+ ) {
46
+ throw new Error(`${label}: "max_items" must be a positive integer.`);
47
+ }
48
+ const transforms = section.transform == null ? [] : [section.transform].flat();
49
+ for (const transform of transforms) {
50
+ if (!TRANSFORMS.has(transform)) throw new Error(`${label}: unknown transform '${transform}'.`);
51
+ }
52
+ if (section.children != null) {
53
+ if (!Array.isArray(section.children)) throw new Error(`${label}: "children" must be a list.`);
54
+ for (const child of section.children) {
55
+ validateSection(child, label);
56
+ if (child.children) throw new Error(`${label}: children cannot be nested.`);
57
+ }
58
+ }
59
+ }
60
+
61
+ /** Validate a template object, compile its URL patterns, and return it. Throws on errors. */
62
+ export function validateTemplate(template, where = "template") {
63
+ if (!isObject(template)) throw new Error(`${where}: template must be a JSON object.`);
64
+ if (typeof template.name !== "string" || !template.name) {
65
+ throw new Error(`${where}: template needs a non-empty "name".`);
66
+ }
67
+ if (!Array.isArray(template.sections)) {
68
+ throw new Error(`${where}: template needs a "sections" list.`);
69
+ }
70
+ for (const section of template.sections) validateSection(section, where);
71
+ const patterns = template.url_patterns ?? [];
72
+ if (!Array.isArray(patterns) || patterns.some((pattern) => typeof pattern !== "string")) {
73
+ throw new Error(`${where}: "url_patterns" must be a list of strings.`);
74
+ }
75
+ for (const pattern of patterns) {
76
+ try {
77
+ new RegExp(pattern);
78
+ } catch (err) {
79
+ throw new Error(`${where}: invalid URL pattern ${JSON.stringify(pattern)}: ${err.message}`, {
80
+ cause: err,
81
+ });
82
+ }
83
+ }
84
+ return template;
85
+ }
86
+
87
+ /** Parse and validate a template passed inline as JSON text. */
88
+ export function parseInlineTemplate(text) {
89
+ let template;
90
+ try {
91
+ template = JSON.parse(text);
92
+ } catch (err) {
93
+ throw new Error(`Invalid inline JSON template: ${err.message}`, { cause: err });
94
+ }
95
+ if (isObject(template)) template.name ??= "custom";
96
+ return validateTemplate(template, "Inline template");
97
+ }
98
+
99
+ /** Load every `*.json` template from `directory`, sorted by `order` for URL matching. */
100
+ export function loadTemplates(directory = TEMPLATES_DIR) {
101
+ const files = readdirSync(directory)
102
+ .filter((file) => file.endsWith(".json"))
103
+ .sort();
104
+ if (files.length === 0) throw new Error(`No template JSON files found in '${directory}'.`);
105
+
106
+ const templates = new Map();
107
+ const loaded = files.map((file) => {
108
+ const path = join(directory, file);
109
+ let template;
110
+ try {
111
+ template = JSON.parse(readFileSync(path, "utf8"));
112
+ } catch (err) {
113
+ throw new Error(`Invalid JSON in template file '${path}': ${err.message}`, { cause: err });
114
+ }
115
+ return validateTemplate(template, `Template file '${path}'`);
116
+ });
117
+ loaded.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
118
+ for (const template of loaded) {
119
+ if (templates.has(template.name)) throw new Error(`Duplicate template '${template.name}'.`);
120
+ templates.set(template.name, template);
121
+ }
122
+ return templates;
123
+ }
124
+
125
+ export const BUILTIN_TEMPLATES = loadTemplates();
126
+
127
+ export function getTemplate(name, templates = BUILTIN_TEMPLATES) {
128
+ const template = templates.get(name);
129
+ if (!template) {
130
+ throw new Error(`Unknown template '${name}'. Available: ${[...templates.keys()].join(", ")}`);
131
+ }
132
+ return template;
133
+ }
134
+
135
+ /** Return the first template (by `order`) whose URL pattern matches, or null. */
136
+ export function detectTemplate(url, templates = BUILTIN_TEMPLATES) {
137
+ for (const template of templates.values()) {
138
+ if (template.url_patterns?.some((pattern) => new RegExp(pattern).test(url))) return template;
139
+ }
140
+ return null;
141
+ }
142
+
143
+ /** Resolve the `template` argument of `webfetch`: "auto", a template name, or inline JSON. */
144
+ export function resolvePageTemplate(url, value) {
145
+ if (value.trimStart().startsWith("{")) return parseInlineTemplate(value);
146
+ if (value === "auto") return detectTemplate(url);
147
+ return getTemplate(value);
148
+ }
149
+
150
+ export function validateUrl(value) {
151
+ let url;
152
+ try {
153
+ url = new URL(value);
154
+ } catch {
155
+ throw new Error(`Invalid URL: ${value}`);
156
+ }
157
+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname) {
158
+ throw new Error("URL must use HTTP or HTTPS and include a hostname.");
159
+ }
160
+ return value;
161
+ }
162
+
163
+ /** Fill `{placeholder}`s in `template.url_template` from `params` and `url_params` defaults. */
164
+ export function resolveUrlTemplate(template, params) {
165
+ if (!template.url_template) throw new Error(`Template '${template.name}' has no url_template.`);
166
+ return template.url_template.replace(/\{(\w+)\}/g, (_match, key) => {
167
+ const definition = template.url_params?.[key] ?? {};
168
+ const value = (Object.hasOwn(params, key) ? params[key] : null) ?? definition.default;
169
+ if (value == null && definition.required) {
170
+ throw new Error(
171
+ `Required URL parameter '${key}' is missing for template '${template.name}'.`,
172
+ );
173
+ }
174
+ const text = String(value ?? "");
175
+ return definition.encode === "url" ? encodeURIComponent(text) : text;
176
+ });
177
+ }
178
+
179
+ /** Map the engine-neutral `region` and `safe_search` options onto template URL params. */
180
+ export function mapSearchParams(engine, query, region, safeSearch) {
181
+ const params = { query };
182
+ if (engine === "duckduckgo") {
183
+ if (region != null) params.kl = region;
184
+ if (safeSearch != null) params.kp = safeSearch ? "1" : "-2";
185
+ } else if (engine === "google" && region != null) {
186
+ const [country, ...language] = region.split("-");
187
+ params.gl = country;
188
+ if (language.length > 0) params.hl = language.join("-");
189
+ }
190
+ return params;
191
+ }
192
+
193
+ /** Build the request URL for one search template. */
194
+ export function buildSearchUrl(template, query, region, safeSearch) {
195
+ if (!template.url_template) {
196
+ throw new Error(`Template '${template.name}' is not a search template (no url_template).`);
197
+ }
198
+ const params = mapSearchParams(template.engine, query, region, safeSearch);
199
+ const url = resolveUrlTemplate(template, params);
200
+ if (template.engine !== "google" || safeSearch == null) return url;
201
+ const separator = url.includes("?") ? "&" : "?";
202
+ return `${url}${separator}safe=${safeSearch ? "active" : "off"}`;
203
+ }
204
+
205
+ /**
206
+ * Resolve `websearch`'s `engine` argument into the ordered list of templates to try: the
207
+ * requested template followed by its `fallback` chain.
208
+ */
209
+ export function resolveSearchCandidates(engine, query, region, safeSearch) {
210
+ const first = engine.trimStart().startsWith("{")
211
+ ? parseInlineTemplate(engine)
212
+ : getTemplate(ENGINE_ALIASES[engine] ?? engine);
213
+
214
+ const candidates = [];
215
+ const seen = new Set();
216
+ for (let template = first; template && !seen.has(template.name);) {
217
+ seen.add(template.name);
218
+ candidates.push({ template, url: buildSearchUrl(template, query, region, safeSearch) });
219
+ template = template.fallback ? getTemplate(template.fallback) : null;
220
+ }
221
+ return candidates;
222
+ }
@@ -1,18 +1,12 @@
1
1
  {
2
2
  "name": "crates-package",
3
3
  "description": "crates.io package page — metadata and README",
4
- "order": 5,
4
+ "order": 50,
5
5
  "url_patterns": [
6
6
  "^https?://crates\\.io/crates/[^/]+/?$",
7
7
  "^https?://crates\\.io/crates/[^/]+/[^/]+/?$"
8
8
  ],
9
- "remove": [
10
- "script",
11
- "style",
12
- "svg",
13
- "nav",
14
- "footer"
15
- ],
9
+ "remove": ["script", "style", "svg", "nav", "footer"],
16
10
  "sections": [
17
11
  {
18
12
  "name": "Crate",
@@ -1,10 +1,8 @@
1
1
  {
2
2
  "name": "devto",
3
3
  "description": "DEV Community article — title, author, and content",
4
- "order": 20,
5
- "url_patterns": [
6
- "^https?://dev\\.to/[^/]+/[^/]+"
7
- ],
4
+ "order": 160,
5
+ "url_patterns": ["^https?://dev\\.to/[^/]+/[^/]+"],
8
6
  "remove": [
9
7
  "script",
10
8
  "style",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "docker-hub",
3
3
  "description": "Docker Hub image page — official and community images with description and README",
4
- "order": 10,
4
+ "order": 110,
5
5
  "url_patterns": [
6
6
  "^https?://hub\\.docker\\.com/_/[^/]+/?$",
7
7
  "^https?://hub\\.docker\\.com/r/[^/]+/[^/]+/?$"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "docs-page",
3
3
  "description": "Documentation page (ReadTheDocs, Sphinx, Mintlify, VitePress, Docusaurus, Nextra, etc.)",
4
- "order": 9,
4
+ "order": 100,
5
5
  "url_patterns": [
6
6
  "^https?://[^/]+\\.readthedocs\\.io/.*",
7
7
  "^https?://[^/]+\\.rtfd\\.io/.*",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "docs-rs",
3
3
  "description": "docs.rs rustdoc documentation page — crate docs, struct/enum/fn items",
4
- "order": 6,
4
+ "order": 60,
5
5
  "url_patterns": [
6
6
  "^https?://docs\\.rs/[^/]+/[^/]+/[^/]+/?$",
7
7
  "^https?://docs\\.rs/[^/]+/[^/]+/[^/]+/index\\.html$",
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "duckduckgo-lite-search",
3
+ "description": "DuckDuckGo Lite search results (fallback for the HTML endpoint)",
4
+ "order": 85,
5
+ "engine": "duckduckgo",
6
+ "url_patterns": ["^https?://lite\\.duckduckgo\\.com/lite/\\?"],
7
+ "url_template": "https://lite.duckduckgo.com/lite/?q={query}&kl={kl}&kp={kp}",
8
+ "url_params": {
9
+ "query": {
10
+ "required": true,
11
+ "description": "Search query string",
12
+ "encode": "url"
13
+ },
14
+ "kl": {
15
+ "required": false,
16
+ "default": "wt-wt",
17
+ "description": "Region/language code (e.g., 'us-en', 'de-de', 'wt-wt' for global)"
18
+ },
19
+ "kp": {
20
+ "required": false,
21
+ "default": "-1",
22
+ "description": "Safe search: '-1' moderate, '1' strict, '-2' off"
23
+ }
24
+ },
25
+ "block_resources": ["image", "media", "font", "stylesheet"],
26
+ "remove": ["script", "style", "svg", "img", "nav", "footer"],
27
+ "sections": [
28
+ {
29
+ "name": "Results",
30
+ "selector": "a.result-link",
31
+ "multiple": true,
32
+ "max_items": 10,
33
+ "children": [
34
+ {
35
+ "name": "Title",
36
+ "selector": "",
37
+ "format": "text"
38
+ },
39
+ {
40
+ "name": "URL",
41
+ "selector": "",
42
+ "format": "attribute",
43
+ "attribute": "href",
44
+ "transform": "decode_ddg_url"
45
+ }
46
+ ]
47
+ }
48
+ ]
49
+ }
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "duckduckgo-search",
3
3
  "description": "DuckDuckGo HTML search results",
4
- "order": 8,
5
- "url_patterns": [
6
- "^https?://html\\.duckduckgo\\.com/html/\\?"
7
- ],
4
+ "order": 80,
5
+ "engine": "duckduckgo",
6
+ "fallback": "duckduckgo-lite-search",
7
+ "url_patterns": ["^https?://html\\.duckduckgo\\.com/html/\\?"],
8
8
  "url_template": "https://html.duckduckgo.com/html/?q={query}&kl={kl}&kp={kp}",
9
9
  "url_params": {
10
10
  "query": {
@@ -23,20 +23,8 @@
23
23
  "description": "Safe search: '-1' moderate, '1' strict, '-2' off"
24
24
  }
25
25
  },
26
- "block_resources": [
27
- "image",
28
- "media",
29
- "font",
30
- "stylesheet"
31
- ],
32
- "remove": [
33
- "script",
34
- "style",
35
- "svg",
36
- "img",
37
- "nav",
38
- "footer"
39
- ],
26
+ "block_resources": ["image", "media", "font", "stylesheet"],
27
+ "remove": ["script", "style", "svg", "img", "nav", "footer"],
40
28
  "sections": [
41
29
  {
42
30
  "name": "Results",
@@ -1,18 +1,12 @@
1
1
  {
2
2
  "name": "github-issue",
3
3
  "description": "GitHub issue or pull request",
4
- "order": 2,
4
+ "order": 20,
5
5
  "url_patterns": [
6
6
  "^https?://github\\.com/[^/]+/[^/]+/issues/\\d+/?$",
7
7
  "^https?://github\\.com/[^/]+/[^/]+/pull/\\d+/?$"
8
8
  ],
9
- "remove": [
10
- "script",
11
- "style",
12
- "svg",
13
- ".octicon",
14
- ".anchor"
15
- ],
9
+ "remove": ["script", "style", "svg", ".octicon", ".anchor"],
16
10
  "sections": [
17
11
  {
18
12
  "name": "Title",
@@ -1,17 +1,9 @@
1
1
  {
2
2
  "name": "github-repo",
3
3
  "description": "GitHub repository root — file listing and README",
4
- "order": 1,
5
- "url_patterns": [
6
- "^https?://github\\.com/[^/]+/[^/]+/?$"
7
- ],
8
- "remove": [
9
- "script",
10
- "style",
11
- "svg",
12
- ".octicon",
13
- ".anchor"
14
- ],
4
+ "order": 10,
5
+ "url_patterns": ["^https?://github\\.com/[^/]+/[^/]+/?$"],
6
+ "remove": ["script", "style", "svg", ".octicon", ".anchor"],
15
7
  "sections": [
16
8
  {
17
9
  "name": "Description",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gitlab",
3
3
  "description": "GitLab project — description, file listing, and README",
4
- "order": 12,
4
+ "order": 130,
5
5
  "url_patterns": [
6
6
  "^https?://gitlab\\.com/[^/]+/[^/]+/?$",
7
7
  "^https?://gitlab\\.com/[^/]+/[^/]+/-/tree/[^/]+/?$"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "go-pkg",
3
3
  "description": "Go package documentation on pkg.go.dev — name, overview, and docs",
4
- "order": 22,
4
+ "order": 170,
5
5
  "url_patterns": [
6
6
  "^https?://pkg\\.go\\.dev/[^/]+/?$",
7
7
  "^https?://pkg\\.go\\.dev/[^/]+/[^/]+/?$",
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "google-search",
3
3
  "description": "Google web search results",
4
- "order": 7,
5
- "url_patterns": [
6
- "^https?://(www\\.)?google\\.[^/]+/search\\?"
7
- ],
4
+ "order": 70,
5
+ "engine": "google",
6
+ "fallback": "duckduckgo-search",
7
+ "url_patterns": ["^https?://(www\\.)?google\\.[^/]+/search\\?"],
8
8
  "url_template": "https://www.google.com/search?udm=14&q={query}&hl={hl}&gl={gl}",
9
9
  "url_params": {
10
10
  "query": {
@@ -31,20 +31,8 @@
31
31
  "path": "/"
32
32
  }
33
33
  ],
34
- "block_resources": [
35
- "image",
36
- "media",
37
- "font",
38
- "stylesheet"
39
- ],
40
- "remove": [
41
- "script",
42
- "style",
43
- "svg",
44
- "img",
45
- "nav",
46
- "footer"
47
- ],
34
+ "block_resources": ["image", "media", "font", "stylesheet"],
35
+ "remove": ["script", "style", "svg", "img", "nav", "footer"],
48
36
  "sections": [
49
37
  {
50
38
  "name": "Results",
@@ -54,7 +42,7 @@
54
42
  "children": [
55
43
  {
56
44
  "name": "Title",
57
- "selector": "h3, " ,
45
+ "selector": "h3, ",
58
46
  "format": "text"
59
47
  },
60
48
  {
@@ -1,10 +1,8 @@
1
1
  {
2
2
  "name": "javadoc",
3
3
  "description": "Java SE API documentation — class/method details",
4
- "order": 8.5,
5
- "url_patterns": [
6
- "^https?://docs\\.oracle\\.com/.*/docs/api/.*"
7
- ],
4
+ "order": 90,
5
+ "url_patterns": ["^https?://docs\\.oracle\\.com/.*/docs/api/.*"],
8
6
  "remove": [
9
7
  "script",
10
8
  "style",
@@ -1,10 +1,8 @@
1
1
  {
2
2
  "name": "mdn-web-docs",
3
3
  "description": "MDN Web Docs article — title and main content",
4
- "order": 15,
5
- "url_patterns": [
6
- "^https?://developer\\.mozilla\\.org/.*"
7
- ],
4
+ "order": 150,
5
+ "url_patterns": ["^https?://developer\\.mozilla\\.org/.*"],
8
6
  "remove": [
9
7
  "script",
10
8
  "style",
@@ -1,17 +1,9 @@
1
1
  {
2
2
  "name": "npm-package",
3
3
  "description": "npm package page — metadata and README",
4
- "order": 3,
5
- "url_patterns": [
6
- "^https?://(www\\.)?npmjs\\.com/package/[^/]+/?$"
7
- ],
8
- "remove": [
9
- "script",
10
- "style",
11
- "svg",
12
- "nav",
13
- "footer"
14
- ],
4
+ "order": 30,
5
+ "url_patterns": ["^https?://(www\\.)?npmjs\\.com/package/[^/]+/?$"],
6
+ "remove": ["script", "style", "svg", "nav", "footer"],
15
7
  "sections": [
16
8
  {
17
9
  "name": "Package",
@@ -1,18 +1,12 @@
1
1
  {
2
2
  "name": "pypi-package",
3
3
  "description": "PyPI package page — metadata and README",
4
- "order": 4,
4
+ "order": 40,
5
5
  "url_patterns": [
6
6
  "^https?://pypi\\.org/project/[^/]+/?$",
7
7
  "^https?://pypi\\.org/project/[^/]+/[^/]+/?$"
8
8
  ],
9
- "remove": [
10
- "script",
11
- "style",
12
- "svg",
13
- "nav",
14
- "footer"
15
- ],
9
+ "remove": ["script", "style", "svg", "nav", "footer"],
16
10
  "sections": [
17
11
  {
18
12
  "name": "Package",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "raw",
3
3
  "description": "Raw page content — minimal filtering, full body as markdown (use when you need the complete page without template extraction)",
4
- "order": 999,
4
+ "order": 1000,
5
5
  "remove": [],
6
6
  "sections": [
7
7
  {
@@ -1,10 +1,8 @@
1
1
  {
2
2
  "name": "reddit",
3
3
  "description": "Reddit post — title, content, and comments",
4
- "order": 13,
5
- "url_patterns": [
6
- "^https?://(?:www\\.|old\\.)?reddit\\.com/r/[^/]+/comments/[^/]+"
7
- ],
4
+ "order": 140,
5
+ "url_patterns": ["^https?://(?:www\\.|old\\.)?reddit\\.com/r/[^/]+/comments/[^/]+"],
8
6
  "remove": [
9
7
  "script",
10
8
  "style",
@@ -1,10 +1,8 @@
1
1
  {
2
2
  "name": "wikipedia",
3
3
  "description": "Wikipedia article — title and main content",
4
- "order": 11,
5
- "url_patterns": [
6
- "^https?://[a-z]{2,4}\\.wikipedia\\.org/wiki/[^:]+$"
7
- ],
4
+ "order": 120,
5
+ "url_patterns": ["^https?://[a-z]{2,4}\\.wikipedia\\.org/wiki/[^:]+$"],
8
6
  "remove": [
9
7
  "script",
10
8
  "style",
@@ -1,10 +1,8 @@
1
1
  {
2
2
  "name": "youtube",
3
3
  "description": "YouTube video — title, channel, description",
4
- "order": 30,
5
- "url_patterns": [
6
- "^https?://(?:www\\.)?(?:youtube\\.com/watch\\?v=|youtu\\.be/).+"
7
- ],
4
+ "order": 180,
5
+ "url_patterns": ["^https?://(?:www\\.)?(?:youtube\\.com/watch\\?v=|youtu\\.be/).+"],
8
6
  "remove": [
9
7
  "script",
10
8
  "style",