@sisu-ai/tool-web-fetch 8.0.0 → 8.0.2

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Tool } from '@sisu-ai/core';
2
- export type WebFetchFormat = 'text' | 'html' | 'json';
1
+ import type { Tool } from "@sisu-ai/core";
2
+ export type WebFetchFormat = "text" | "html" | "json";
3
3
  export interface WebFetchArgs {
4
4
  url: string;
5
5
  format?: WebFetchFormat;
package/dist/index.js CHANGED
@@ -1,32 +1,35 @@
1
- import { firstConfigValue } from '@sisu-ai/core';
2
- import { z } from 'zod';
1
+ import { firstConfigValue } from "@sisu-ai/core";
2
+ import { z } from "zod";
3
3
  export const webFetch = {
4
- name: 'webFetch',
5
- description: 'Fetch a web page by URL and return text, HTML, or JSON. Defaults to text extraction for HTML.',
4
+ name: "webFetch",
5
+ description: "Fetch a web page by URL and return text, HTML, or JSON. Defaults to text extraction for HTML.",
6
6
  schema: z.object({
7
7
  url: z.string().url(),
8
- format: z.enum(['text', 'html', 'json']).optional(),
8
+ format: z.enum(["text", "html", "json"]).optional(),
9
9
  maxBytes: z.number().int().positive().max(5_000_000).optional(),
10
10
  respectRobots: z.boolean().optional(),
11
11
  }),
12
- handler: async ({ url, format = 'text', maxBytes, respectRobots }, ctx) => {
13
- const ua = firstConfigValue(['WEB_FETCH_USER_AGENT', 'HTTP_USER_AGENT'])
14
- || 'SisuWebFetch/0.1 (+https://github.com/finger-gun/sisu)';
15
- const capEnv = firstConfigValue(['WEB_FETCH_MAX_BYTES']);
12
+ handler: async ({ url, format = "text", maxBytes, respectRobots }, ctx) => {
13
+ const ua = firstConfigValue(["WEB_FETCH_USER_AGENT", "HTTP_USER_AGENT"]) ||
14
+ "SisuWebFetch/0.1 (+https://github.com/finger-gun/sisu)";
15
+ const capEnv = firstConfigValue(["WEB_FETCH_MAX_BYTES"]);
16
16
  const cap = Number(maxBytes ?? (capEnv !== undefined ? Number(capEnv) : 500_000));
17
17
  // robots.txt compliance (default on; disable with arg or env WEB_FETCH_RESPECT_ROBOTS=0)
18
18
  const respect = (() => {
19
- if (typeof respectRobots === 'boolean')
19
+ if (typeof respectRobots === "boolean")
20
20
  return respectRobots;
21
- const env = firstConfigValue(['WEB_FETCH_RESPECT_ROBOTS', 'RESPECT_ROBOTS']);
21
+ const env = firstConfigValue([
22
+ "WEB_FETCH_RESPECT_ROBOTS",
23
+ "RESPECT_ROBOTS",
24
+ ]);
22
25
  if (env === undefined)
23
26
  return true; // default on
24
- return !(env === '0' || /^false$/i.test(env));
27
+ return !(env === "0" || /^false$/i.test(env));
25
28
  })();
26
29
  if (respect) {
27
30
  const decision = await robotsDecision(url, ua).catch(() => ({ allowed: true }));
28
31
  if (!decision.allowed) {
29
- ctx?.log?.info?.('[webFetch] blocked by robots.txt', {
32
+ ctx?.log?.info?.("[webFetch] blocked by robots.txt", {
30
33
  url,
31
34
  userAgent: ua,
32
35
  matchedAgent: decision.matchedAgent,
@@ -36,48 +39,76 @@ export const webFetch = {
36
39
  return {
37
40
  url,
38
41
  status: 403,
39
- contentType: 'text/plain',
40
- text: `Blocked by robots.txt (agent: ${decision.matchedAgent ?? 'unknown'}, rule: ${decision.ruleType ?? 'disallow'} ${decision.rulePattern ?? ''})`.
41
- trim(),
42
+ contentType: "text/plain",
43
+ text: `Blocked by robots.txt (agent: ${decision.matchedAgent ?? "unknown"}, rule: ${decision.ruleType ?? "disallow"} ${decision.rulePattern ?? ""})`.trim(),
42
44
  robotsBlocked: true,
43
- robotsAgent: ua
45
+ robotsAgent: ua,
44
46
  };
45
47
  }
46
48
  }
47
49
  const res = await fetch(url, {
48
- redirect: 'follow',
49
- headers: { 'User-Agent': ua, 'Accept': '*/*' },
50
+ redirect: "follow",
51
+ headers: { "User-Agent": ua, Accept: "*/*" },
50
52
  });
51
- const contentType = res.headers?.get?.('content-type') || '';
53
+ const contentType = res.headers?.get?.("content-type") || "";
52
54
  // Stream read with cap to avoid massive bodies
53
55
  const buf = await readWithCap(res, cap);
54
56
  const finalUrl = res.url || undefined;
55
57
  if (!res.ok) {
56
- return { url, finalUrl, status: res.status, contentType, text: truncateText(buf.toString('utf8')) };
58
+ return {
59
+ url,
60
+ finalUrl,
61
+ status: res.status,
62
+ contentType,
63
+ text: truncateText(buf.toString("utf8")),
64
+ };
57
65
  }
58
66
  // Handle by requested format and content-type
59
67
  const ctLower = contentType.toLowerCase();
60
- if (format === 'json' || ctLower.includes('application/json')) {
68
+ if (format === "json" || ctLower.includes("application/json")) {
61
69
  try {
62
- const json = JSON.parse(buf.toString('utf8'));
70
+ const json = JSON.parse(buf.toString("utf8"));
63
71
  return { url, finalUrl, status: res.status, contentType, json };
64
72
  }
65
73
  catch {
66
74
  // Fall through to text
67
75
  }
68
76
  }
69
- if (format === 'html' || ctLower.includes('text/html') || ctLower.includes('application/xhtml')) {
70
- const html = buf.toString('utf8');
71
- if (format === 'html') {
72
- return { url, finalUrl, status: res.status, contentType, html, title: extractTitle(html) };
77
+ if (format === "html" ||
78
+ ctLower.includes("text/html") ||
79
+ ctLower.includes("application/xhtml")) {
80
+ const html = buf.toString("utf8");
81
+ if (format === "html") {
82
+ return {
83
+ url,
84
+ finalUrl,
85
+ status: res.status,
86
+ contentType,
87
+ html,
88
+ title: extractTitle(html),
89
+ };
73
90
  }
74
91
  // format === 'text'
75
92
  const text = htmlToText(html);
76
- return { url, finalUrl, status: res.status, contentType, text, title: extractTitle(html), html: undefined };
93
+ return {
94
+ url,
95
+ finalUrl,
96
+ status: res.status,
97
+ contentType,
98
+ text,
99
+ title: extractTitle(html),
100
+ html: undefined,
101
+ };
77
102
  }
78
103
  // Fallback: treat as text/*
79
- const text = buf.toString('utf8');
80
- return { url, finalUrl, status: res.status, contentType, text: truncateText(text) };
104
+ const text = buf.toString("utf8");
105
+ return {
106
+ url,
107
+ finalUrl,
108
+ status: res.status,
109
+ contentType,
110
+ text: truncateText(text),
111
+ };
81
112
  },
82
113
  };
83
114
  export default webFetch;
@@ -87,10 +118,13 @@ async function robotsDecision(targetUrl, userAgent) {
87
118
  const origin = `${u.protocol}//${u.host}`;
88
119
  const cache = robotsCache.get(origin);
89
120
  const now = Date.now();
90
- if (!cache || (now - cache.ts) > 60 * 60 * 1000) { // 1h TTL
121
+ if (!cache || now - cache.ts > 60 * 60 * 1000) {
122
+ // 1h TTL
91
123
  const robotsUrl = `${origin}/robots.txt`;
92
124
  try {
93
- const res = await fetch(robotsUrl, { headers: { 'User-Agent': userAgent, 'Accept': 'text/plain' } });
125
+ const res = await fetch(robotsUrl, {
126
+ headers: { "User-Agent": userAgent, Accept: "text/plain" },
127
+ });
94
128
  const txt = await res.text();
95
129
  const rules = res.ok ? parseRobots(txt) : null;
96
130
  robotsCache.set(origin, { ts: now, rules });
@@ -102,7 +136,7 @@ async function robotsDecision(targetUrl, userAgent) {
102
136
  const rules = robotsCache.get(origin)?.rules;
103
137
  if (!rules)
104
138
  return { allowed: true };
105
- return evaluateRobotsDetailed(rules, userAgent, u.pathname + (u.search || ''));
139
+ return evaluateRobotsDetailed(rules, userAgent, u.pathname + (u.search || ""));
106
140
  }
107
141
  function parseRobots(text) {
108
142
  const lines = text.split(/\r?\n/);
@@ -110,31 +144,31 @@ function parseRobots(text) {
110
144
  let current = null;
111
145
  for (const raw of lines) {
112
146
  const line = raw.trim();
113
- if (!line || line.startsWith('#'))
147
+ if (!line || line.startsWith("#"))
114
148
  continue;
115
149
  const m = line.match(/^(user-agent|allow|disallow)\s*:\s*(.*)$/i);
116
150
  if (!m)
117
151
  continue;
118
152
  const key = m[1].toLowerCase();
119
153
  const val = m[2].trim();
120
- if (key === 'user-agent') {
154
+ if (key === "user-agent") {
121
155
  // Start a new group if we already had one and it contains rules
122
- if (!current || (current.allows.length + current.disallows.length) > 0) {
156
+ if (!current || current.allows.length + current.disallows.length > 0) {
123
157
  current = { agents: [], allows: [], disallows: [] };
124
158
  groups.push(current);
125
159
  }
126
160
  current.agents.push(val.toLowerCase());
127
161
  }
128
- else if (key === 'allow') {
162
+ else if (key === "allow") {
129
163
  if (!current) {
130
- current = { agents: ['*'], allows: [], disallows: [] };
164
+ current = { agents: ["*"], allows: [], disallows: [] };
131
165
  groups.push(current);
132
166
  }
133
167
  current.allows.push(val);
134
168
  }
135
- else if (key === 'disallow') {
169
+ else if (key === "disallow") {
136
170
  if (!current) {
137
- current = { agents: ['*'], allows: [], disallows: [] };
171
+ current = { agents: ["*"], allows: [], disallows: [] };
138
172
  groups.push(current);
139
173
  }
140
174
  current.disallows.push(val);
@@ -145,18 +179,20 @@ function parseRobots(text) {
145
179
  function evaluateRobotsDetailed(rules, userAgent, pathWithQuery) {
146
180
  // Match exact agent token (product) ignoring case, or '*'.
147
181
  // Example: 'SisuWebFetch/0.1 (+...)' -> baseAgent 'sisuwebfetch'
148
- const baseAgent = (userAgent.split(/[\/\s]/)[0] || '').toLowerCase();
182
+ const baseAgent = (userAgent.split(/[\s/]/)[0] || "").toLowerCase();
149
183
  const agentMatches = (agent) => {
150
- if (agent === '*')
184
+ if (agent === "*")
151
185
  return true;
152
186
  return agent.toLowerCase() === baseAgent;
153
187
  };
154
188
  const matching = rules.groups
155
- .map(g => ({ g, matchedAgent: g.agents.find(agentMatches) }))
156
- .filter(x => !!x.matchedAgent);
189
+ .map((g) => ({ g, matchedAgent: g.agents.find(agentMatches) }))
190
+ .filter((x) => !!x.matchedAgent);
157
191
  const selected = matching.length
158
192
  ? matching
159
- : rules.groups.filter(g => g.agents.includes('*')).map(g => ({ g, matchedAgent: '*' }));
193
+ : rules.groups
194
+ .filter((g) => g.agents.includes("*"))
195
+ .map((g) => ({ g, matchedAgent: "*" }));
160
196
  if (!selected.length)
161
197
  return { allowed: true };
162
198
  // longest match wins between allow and disallow
@@ -172,7 +208,7 @@ function evaluateRobotsDetailed(rules, userAgent, pathWithQuery) {
172
208
  const L = pat.length;
173
209
  if (L > bestLen) {
174
210
  bestLen = L;
175
- bestType = 'allow';
211
+ bestType = "allow";
176
212
  bestPat = pat;
177
213
  bestAgent = matchedAgent;
178
214
  }
@@ -185,28 +221,38 @@ function evaluateRobotsDetailed(rules, userAgent, pathWithQuery) {
185
221
  const L = pat.length;
186
222
  if (L > bestLen) {
187
223
  bestLen = L;
188
- bestType = 'disallow';
224
+ bestType = "disallow";
189
225
  bestPat = pat;
190
226
  bestAgent = matchedAgent;
191
227
  }
192
228
  }
193
229
  }
194
230
  }
195
- if (bestType === 'disallow')
196
- return { allowed: false, matchedAgent: bestAgent, ruleType: 'disallow', rulePattern: bestPat };
197
- return { allowed: true, matchedAgent: bestAgent, ruleType: bestType, rulePattern: bestPat };
231
+ if (bestType === "disallow")
232
+ return {
233
+ allowed: false,
234
+ matchedAgent: bestAgent,
235
+ ruleType: "disallow",
236
+ rulePattern: bestPat,
237
+ };
238
+ return {
239
+ allowed: true,
240
+ matchedAgent: bestAgent,
241
+ ruleType: bestType,
242
+ rulePattern: bestPat,
243
+ };
198
244
  }
199
245
  function patternMatches(pat, path) {
200
246
  // Support '*' wildcard and '$' end anchor; treat path as starting with '/'
201
247
  const p = pat.trim();
202
- if (p === '')
248
+ if (p === "")
203
249
  return false;
204
250
  // Empty disallow means allow all; already handled by return false above
205
251
  // Convert to regex
206
- const escaped = p.replace(/[.+?^${}()|\[\]\\]/g, r => '\\' + r);
207
- let reStr = '^' + escaped.replace(/\*/g, '.*');
208
- if (reStr.endsWith('\$')) {
209
- reStr = reStr.slice(0, -2) + '$';
252
+ const escaped = p.replace(/[.+?^${}()|[\]\\]/g, (r) => "\\" + r);
253
+ let reStr = "^" + escaped.replace(/\*/g, ".*");
254
+ if (reStr.endsWith("$")) {
255
+ reStr = reStr.slice(0, -1) + "$";
210
256
  }
211
257
  const re = new RegExp(reStr);
212
258
  return re.test(path);
@@ -214,9 +260,9 @@ function patternMatches(pat, path) {
214
260
  async function readWithCap(res, cap) {
215
261
  // If body is not a stream (older fetch mocks), try res.text()
216
262
  const anyRes = res;
217
- if (!anyRes.body || typeof anyRes.body.getReader !== 'function') {
218
- const t = typeof anyRes.text === 'function' ? await anyRes.text() : '';
219
- return Buffer.from(String(t), 'utf8');
263
+ if (!anyRes.body || typeof anyRes.body.getReader !== "function") {
264
+ const t = typeof anyRes.text === "function" ? await anyRes.text() : "";
265
+ return Buffer.from(String(t), "utf8");
220
266
  }
221
267
  const reader = anyRes.body.getReader();
222
268
  const chunks = [];
@@ -249,34 +295,34 @@ function extractTitle(html) {
249
295
  function htmlToText(html) {
250
296
  // Remove script/style robustly: allow attributes and sloppy closing tags like </script foo="bar"> or </script >
251
297
  let s = html
252
- .replace(/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>/gi, ' ')
253
- .replace(/<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>/gi, ' ');
298
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>/gi, " ")
299
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>/gi, " ");
254
300
  // Remove HTML comments, including non-standard end '--!>' browsers tolerate
255
- s = s.replace(/<!--[\s\S]*?--!?>(\n)?/g, ' ');
301
+ s = s.replace(/<!--[\s\S]*?--!?>(\n)?/g, " ");
256
302
  // Replace <br> and block tags with newlines
257
- s = s.replace(/<(br|BR)\s*\/?>(\n)?/g, '\n');
258
- s = s.replace(/<\/(p|div|section|article|h[1-6]|li|ul|ol|header|footer|main)>/gi, '\n');
303
+ s = s.replace(/<(br|BR)\s*\/?>(\n)?/g, "\n");
304
+ s = s.replace(/<\/(p|div|section|article|h[1-6]|li|ul|ol|header|footer|main)>/gi, "\n");
259
305
  // Strip remaining tags
260
- s = s.replace(/<[^>]+>/g, ' ');
306
+ s = s.replace(/<[^>]+>/g, " ");
261
307
  // Decode entities
262
308
  s = decodeHTMLEntities(s);
263
309
  // Collapse whitespace
264
- s = s.replace(/\s+/g, ' ').trim();
310
+ s = s.replace(/\s+/g, " ").trim();
265
311
  return truncateText(s);
266
312
  }
267
313
  function truncateText(text, max = 200_000) {
268
- return text.length > max ? text.slice(0, max) + '' : text;
314
+ return text.length > max ? text.slice(0, max) + "" : text;
269
315
  }
270
316
  // Minimal HTML entity decoder for common entities
271
317
  function decodeHTMLEntities(s) {
272
318
  const map = {
273
- '&amp;': '&',
274
- '&lt;': '<',
275
- '&gt;': '>',
276
- '&quot;': '"',
277
- '&#39;': "'",
278
- '&apos;': "'",
279
- '&nbsp;': ' ',
319
+ "&amp;": "&",
320
+ "&lt;": "<",
321
+ "&gt;": ">",
322
+ "&quot;": '"',
323
+ "&#39;": "'",
324
+ "&apos;": "'",
325
+ "&nbsp;": " ",
280
326
  };
281
327
  return s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => map[m] || m);
282
328
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sisu-ai/tool-web-fetch",
3
- "version": "8.0.0",
3
+ "version": "8.0.2",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -8,14 +8,11 @@
8
8
  "files": [
9
9
  "dist"
10
10
  ],
11
- "scripts": {
12
- "build": "tsc -b"
13
- },
14
11
  "dependencies": {
15
12
  "zod": "^3.23.8"
16
13
  },
17
14
  "peerDependencies": {
18
- "@sisu-ai/core": "^2.3.0"
15
+ "@sisu-ai/core": "^2.3.1"
19
16
  },
20
17
  "repository": {
21
18
  "type": "git",
@@ -33,5 +30,12 @@
33
30
  "agentic",
34
31
  "tool",
35
32
  "web-fetch"
36
- ]
37
- }
33
+ ],
34
+ "scripts": {
35
+ "build": "tsc -b",
36
+ "clean": "rm -rf dist",
37
+ "lint": "eslint src --ext .ts,.js",
38
+ "lint:fix": "eslint src --ext .ts,.js --fix",
39
+ "typecheck": "tsc --noEmit"
40
+ }
41
+ }