dsh-querit 1.1.2 → 2.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.
- package/README.md +62 -46
- package/cordis.patch.yml +6 -0
- package/lib/card.js +264 -240
- package/lib/client.d.ts +105 -6
- package/lib/client.js +198 -41
- package/lib/index.d.ts +70 -59
- package/lib/index.js +150 -123
- package/lib/provider.d.ts +51 -17
- package/lib/provider.js +160 -90
- package/lib/sanitize.d.ts +2 -0
- package/lib/sanitize.js +4 -0
- package/package.json +29 -30
- package/lib/invariant.d.ts +0 -18
- package/lib/invariant.js +0 -20
package/lib/client.d.ts
CHANGED
|
@@ -1,10 +1,38 @@
|
|
|
1
|
-
|
|
1
|
+
/** Per-operation deadline, retries and backoff waits included. */
|
|
2
2
|
export declare const DEFAULT_REQUEST_TIMEOUT_MS = 70000;
|
|
3
|
+
export declare const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
4
|
+
/** Largest `count` the API accepts. */
|
|
5
|
+
export declare const QUERIT_COUNT_LIMIT = 100;
|
|
6
|
+
/** Largest `contentMaxChars` the API accepts. */
|
|
7
|
+
export declare const QUERIT_CONTENT_MAX_CHARS_LIMIT = 1000000;
|
|
8
|
+
/** The values `filters.vertical`, `rank.preference`, and `filters.resourceTags.include[]` accept. */
|
|
9
|
+
export declare const VERTICAL_VALUES: readonly ["code", "finance"];
|
|
10
|
+
export declare const RANK_VALUES: readonly ["relevance", "freshness"];
|
|
11
|
+
export declare const RESOURCE_TAG_VALUES: readonly ["qa", "github"];
|
|
12
|
+
export type QueritVertical = (typeof VERTICAL_VALUES)[number];
|
|
13
|
+
export type QueritRankPreference = (typeof RANK_VALUES)[number];
|
|
14
|
+
export type QueritResourceTag = (typeof RESOURCE_TAG_VALUES)[number];
|
|
15
|
+
interface QueritHighlights {
|
|
16
|
+
/** Guides the extraction; Querit falls back to the top-level query when omitted. */
|
|
17
|
+
query?: string;
|
|
18
|
+
maxCharacters?: number;
|
|
19
|
+
}
|
|
3
20
|
export interface QueritSearchRequest {
|
|
4
21
|
query: string;
|
|
5
|
-
|
|
22
|
+
/** Omit to let Querit apply its server default. */
|
|
23
|
+
count?: number;
|
|
24
|
+
/** Deprecated by Querit in favor of `highlights`. Send only when a user explicitly configured it. */
|
|
6
25
|
chunksPerDoc?: number;
|
|
26
|
+
highlights?: boolean | QueritHighlights;
|
|
7
27
|
needContent?: boolean;
|
|
28
|
+
/** Body-text limit per result; only meaningful together with `needContent: true`. */
|
|
29
|
+
contentMaxChars?: number;
|
|
30
|
+
/** Enterprise only; ignored by Querit on other plans. */
|
|
31
|
+
needMarkdown?: boolean;
|
|
32
|
+
/** Returns 400 when combined with `filters.vertical: "code"`. */
|
|
33
|
+
rank?: {
|
|
34
|
+
preference: QueritRankPreference;
|
|
35
|
+
};
|
|
8
36
|
filters?: {
|
|
9
37
|
sites?: {
|
|
10
38
|
include?: string[];
|
|
@@ -21,6 +49,11 @@ export interface QueritSearchRequest {
|
|
|
21
49
|
languages?: {
|
|
22
50
|
include: string[];
|
|
23
51
|
};
|
|
52
|
+
vertical?: QueritVertical;
|
|
53
|
+
/** Sub-tags of a vertical. Only `qa` and `github`, on the code vertical, are documented. */
|
|
54
|
+
resourceTags?: {
|
|
55
|
+
include?: QueritResourceTag[];
|
|
56
|
+
};
|
|
24
57
|
};
|
|
25
58
|
}
|
|
26
59
|
export interface QueritContentsRequest {
|
|
@@ -28,49 +61,99 @@ export interface QueritContentsRequest {
|
|
|
28
61
|
format: "text" | "markdown" | "html";
|
|
29
62
|
crawlTimeout: number;
|
|
30
63
|
extrasMeta: boolean;
|
|
64
|
+
/** Content limit per URL. Omit for the full available content. */
|
|
65
|
+
contentMaxChars?: number;
|
|
66
|
+
highlights?: QueritHighlights;
|
|
67
|
+
}
|
|
68
|
+
interface QueritCost {
|
|
69
|
+
/** Querit always reports "USD". */
|
|
70
|
+
currency: string;
|
|
71
|
+
/** Charge in dollars with up to six decimal places; 0 is a reported zero charge. */
|
|
72
|
+
total: number;
|
|
31
73
|
}
|
|
32
|
-
|
|
74
|
+
interface QueritSearchResult {
|
|
33
75
|
title: string;
|
|
34
76
|
url: string;
|
|
35
77
|
snippet: string;
|
|
36
78
|
pageAge?: string;
|
|
37
79
|
siteName?: string;
|
|
38
80
|
siteIcon?: string;
|
|
81
|
+
/** Body text, present only when `needContent: true` was requested and is available. */
|
|
39
82
|
sentences: string[];
|
|
83
|
+
/** Query-focused fragments, present only when `highlights` was requested and is available. */
|
|
84
|
+
highlights: string[];
|
|
85
|
+
/** Markdown versions. Omitted unless `needMarkdown: true` was requested on an Enterprise plan. */
|
|
86
|
+
snippetMarkdown?: string[];
|
|
87
|
+
contentMarkdown?: string;
|
|
40
88
|
}
|
|
41
89
|
export interface QueritSearchResponse {
|
|
90
|
+
errorCode?: string;
|
|
91
|
+
errorMessage?: string;
|
|
42
92
|
searchId?: string;
|
|
43
93
|
took?: string;
|
|
94
|
+
/** Absent means unavailable, never "free". */
|
|
95
|
+
cost?: QueritCost;
|
|
44
96
|
query: string;
|
|
45
97
|
results: QueritSearchResult[];
|
|
46
98
|
}
|
|
47
|
-
|
|
99
|
+
interface QueritContentMetadata {
|
|
100
|
+
title?: string;
|
|
101
|
+
url?: string;
|
|
102
|
+
publishTime?: string;
|
|
103
|
+
siteName?: string;
|
|
104
|
+
siteIcon?: string;
|
|
105
|
+
}
|
|
106
|
+
interface QueritContentResult {
|
|
48
107
|
id?: string;
|
|
49
108
|
url: string;
|
|
50
109
|
content: string;
|
|
110
|
+
highlights: string[];
|
|
111
|
+
metadata?: QueritContentMetadata;
|
|
51
112
|
}
|
|
52
|
-
|
|
113
|
+
interface QueritContentStatus {
|
|
53
114
|
id?: string;
|
|
54
115
|
status?: string;
|
|
55
116
|
}
|
|
56
117
|
export interface QueritContentsResponse {
|
|
118
|
+
errorCode?: string;
|
|
119
|
+
errorMessage?: string;
|
|
57
120
|
searchId?: string;
|
|
121
|
+
searchTime?: number;
|
|
122
|
+
/** Absent means unavailable, never "free". */
|
|
123
|
+
cost?: QueritCost;
|
|
58
124
|
results: QueritContentResult[];
|
|
59
125
|
statuses: QueritContentStatus[];
|
|
60
|
-
|
|
126
|
+
}
|
|
127
|
+
export interface QueritRetryOptions {
|
|
128
|
+
/** Retries after the first attempt. `0` disables retries. */
|
|
129
|
+
maxRetries: number;
|
|
130
|
+
baseDelayMs: number;
|
|
131
|
+
/**
|
|
132
|
+
* Ceiling for backoff waits and for an honored `Retry-After`. A `Retry-After` that
|
|
133
|
+
* exceeds it is not waited out: the tool call fails instead of blocking the agent.
|
|
134
|
+
*/
|
|
135
|
+
maxDelayMs: number;
|
|
61
136
|
}
|
|
62
137
|
export interface QueritClientOptions {
|
|
63
138
|
apiKey: string;
|
|
64
139
|
fetchImpl?: typeof fetch;
|
|
65
140
|
baseUrl?: string;
|
|
141
|
+
/** Deadline for the whole operation, retries and backoff waits included. */
|
|
66
142
|
timeoutMs?: number;
|
|
143
|
+
retry?: Partial<QueritRetryOptions>;
|
|
67
144
|
}
|
|
68
145
|
export declare class QueritApiError extends Error {
|
|
69
146
|
readonly status?: number;
|
|
70
147
|
readonly searchId?: string;
|
|
148
|
+
/** Wait the server asked for through `Retry-After`, when it sent one. */
|
|
149
|
+
readonly retryAfterMs?: number;
|
|
150
|
+
/** Requests sent before giving up, including the first. */
|
|
151
|
+
readonly attempts: number;
|
|
71
152
|
constructor(message: string, options?: {
|
|
72
153
|
status?: number;
|
|
73
154
|
searchId?: string;
|
|
155
|
+
retryAfterMs?: number;
|
|
156
|
+
attempts?: number;
|
|
74
157
|
cause?: unknown;
|
|
75
158
|
});
|
|
76
159
|
}
|
|
@@ -79,8 +162,24 @@ export declare class QueritClient {
|
|
|
79
162
|
private readonly fetchImpl;
|
|
80
163
|
private readonly baseUrl;
|
|
81
164
|
private readonly timeoutMs;
|
|
165
|
+
private readonly retry;
|
|
82
166
|
constructor(options: QueritClientOptions);
|
|
83
167
|
search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse>;
|
|
84
168
|
contents(request: QueritContentsRequest, signal?: AbortSignal): Promise<QueritContentsResponse>;
|
|
169
|
+
/**
|
|
170
|
+
* Posts the request, retrying the statuses Querit calls transient with bounded
|
|
171
|
+
* exponential backoff and jitter. One deadline covers every attempt and wait.
|
|
172
|
+
*/
|
|
85
173
|
private postJson;
|
|
174
|
+
private attempt;
|
|
175
|
+
/**
|
|
176
|
+
* Marks an API failure with its status and Retry-After so postJson can decide whether to
|
|
177
|
+
* retry, and puts search_id in the message: support needs it to trace the request.
|
|
178
|
+
*/
|
|
179
|
+
private apiError;
|
|
86
180
|
}
|
|
181
|
+
/** Parses `Retry-After` in both forms the HTTP spec allows: delay-seconds or an HTTP-date. */
|
|
182
|
+
export declare function parseRetryAfter(value: string | null, now?: number): number | undefined;
|
|
183
|
+
/** Renders a cost at the API's six-decimal precision so small charges stay visible. */
|
|
184
|
+
export declare function formatCost(cost: QueritCost): string;
|
|
185
|
+
export {};
|
package/lib/client.js
CHANGED
|
@@ -2,26 +2,45 @@
|
|
|
2
2
|
* Credential-safe client for the public Querit API
|
|
3
3
|
* (`POST https://api.querit.ai/v1/search` and `/v1/contents`).
|
|
4
4
|
* Structure follows the client shipped by pi-querit (MIT):
|
|
5
|
-
* response-size limits, deduplication, URL normalization,
|
|
6
|
-
* redaction from every error surface
|
|
5
|
+
* response-size limits, deduplication, URL normalization, API-key
|
|
6
|
+
* redaction from every error surface, and retries for the statuses
|
|
7
|
+
* Querit documents as transient.
|
|
7
8
|
* @module dsh-querit/client
|
|
8
9
|
*/
|
|
9
|
-
import { sanitizeUntrustedText } from "./sanitize.js";
|
|
10
|
-
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
11
|
-
export const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
12
|
-
/** Attribution header sent on every request. Bump with the package version. */
|
|
13
|
-
const USER_AGENT = "dsh-querit/1.1.2";
|
|
10
|
+
import { sanitizeErrorMessage, sanitizeUntrustedText } from "./sanitize.js";
|
|
14
11
|
const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
15
12
|
const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
|
|
16
13
|
const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
|
|
14
|
+
/** Attribution header sent on every request. Bump with the package version. */
|
|
15
|
+
const USER_AGENT = "dsh-querit/2.0.0";
|
|
16
|
+
/** Querit documents these as the only statuses worth retrying; never 400, 401, 403, or 404. */
|
|
17
|
+
const RETRYABLE_STATUSES = new Set([429, 500, 503]);
|
|
18
|
+
/** Per-operation deadline, retries and backoff waits included. */
|
|
19
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
20
|
+
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
21
|
+
/** Largest `count` the API accepts. */
|
|
22
|
+
export const QUERIT_COUNT_LIMIT = 100;
|
|
23
|
+
/** Largest `contentMaxChars` the API accepts. */
|
|
24
|
+
export const QUERIT_CONTENT_MAX_CHARS_LIMIT = 1_000_000;
|
|
25
|
+
/** The values `filters.vertical`, `rank.preference`, and `filters.resourceTags.include[]` accept. */
|
|
26
|
+
export const VERTICAL_VALUES = ["code", "finance"];
|
|
27
|
+
export const RANK_VALUES = ["relevance", "freshness"];
|
|
28
|
+
export const RESOURCE_TAG_VALUES = ["qa", "github"];
|
|
29
|
+
const DEFAULT_RETRY = { maxRetries: 2, baseDelayMs: 500, maxDelayMs: 5_000 };
|
|
17
30
|
export class QueritApiError extends Error {
|
|
18
31
|
status;
|
|
19
32
|
searchId;
|
|
33
|
+
/** Wait the server asked for through `Retry-After`, when it sent one. */
|
|
34
|
+
retryAfterMs;
|
|
35
|
+
/** Requests sent before giving up, including the first. */
|
|
36
|
+
attempts;
|
|
20
37
|
constructor(message, options = {}) {
|
|
21
38
|
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
22
39
|
this.name = "QueritApiError";
|
|
23
40
|
this.status = options.status;
|
|
24
41
|
this.searchId = options.searchId;
|
|
42
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
43
|
+
this.attempts = options.attempts ?? 1;
|
|
25
44
|
}
|
|
26
45
|
}
|
|
27
46
|
export class QueritClient {
|
|
@@ -29,6 +48,7 @@ export class QueritClient {
|
|
|
29
48
|
fetchImpl;
|
|
30
49
|
baseUrl;
|
|
31
50
|
timeoutMs;
|
|
51
|
+
retry;
|
|
32
52
|
constructor(options) {
|
|
33
53
|
const apiKey = options.apiKey.trim();
|
|
34
54
|
if (!apiKey) {
|
|
@@ -38,6 +58,7 @@ export class QueritClient {
|
|
|
38
58
|
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
39
59
|
this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
|
|
40
60
|
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
61
|
+
this.retry = { ...DEFAULT_RETRY, ...options.retry };
|
|
41
62
|
}
|
|
42
63
|
async search(request, signal) {
|
|
43
64
|
const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
|
|
@@ -47,9 +68,46 @@ export class QueritClient {
|
|
|
47
68
|
const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
|
|
48
69
|
return normalizeContentsResponse(response.body, response.searchId);
|
|
49
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Posts the request, retrying the statuses Querit calls transient with bounded
|
|
73
|
+
* exponential backoff and jitter. One deadline covers every attempt and wait.
|
|
74
|
+
*/
|
|
50
75
|
async postJson(path, requestBody, responseLimit, callerSignal) {
|
|
51
|
-
const
|
|
52
|
-
const
|
|
76
|
+
const deadline = AbortSignal.timeout(this.timeoutMs);
|
|
77
|
+
const operation = {
|
|
78
|
+
deadline,
|
|
79
|
+
callerSignal,
|
|
80
|
+
signal: callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline,
|
|
81
|
+
};
|
|
82
|
+
for (let attempt = 0;; attempt++) {
|
|
83
|
+
let failure;
|
|
84
|
+
try {
|
|
85
|
+
return await this.attempt(path, requestBody, responseLimit, operation);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
failure = error instanceof QueritApiError
|
|
89
|
+
? error
|
|
90
|
+
: new QueritApiError(sanitizeErrorMessage(error), { cause: error });
|
|
91
|
+
}
|
|
92
|
+
// Cancellations and timeouts are reported as-is: they are not transient server states.
|
|
93
|
+
const retryable = RETRYABLE_STATUSES.has(failure.status ?? 0);
|
|
94
|
+
if (!retryable || attempt >= this.retry.maxRetries)
|
|
95
|
+
throw withAttempts(failure, attempt + 1);
|
|
96
|
+
const waitMs = retryDelayMs(failure.retryAfterMs, attempt, this.retry);
|
|
97
|
+
if (waitMs === undefined) {
|
|
98
|
+
// Honor an over-long Retry-After by not retrying sooner.
|
|
99
|
+
throw withAttempts(new QueritApiError(`${failure.message} Querit asked to retry after ${Math.ceil((failure.retryAfterMs ?? 0) / 1_000)}s, `
|
|
100
|
+
+ `longer than the ${this.retry.maxDelayMs} ms this client waits; not retried.`, { status: failure.status, searchId: failure.searchId, retryAfterMs: failure.retryAfterMs, cause: failure }), attempt + 1);
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
await sleep(waitMs, operation.signal);
|
|
104
|
+
}
|
|
105
|
+
catch (cancelled) {
|
|
106
|
+
throw interrupted(cancelled, operation, this.timeoutMs, sanitizeErrorMessage(cancelled));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async attempt(path, requestBody, responseLimit, operation) {
|
|
53
111
|
let response;
|
|
54
112
|
try {
|
|
55
113
|
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
@@ -57,21 +115,15 @@ export class QueritClient {
|
|
|
57
115
|
headers: {
|
|
58
116
|
Accept: "application/json",
|
|
59
117
|
Authorization: `Bearer ${this.apiKey}`,
|
|
60
|
-
"Content-Type": "application/json",
|
|
61
118
|
"User-Agent": USER_AGENT,
|
|
119
|
+
"Content-Type": "application/json",
|
|
62
120
|
},
|
|
63
121
|
body: JSON.stringify(requestBody),
|
|
64
|
-
signal,
|
|
122
|
+
signal: operation.signal,
|
|
65
123
|
});
|
|
66
124
|
}
|
|
67
125
|
catch (error) {
|
|
68
|
-
|
|
69
|
-
throw new QueritApiError("Querit request was cancelled.", { cause: error });
|
|
70
|
-
}
|
|
71
|
-
if (timeoutSignal.aborted) {
|
|
72
|
-
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
|
|
73
|
-
}
|
|
74
|
-
throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
|
|
126
|
+
throw interrupted(error, operation, this.timeoutMs, `Querit request failed: ${sanitizeErrorMessage(error)}`);
|
|
75
127
|
}
|
|
76
128
|
const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
|
|
77
129
|
let text;
|
|
@@ -79,19 +131,7 @@ export class QueritClient {
|
|
|
79
131
|
text = await readResponseText(response, bodyLimit);
|
|
80
132
|
}
|
|
81
133
|
catch (error) {
|
|
82
|
-
|
|
83
|
-
throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
|
|
84
|
-
}
|
|
85
|
-
if (timeoutSignal.aborted) {
|
|
86
|
-
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
|
|
87
|
-
status: response.status,
|
|
88
|
-
cause: error,
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
|
|
92
|
-
status: response.status,
|
|
93
|
-
cause: error,
|
|
94
|
-
});
|
|
134
|
+
throw interrupted(error, operation, this.timeoutMs, `Could not read the Querit response: ${sanitizeErrorMessage(error)}`, response.status);
|
|
95
135
|
}
|
|
96
136
|
const searchId = extractSearchId(text);
|
|
97
137
|
let payload;
|
|
@@ -101,7 +141,7 @@ export class QueritClient {
|
|
|
101
141
|
catch (error) {
|
|
102
142
|
const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
|
|
103
143
|
if (!response.ok) {
|
|
104
|
-
throw
|
|
144
|
+
throw this.apiError(`Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`, response, response.status, searchId, error);
|
|
105
145
|
}
|
|
106
146
|
throw new QueritApiError(`Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`, { status: response.status, searchId, cause: error });
|
|
107
147
|
}
|
|
@@ -114,12 +154,91 @@ export class QueritClient {
|
|
|
114
154
|
const apiErrorCode = optionalString(payload.error_code);
|
|
115
155
|
const apiErrorMessage = optionalString(payload.error_msg);
|
|
116
156
|
const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
|
|
157
|
+
// Querit asks clients to check error_code even on an HTTP 200.
|
|
117
158
|
if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
|
|
118
|
-
|
|
119
|
-
|
|
159
|
+
// error_code is the request's own verdict; the HTTP status stands in when the body has none.
|
|
160
|
+
const status = response.ok ? (numericErrorCode ?? response.status) : response.status;
|
|
161
|
+
throw this.apiError(redactSecret(apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`, this.apiKey), response, status, searchId);
|
|
120
162
|
}
|
|
121
163
|
return { body: payload, searchId };
|
|
122
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* Marks an API failure with its status and Retry-After so postJson can decide whether to
|
|
167
|
+
* retry, and puts search_id in the message: support needs it to trace the request.
|
|
168
|
+
*/
|
|
169
|
+
apiError(message, response, status, searchId, cause) {
|
|
170
|
+
const traced = searchId ? `${message} [search_id: ${searchId}]` : message;
|
|
171
|
+
return new QueritApiError(traced, {
|
|
172
|
+
status,
|
|
173
|
+
searchId,
|
|
174
|
+
retryAfterMs: parseRetryAfter(response.headers.get("retry-after")),
|
|
175
|
+
cause,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** Says how many requests a final failure took, when the first one was retried. */
|
|
180
|
+
function withAttempts(failure, attempts) {
|
|
181
|
+
if (attempts <= 1)
|
|
182
|
+
return failure;
|
|
183
|
+
return new QueritApiError(`Querit request failed after ${attempts} attempts: ${failure.message}`, {
|
|
184
|
+
status: failure.status,
|
|
185
|
+
searchId: failure.searchId,
|
|
186
|
+
retryAfterMs: failure.retryAfterMs,
|
|
187
|
+
attempts,
|
|
188
|
+
cause: failure,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Says when the caller cancelled or the deadline passed — neither is a transient
|
|
193
|
+
* server state, so neither is retried — and otherwise reports `failure`.
|
|
194
|
+
* `status` is the HTTP status, when a response had already arrived.
|
|
195
|
+
*/
|
|
196
|
+
function interrupted(error, operation, timeoutMs, failure, status) {
|
|
197
|
+
if (operation.callerSignal?.aborted) {
|
|
198
|
+
return new QueritApiError("Querit request was cancelled.", { status, cause: error });
|
|
199
|
+
}
|
|
200
|
+
if (operation.deadline.aborted) {
|
|
201
|
+
return new QueritApiError(`Querit request timed out after ${timeoutMs} ms.`, { status, cause: error });
|
|
202
|
+
}
|
|
203
|
+
return new QueritApiError(failure, { status, cause: error });
|
|
204
|
+
}
|
|
205
|
+
function retryDelayMs(retryAfterMs, attempt, retry) {
|
|
206
|
+
if (retryAfterMs !== undefined) {
|
|
207
|
+
return retryAfterMs <= retry.maxDelayMs ? retryAfterMs : undefined;
|
|
208
|
+
}
|
|
209
|
+
// Equal jitter: half the ceiling plus a random half, so waits back off without clustering.
|
|
210
|
+
const ceiling = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** attempt);
|
|
211
|
+
return Math.round(ceiling / 2 + Math.random() * (ceiling / 2));
|
|
212
|
+
}
|
|
213
|
+
/** Parses `Retry-After` in both forms the HTTP spec allows: delay-seconds or an HTTP-date. */
|
|
214
|
+
export function parseRetryAfter(value, now = Date.now()) {
|
|
215
|
+
if (value === null)
|
|
216
|
+
return undefined;
|
|
217
|
+
const trimmed = value.trim();
|
|
218
|
+
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
219
|
+
return Math.max(0, Math.ceil(Number(trimmed) * 1_000));
|
|
220
|
+
}
|
|
221
|
+
const date = Date.parse(trimmed);
|
|
222
|
+
if (!Number.isFinite(date))
|
|
223
|
+
return undefined;
|
|
224
|
+
return Math.max(0, date - now);
|
|
225
|
+
}
|
|
226
|
+
function sleep(ms, signal) {
|
|
227
|
+
return new Promise((resolve, reject) => {
|
|
228
|
+
if (signal.aborted) {
|
|
229
|
+
reject(signal.reason);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const onAbort = () => {
|
|
233
|
+
clearTimeout(timer);
|
|
234
|
+
reject(signal.reason);
|
|
235
|
+
};
|
|
236
|
+
const timer = setTimeout(() => {
|
|
237
|
+
signal.removeEventListener("abort", onAbort);
|
|
238
|
+
resolve();
|
|
239
|
+
}, ms);
|
|
240
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
241
|
+
});
|
|
123
242
|
}
|
|
124
243
|
async function readResponseText(response, maxBytes) {
|
|
125
244
|
const contentLength = response.headers.get("content-length");
|
|
@@ -165,6 +284,7 @@ function normalizeSearchResponse(payload, searchId, requestedQuery) {
|
|
|
165
284
|
if (!isRecord(rawItem))
|
|
166
285
|
continue;
|
|
167
286
|
const url = normalizeHttpUrl(rawItem.url);
|
|
287
|
+
// Every result field is optional; a result without a usable URL cannot be cited.
|
|
168
288
|
if (!url || deduplicated.has(url))
|
|
169
289
|
continue;
|
|
170
290
|
deduplicated.set(url, {
|
|
@@ -174,15 +294,19 @@ function normalizeSearchResponse(payload, searchId, requestedQuery) {
|
|
|
174
294
|
pageAge: optionalString(rawItem.page_age),
|
|
175
295
|
siteName: optionalString(rawItem.site_name),
|
|
176
296
|
siteIcon: optionalString(rawItem.site_icon),
|
|
177
|
-
sentences:
|
|
178
|
-
|
|
179
|
-
|
|
297
|
+
sentences: stringList(rawItem.sentence),
|
|
298
|
+
highlights: stringList(rawItem.highlights),
|
|
299
|
+
snippetMarkdown: optionalStringList(rawItem.snippet_markdown),
|
|
300
|
+
contentMarkdown: optionalString(rawItem.content_markdown),
|
|
180
301
|
});
|
|
181
302
|
}
|
|
182
303
|
const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
|
|
183
304
|
return {
|
|
305
|
+
errorCode: optionalString(payload.error_code),
|
|
306
|
+
errorMessage: optionalString(payload.error_msg),
|
|
184
307
|
searchId,
|
|
185
308
|
took: optionalString(payload.took),
|
|
309
|
+
cost: normalizeCost(payload.cost),
|
|
186
310
|
query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
|
|
187
311
|
results: [...deduplicated.values()],
|
|
188
312
|
};
|
|
@@ -198,10 +322,22 @@ function normalizeContentsResponse(payload, searchId) {
|
|
|
198
322
|
const url = normalizeHttpUrl(rawResult.url);
|
|
199
323
|
if (!url || deduplicated.has(url))
|
|
200
324
|
continue;
|
|
325
|
+
const rawMetadata = isRecord(rawResult.extrasMeta) ? rawResult.extrasMeta : undefined;
|
|
326
|
+
const metadata = rawMetadata
|
|
327
|
+
? {
|
|
328
|
+
title: optionalString(rawMetadata.title),
|
|
329
|
+
url: normalizeHttpUrl(rawMetadata.url),
|
|
330
|
+
publishTime: optionalString(rawMetadata.publishTime),
|
|
331
|
+
siteName: optionalString(rawMetadata.siteName),
|
|
332
|
+
siteIcon: normalizeHttpUrl(rawMetadata.siteIcon),
|
|
333
|
+
}
|
|
334
|
+
: undefined;
|
|
201
335
|
deduplicated.set(url, {
|
|
202
336
|
id: optionalString(rawResult.id),
|
|
203
337
|
url,
|
|
204
338
|
content: optionalString(rawResult.content) ?? "",
|
|
339
|
+
highlights: stringList(rawResult.highlights),
|
|
340
|
+
metadata,
|
|
205
341
|
});
|
|
206
342
|
}
|
|
207
343
|
const statuses = payload.statuses
|
|
@@ -211,12 +347,28 @@ function normalizeContentsResponse(payload, searchId) {
|
|
|
211
347
|
status: optionalString(status.status),
|
|
212
348
|
}));
|
|
213
349
|
return {
|
|
350
|
+
errorCode: optionalString(payload.error_code),
|
|
351
|
+
errorMessage: optionalString(payload.error_msg),
|
|
214
352
|
searchId,
|
|
353
|
+
searchTime: optionalNumber(payload.searchTime),
|
|
354
|
+
cost: normalizeCost(payload.cost),
|
|
215
355
|
results: [...deduplicated.values()],
|
|
216
356
|
statuses,
|
|
217
|
-
searchTime: optionalNumber(payload.searchTime),
|
|
218
357
|
};
|
|
219
358
|
}
|
|
359
|
+
/** Reads `cost`, keeping Querit's "absent means unavailable" distinct from a reported zero. */
|
|
360
|
+
function normalizeCost(value) {
|
|
361
|
+
if (!isRecord(value) || typeof value.currency !== "string")
|
|
362
|
+
return undefined;
|
|
363
|
+
const total = optionalNumber(value.total);
|
|
364
|
+
if (total === undefined || total < 0)
|
|
365
|
+
return undefined;
|
|
366
|
+
return { currency: value.currency, total };
|
|
367
|
+
}
|
|
368
|
+
/** Renders a cost at the API's six-decimal precision so small charges stay visible. */
|
|
369
|
+
export function formatCost(cost) {
|
|
370
|
+
return `${cost.currency} ${cost.total.toFixed(6)}`;
|
|
371
|
+
}
|
|
220
372
|
function extractSearchId(text) {
|
|
221
373
|
const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
|
|
222
374
|
const value = match?.[1] ?? match?.[2];
|
|
@@ -249,9 +401,14 @@ function optionalString(value) {
|
|
|
249
401
|
function optionalNumber(value) {
|
|
250
402
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
251
403
|
}
|
|
404
|
+
/** Reads an optional string array, dropping anything that is not a string. */
|
|
405
|
+
function stringList(value) {
|
|
406
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
407
|
+
}
|
|
408
|
+
/** Like stringList, but keeps "the API omitted this field" distinct from an empty list. */
|
|
409
|
+
function optionalStringList(value) {
|
|
410
|
+
return Array.isArray(value) ? stringList(value) : undefined;
|
|
411
|
+
}
|
|
252
412
|
function isRecord(value) {
|
|
253
413
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
254
414
|
}
|
|
255
|
-
function errorMessage(error) {
|
|
256
|
-
return sanitizeUntrustedText(error instanceof Error ? error.message : String(error));
|
|
257
|
-
}
|