@zeldrisho/pi-web-fetch 0.18.0 → 0.18.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.
@@ -1,6 +1,6 @@
1
1
  import type { CompleteDocument } from "./content.ts";
2
2
 
3
- /** Removes a URL fragment before acquisition so fragment variants share cache entries. */
3
+ /** Removes the client-side fragment before network acquisition. */
4
4
  export function urlWithoutFragment(rawUrl: string): string {
5
5
  try {
6
6
  const url = new URL(rawUrl);
@@ -33,32 +33,48 @@ function sourceOffset(markdown: string, lineNumber: number, columnNumber = 1): n
33
33
  return offset + Math.min(columnNumber - 1, lines[lineNumber - 1].length);
34
34
  }
35
35
 
36
- /** Resolves heading and source-location URL fragments against a fetched document. */
37
- export function resolveFragmentOffset(
38
- document: CompleteDocument,
39
- rawUrl: string,
40
- ): ResolvedFragment {
41
- let fragment: string | undefined;
36
+ const SOURCE_LINE_ANCHOR = /^L(\d+)(?:C(\d+))?(?:-L?(\d+)(?:C(\d+))?)?$/i;
37
+
38
+ /** Reads a URL fragment, retaining malformed percent escapes as literal text. */
39
+ export function urlFragment(rawUrl: string): string | undefined {
40
+ let fragment: string;
42
41
 
43
42
  try {
44
- const hash = new URL(rawUrl).hash;
43
+ fragment = new URL(rawUrl).hash.slice(1);
44
+ } catch {
45
+ return undefined;
46
+ }
45
47
 
46
- if (hash) {
47
- const rawFragment = hash.slice(1);
48
+ if (!fragment) return undefined;
48
49
 
49
- try {
50
- fragment = decodeURIComponent(rawFragment);
51
- } catch {
52
- fragment = rawFragment;
53
- }
54
- }
50
+ try {
51
+ return decodeURIComponent(fragment);
55
52
  } catch {
56
- return {};
53
+ return fragment;
57
54
  }
55
+ }
56
+
57
+ /** A bounded potential HTML tab ID, not a source line/range. */
58
+ export function fragmentTabId(rawUrl: string): string | undefined {
59
+ const fragment = urlFragment(rawUrl);
60
+
61
+ return fragment && isFragmentTabId(fragment) ? fragment : undefined;
62
+ }
63
+
64
+ export function isFragmentTabId(fragment: string): boolean {
65
+ return /^[\w.:-]{1,80}$/u.test(fragment) && !SOURCE_LINE_ANCHOR.test(fragment);
66
+ }
67
+
68
+ /** Resolves heading and source-location URL fragments against a fetched document. */
69
+ export function resolveFragmentOffset(
70
+ document: CompleteDocument,
71
+ rawUrl: string,
72
+ ): ResolvedFragment {
73
+ const fragment = urlFragment(rawUrl);
58
74
 
59
75
  if (!fragment) return {};
60
76
 
61
- const lineAnchor = /^L(\d+)(?:C(\d+))?(?:-L?(\d+)(?:C(\d+))?)?$/i.exec(fragment);
77
+ const lineAnchor = SOURCE_LINE_ANCHOR.exec(fragment);
62
78
 
63
79
  if (lineAnchor) {
64
80
  const [, firstLine, firstColumn, lastLine, lastColumn] = lineAnchor;
@@ -19,7 +19,7 @@ function stripCompleteStyleElements(value: string): string {
19
19
  let cleaned = value;
20
20
 
21
21
  while (true) {
22
- const next = cleaned.replace(COMPLETE_STYLE_ELEMENT, "");
22
+ const next = cleaned.replaceAll(COMPLETE_STYLE_ELEMENT, "");
23
23
 
24
24
  if (next === cleaned) return cleaned;
25
25
  cleaned = next;
@@ -109,6 +109,6 @@ export function stripExtractedCssCruft(markdown: string): string {
109
109
 
110
110
  return output
111
111
  .join("\n")
112
- .replace(/\n{3,}/g, "\n\n")
112
+ .replaceAll(/\n{3,}/g, "\n\n")
113
113
  .trim();
114
114
  }
@@ -1,9 +1,25 @@
1
- import { parse } from "acorn";
2
- import { simple } from "acorn-walk";
3
- import { parseDocument } from "yaml";
1
+ import { createRequire } from "node:module";
4
2
  import { Type } from "typebox";
5
3
  import { Check } from "typebox/value";
6
4
 
5
+ const require = createRequire(import.meta.url);
6
+
7
+ let parserModules:
8
+ | {
9
+ parse: typeof import("acorn").parse;
10
+ simple: typeof import("acorn-walk").simple;
11
+ parseDocument: typeof import("yaml").parseDocument;
12
+ }
13
+ | undefined;
14
+
15
+ function getParserModules(): NonNullable<typeof parserModules> {
16
+ return (parserModules ??= {
17
+ parse: require("acorn").parse,
18
+ simple: require("acorn-walk").simple,
19
+ parseDocument: require("yaml").parseDocument,
20
+ });
21
+ }
22
+
7
23
  const schema = Type.Union([
8
24
  Type.Object({
9
25
  openapi: Type.String({ pattern: "^3\\.\\d+\\.\\d+$" }),
@@ -24,12 +40,13 @@ export function isOpenapiSource(raw: string, contentType: string): boolean {
24
40
  if (contentType === "application/json") return Check(schema, JSON.parse(raw));
25
41
 
26
42
  if (contentType === "text/yaml") {
27
- const document = parseDocument(raw, { uniqueKeys: true });
43
+ const document = getParserModules().parseDocument(raw, { uniqueKeys: true });
28
44
 
29
45
  return document.errors.length === 0 && Check(schema, document.toJS({ maxAliasCount: 0 }));
30
46
  }
31
47
 
32
48
  if (contentType !== "text/javascript") return false;
49
+ const { parse, simple } = getParserModules();
33
50
  const ast = parse(raw, { ecmaVersion: "latest", sourceType: "module" });
34
51
  let found = false;
35
52
  simple(ast, {
@@ -39,8 +56,9 @@ export function isOpenapiSource(raw: string, contentType: string): boolean {
39
56
  let paths = false;
40
57
 
41
58
  for (const property of node.properties) {
42
- if (property.type !== "Property" || property.computed || property.kind !== "init")
59
+ if (property.type !== "Property" || property.computed || property.kind !== "init") {
43
60
  continue;
61
+ }
44
62
 
45
63
  const key =
46
64
  property.key.type === "Identifier"
@@ -16,13 +16,13 @@ function isSourceContentType(value: string): value is SourceContentType {
16
16
  }
17
17
 
18
18
  /** Shortest body reformatted; below this a page is returned verbatim. */
19
- const MINIFIED_MIN_CHARACTERS = 2_000;
19
+ const MINIFIED_MIN_CHARACTERS = 2000;
20
20
 
21
21
  /**
22
22
  * Largest body reformatted. Reformatting triples transient memory for a document too
23
23
  * large to cache, so bigger bodies keep their original single-line layout.
24
24
  */
25
- const MINIFIED_MAX_CHARACTERS = 2 * 1_024 * 1_024;
25
+ const MINIFIED_MAX_CHARACTERS = 2 * 1024 * 1024;
26
26
 
27
27
  /**
28
28
  * Shortest average line that still counts as machine-generated. Bundled source is
@@ -51,8 +51,9 @@ const LINE_ENDING_CHARACTERS = new Set([",", ";"]);
51
51
  * author's line structure, which is more useful than any generated layout.
52
52
  */
53
53
  function isMinified(value: string): boolean {
54
- if (value.length < MINIFIED_MIN_CHARACTERS || value.length > MINIFIED_MAX_CHARACTERS)
54
+ if (value.length < MINIFIED_MIN_CHARACTERS || value.length > MINIFIED_MAX_CHARACTERS) {
55
55
  return false;
56
+ }
56
57
 
57
58
  let lineBreaks = 0;
58
59
 
package/src/limits.ts CHANGED
@@ -2,10 +2,10 @@
2
2
  export const FETCH_DEFAULT_OFFSET = 0;
3
3
 
4
4
  /** Minimum allowed value for maxCharacters parameter. */
5
- export const FETCH_MIN_MAX_CHARACTERS = 1_000;
5
+ export const FETCH_MIN_MAX_CHARACTERS = 1000;
6
6
 
7
7
  /** Default maximum characters to return per fetch. */
8
- export const FETCH_DEFAULT_MAX_CHARACTERS = 6_000;
8
+ export const FETCH_DEFAULT_MAX_CHARACTERS = 6000;
9
9
 
10
10
  /** Maximum allowed characters to return per fetch. */
11
11
  export const FETCH_MAX_CHARACTERS = 30_000;
@@ -17,4 +17,4 @@ export const FETCH_MAX_OFFSET_CHARACTERS = 20_000_000;
17
17
  export const FETCH_MAX_QUERY_CHARACTERS = 400;
18
18
 
19
19
  /** Maximum allowed length for input URLs (characters). */
20
- export const FETCH_MAX_URL_CHARACTERS = 2_048;
20
+ export const FETCH_MAX_URL_CHARACTERS = 2048;
@@ -4,7 +4,7 @@ import type { IncomingHttpHeaders, IncomingMessage } from "node:http";
4
4
  const MAX_COOKIES = 128;
5
5
 
6
6
  /** Maximum accepted cookie value length in characters. */
7
- const MAX_COOKIE_VALUE_CHARACTERS = 4_096;
7
+ const MAX_COOKIE_VALUE_CHARACTERS = 4096;
8
8
 
9
9
  /** Maximum accepted cookie name length in characters. */
10
10
  const MAX_COOKIE_NAME_CHARACTERS = 256;
@@ -148,7 +148,7 @@ function parseSetCookie(raw: string, url: URL, now: number): ParsedCookie | unde
148
148
  ? expires
149
149
  : maxAge <= 0
150
150
  ? now - 1
151
- : now + Math.min(maxAge, 31_536_000) * 1_000;
151
+ : now + Math.min(maxAge, 31_536_000) * 1000;
152
152
 
153
153
  return { name, value, path, secure, expiresAt };
154
154
  }
@@ -145,15 +145,17 @@ export async function validateRemoteUrl(
145
145
  ): Promise<ValidatedTarget> {
146
146
  const url = value instanceof URL ? value : new URL(value);
147
147
 
148
- if (url.protocol !== "http:" && url.protocol !== "https:")
148
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
149
149
  throw new Error("web_fetch only supports HTTP and HTTPS URLs.");
150
+ }
150
151
 
151
- if (url.username || url.password)
152
+ if (url.username || url.password) {
152
153
  throw new Error("web_fetch blocks URLs containing credentials.");
154
+ }
153
155
 
154
156
  const hostname = url.hostname
155
157
  .toLowerCase()
156
- .replace(/^\[|\]$/g, "")
158
+ .replaceAll(/^\[|\]$/g, "")
157
159
  .replace(/\.$/, "");
158
160
 
159
161
  if (!hostname || hostname === "localhost" || hostname.endsWith(".localhost")) {
@@ -17,7 +17,7 @@ const BASE_RETRY_DELAY_MS = 250;
17
17
 
18
18
  interface OriginState {
19
19
  active: number;
20
- waiting: Array<() => void>;
20
+ waiting: (() => void)[];
21
21
  }
22
22
 
23
23
  const origins = new Map<string, OriginState>();
@@ -121,7 +121,7 @@ function retryAfterMilliseconds(value: string | undefined, now = Date.now()): nu
121
121
  if (!value) return undefined;
122
122
  const trimmed = value.trim();
123
123
 
124
- if (/^\d+(?:\.\d+)?$/u.test(trimmed)) return Number(trimmed) * 1_000;
124
+ if (/^\d+(?:\.\d+)?$/u.test(trimmed)) return Number(trimmed) * 1000;
125
125
  const date = Date.parse(value);
126
126
 
127
127
  if (!Number.isFinite(date)) return undefined;
@@ -144,6 +144,7 @@ async function coordinatedRequest(
144
144
  const random = dependencies.random ?? Math.random;
145
145
  const sleep = dependencies.sleep ?? defaultSleep;
146
146
 
147
+ // oxlint-disable-next-line no-useless-assignment -- the update feeds the next retry iteration
147
148
  for (let attempt = 0; ; attempt += 1) {
148
149
  const release = await acquireOrigin(target.url.origin, signal);
149
150
  let response: IncomingMessage;
@@ -211,11 +212,12 @@ export async function requestFollowingRedirects(
211
212
 
212
213
  if (!location) throw new Error("web_fetch received a redirect without a Location header.");
213
214
 
214
- if (redirects === FETCH_MAX_REDIRECTS)
215
+ if (redirects === FETCH_MAX_REDIRECTS) {
215
216
  throw new Error("web_fetch followed too many redirects.");
217
+ }
216
218
  target = await awaitWithAbort(validateUrl(new URL(location, target.url)), signal);
217
219
  // Validators describe the originally cached resource and must not leak to a redirect target.
218
- // Challenge handshakes opt into a fixed browser identity instead.
220
+ // Representation preferences and challenge identities are safe to retain.
219
221
  requestHeaders = dependencies.persistentHeaders ?? {};
220
222
  }
221
223
 
@@ -6,7 +6,7 @@ import { formatSize } from "@earendil-works/pi-coding-agent";
6
6
  import type { ValidatedTarget } from "./network-policy.ts";
7
7
 
8
8
  /** Maximum size in bytes for raw HTTP response bodies. */
9
- export const FETCH_MAX_BYTES = 5 * 1_024 * 1_024;
9
+ export const FETCH_MAX_BYTES = 5 * 1024 * 1024;
10
10
 
11
11
  /** Fixed User-Agent used for page requests and challenge solvers. */
12
12
  export const WEB_FETCH_USER_AGENT = "Mozilla/5.0 (compatible; PiWebFetch/1.0; +https://pi.dev)";
@@ -16,7 +16,7 @@ export const WEB_FETCH_USER_AGENT = "Mozilla/5.0 (compatible; PiWebFetch/1.0; +h
16
16
  * budget so the next validated address can be tried inside the overall
17
17
  * request timeout.
18
18
  */
19
- export const CONNECT_ATTEMPT_TIMEOUT_MS = 4_000;
19
+ export const CONNECT_ATTEMPT_TIMEOUT_MS = 4000;
20
20
 
21
21
  const encoder = new TextEncoder();
22
22
 
@@ -195,6 +195,7 @@ export async function requestPinned(
195
195
  }
196
196
  }
197
197
 
198
+ // oxlint-disable-next-line typescript/only-throw-error -- propagate the last connection rejection unchanged
198
199
  throw lastError ?? new Error("web_fetch could not connect.");
199
200
  }
200
201
 
@@ -327,8 +328,9 @@ export function decompressResponse(
327
328
  else if (encoding === "br") bytes = brotliDecompressSync(bytes, options);
328
329
  else throw new Error(`unsupported content encoding: ${encoding}`);
329
330
  } catch (error) {
330
- if (error instanceof Error && error.message.startsWith("unsupported content encoding:"))
331
+ if (error instanceof Error && error.message.startsWith("unsupported content encoding:")) {
331
332
  throw error;
333
+ }
332
334
 
333
335
  if (error instanceof Error && "code" in error && error.code === "ERR_BUFFER_TOO_LARGE") {
334
336
  throw new Error(
@@ -347,7 +349,7 @@ export function decodeResponse(bytes: Uint8Array, contentTypeHeader: string): st
347
349
  const charset = contentTypeHeader.match(/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i)?.[1];
348
350
 
349
351
  try {
350
- return new TextDecoder(charset || "utf-8").decode(bytes);
352
+ return new TextDecoder(charset || "utf8").decode(bytes);
351
353
  } catch {
352
354
  return new TextDecoder("utf-8").decode(bytes);
353
355
  }
package/src/render.ts CHANGED
@@ -12,7 +12,7 @@ export function renderCollapsibleOutput(
12
12
  warning?: string,
13
13
  expandHint = "Ctrl+O to expand",
14
14
  ): Container {
15
- const lines = output.replace(/\r\n/g, "\n").split("\n");
15
+ const lines = output.replaceAll("\r\n", "\n").split("\n");
16
16
 
17
17
  while (lines.at(-1) === "") lines.pop();
18
18
  const visible = expanded ? lines : lines.slice(0, COLLAPSED_LINES);