pi-querit 1.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/src/client.ts ADDED
@@ -0,0 +1,385 @@
1
+ import { sanitizeTerminalText } from "./sanitize.js";
2
+
3
+ const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
4
+ const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
5
+ const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
6
+ const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
7
+
8
+ export const QUERIT_API_BASE_URL = "https://api.querit.ai";
9
+
10
+ export interface QueritSearchRequest {
11
+ query: string;
12
+ count: number;
13
+ chunksPerDoc?: number;
14
+ needContent?: boolean;
15
+ filters?: {
16
+ sites?: { include?: string[]; exclude?: string[] };
17
+ timeRange?: { date: string };
18
+ geo?: { countries: { include: string[] } };
19
+ languages?: { include: string[] };
20
+ };
21
+ }
22
+
23
+ export interface QueritContentsRequest {
24
+ urls: string[];
25
+ format: "text" | "markdown" | "html";
26
+ crawlTimeout: number;
27
+ extrasMeta: boolean;
28
+ }
29
+
30
+ export interface QueritSearchResult {
31
+ title: string;
32
+ url: string;
33
+ snippet: string;
34
+ pageAge?: string;
35
+ siteName?: string;
36
+ siteIcon?: string;
37
+ sentences: string[];
38
+ }
39
+
40
+ export interface QueritSearchResponse {
41
+ errorCode?: string;
42
+ errorMessage?: string;
43
+ searchId?: string;
44
+ took?: string;
45
+ query: string;
46
+ results: QueritSearchResult[];
47
+ }
48
+
49
+ export interface QueritContentMetadata {
50
+ title?: string;
51
+ url?: string;
52
+ publishTime?: string;
53
+ siteName?: string;
54
+ siteIcon?: string;
55
+ }
56
+
57
+ export interface QueritContentResult {
58
+ id?: string;
59
+ url: string;
60
+ content: string;
61
+ metadata?: QueritContentMetadata;
62
+ }
63
+
64
+ export interface QueritContentStatus {
65
+ id?: string;
66
+ status?: string;
67
+ }
68
+
69
+ export interface QueritContentsResponse {
70
+ errorCode?: string;
71
+ errorMessage?: string;
72
+ searchId?: string;
73
+ results: QueritContentResult[];
74
+ statuses: QueritContentStatus[];
75
+ searchTime?: number;
76
+ }
77
+
78
+ export interface QueritClientOptions {
79
+ apiKey: string;
80
+ fetchImpl?: typeof fetch;
81
+ baseUrl?: string;
82
+ timeoutMs?: number;
83
+ }
84
+
85
+ interface ParsedResponse {
86
+ body: Record<string, unknown>;
87
+ searchId?: string;
88
+ }
89
+
90
+ export class QueritApiError extends Error {
91
+ readonly status?: number;
92
+ readonly searchId?: string;
93
+
94
+ constructor(message: string, options: { status?: number; searchId?: string; cause?: unknown } = {}) {
95
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
96
+ this.name = "QueritApiError";
97
+ this.status = options.status;
98
+ this.searchId = options.searchId;
99
+ }
100
+ }
101
+
102
+ export class QueritClient {
103
+ private readonly apiKey: string;
104
+ private readonly fetchImpl: typeof fetch;
105
+ private readonly baseUrl: string;
106
+ private readonly timeoutMs: number;
107
+
108
+ constructor(options: QueritClientOptions) {
109
+ const apiKey = options.apiKey.trim();
110
+ if (!apiKey) {
111
+ throw new QueritApiError("A Querit API key is required.");
112
+ }
113
+
114
+ this.apiKey = apiKey;
115
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
116
+ this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
117
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
118
+ }
119
+
120
+ async search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse> {
121
+ const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
122
+ return normalizeSearchResponse(response.body, response.searchId, request.query);
123
+ }
124
+
125
+ async contents(request: QueritContentsRequest, signal?: AbortSignal): Promise<QueritContentsResponse> {
126
+ const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
127
+ return normalizeContentsResponse(response.body, response.searchId);
128
+ }
129
+
130
+ private async postJson(
131
+ path: string,
132
+ requestBody: QueritSearchRequest | QueritContentsRequest,
133
+ responseLimit: number,
134
+ callerSignal?: AbortSignal,
135
+ ): Promise<ParsedResponse> {
136
+ const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
137
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
138
+ let response: Response;
139
+
140
+ try {
141
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
142
+ method: "POST",
143
+ headers: {
144
+ Accept: "application/json",
145
+ Authorization: `Bearer ${this.apiKey}`,
146
+ "Content-Type": "application/json",
147
+ },
148
+ body: JSON.stringify(requestBody),
149
+ signal,
150
+ });
151
+ } catch (error) {
152
+ if (callerSignal?.aborted) {
153
+ throw new QueritApiError("Querit request was cancelled.", { cause: error });
154
+ }
155
+ if (timeoutSignal.aborted) {
156
+ throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
157
+ }
158
+ throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
159
+ }
160
+
161
+ const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
162
+ let text: string;
163
+ try {
164
+ text = await readResponseText(response, bodyLimit);
165
+ } catch (error) {
166
+ if (callerSignal?.aborted) {
167
+ throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
168
+ }
169
+ if (timeoutSignal.aborted) {
170
+ throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
171
+ status: response.status,
172
+ cause: error,
173
+ });
174
+ }
175
+ throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
176
+ status: response.status,
177
+ cause: error,
178
+ });
179
+ }
180
+
181
+ const searchId = extractSearchId(text);
182
+ let payload: unknown;
183
+ try {
184
+ payload = JSON.parse(text);
185
+ } catch (error) {
186
+ const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
187
+ if (!response.ok) {
188
+ throw new QueritApiError(
189
+ `Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`,
190
+ { status: response.status, searchId, cause: error },
191
+ );
192
+ }
193
+ throw new QueritApiError(
194
+ `Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`,
195
+ { status: response.status, searchId, cause: error },
196
+ );
197
+ }
198
+
199
+ if (!isRecord(payload)) {
200
+ throw new QueritApiError("Querit returned an invalid response object.", {
201
+ status: response.status,
202
+ searchId,
203
+ });
204
+ }
205
+
206
+ const apiErrorCode = optionalString(payload.error_code);
207
+ const apiErrorMessage = optionalString(payload.error_msg);
208
+ const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
209
+ if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
210
+ const message = redactSecret(
211
+ apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`,
212
+ this.apiKey,
213
+ );
214
+ throw new QueritApiError(message, { status: response.status, searchId });
215
+ }
216
+
217
+ return { body: payload, searchId };
218
+ }
219
+ }
220
+
221
+ async function readResponseText(response: Response, maxBytes: number): Promise<string> {
222
+ const contentLength = response.headers.get("content-length");
223
+ if (contentLength !== null) {
224
+ const declaredLength = Number(contentLength);
225
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
226
+ throw new Error(`response exceeds the ${maxBytes}-byte limit`);
227
+ }
228
+ }
229
+
230
+ if (!response.body) {
231
+ return "";
232
+ }
233
+
234
+ const reader = response.body.getReader();
235
+ const decoder = new TextDecoder();
236
+ const chunks: string[] = [];
237
+ let totalBytes = 0;
238
+
239
+ try {
240
+ while (true) {
241
+ const { done, value } = await reader.read();
242
+ if (done) break;
243
+ totalBytes += value.byteLength;
244
+ if (totalBytes > maxBytes) {
245
+ await reader.cancel("response size limit exceeded");
246
+ throw new Error(`response exceeds the ${maxBytes}-byte limit`);
247
+ }
248
+ chunks.push(decoder.decode(value, { stream: true }));
249
+ }
250
+ chunks.push(decoder.decode());
251
+ return chunks.join("");
252
+ } finally {
253
+ reader.releaseLock();
254
+ }
255
+ }
256
+
257
+ function normalizeSearchResponse(
258
+ payload: Record<string, unknown>,
259
+ searchId: string | undefined,
260
+ requestedQuery: string,
261
+ ): QueritSearchResponse {
262
+ const resultsContainer = payload.results;
263
+ if (!isRecord(resultsContainer) || !Array.isArray(resultsContainer.result)) {
264
+ throw new QueritApiError("Querit search response is missing results.result.", { searchId });
265
+ }
266
+
267
+ const deduplicated = new Map<string, QueritSearchResult>();
268
+ for (const rawItem of resultsContainer.result) {
269
+ if (!isRecord(rawItem)) continue;
270
+ const url = normalizeHttpUrl(rawItem.url);
271
+ if (!url || deduplicated.has(url)) continue;
272
+
273
+ deduplicated.set(url, {
274
+ title: optionalString(rawItem.title) ?? url,
275
+ url,
276
+ snippet: optionalString(rawItem.snippet) ?? "",
277
+ pageAge: optionalString(rawItem.page_age),
278
+ siteName: optionalString(rawItem.site_name),
279
+ siteIcon: optionalString(rawItem.site_icon),
280
+ sentences: Array.isArray(rawItem.sentence)
281
+ ? rawItem.sentence.filter((value): value is string => typeof value === "string")
282
+ : [],
283
+ });
284
+ }
285
+
286
+ const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
287
+ return {
288
+ errorCode: optionalString(payload.error_code),
289
+ errorMessage: optionalString(payload.error_msg),
290
+ searchId,
291
+ took: optionalString(payload.took),
292
+ query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
293
+ results: [...deduplicated.values()],
294
+ };
295
+ }
296
+
297
+ function normalizeContentsResponse(
298
+ payload: Record<string, unknown>,
299
+ searchId: string | undefined,
300
+ ): QueritContentsResponse {
301
+ if (!Array.isArray(payload.results) || !Array.isArray(payload.statuses)) {
302
+ throw new QueritApiError("Querit contents response is missing results or statuses.", { searchId });
303
+ }
304
+
305
+ const deduplicated = new Map<string, QueritContentResult>();
306
+ for (const rawResult of payload.results) {
307
+ if (!isRecord(rawResult)) continue;
308
+ const url = normalizeHttpUrl(rawResult.url);
309
+ if (!url || deduplicated.has(url)) continue;
310
+
311
+ const rawMetadata = isRecord(rawResult.extrasMeta) ? rawResult.extrasMeta : undefined;
312
+ const metadata = rawMetadata
313
+ ? {
314
+ title: optionalString(rawMetadata.title),
315
+ url: normalizeHttpUrl(rawMetadata.url),
316
+ publishTime: optionalString(rawMetadata.publishTime),
317
+ siteName: optionalString(rawMetadata.siteName),
318
+ siteIcon: normalizeHttpUrl(rawMetadata.siteIcon),
319
+ }
320
+ : undefined;
321
+
322
+ deduplicated.set(url, {
323
+ id: optionalString(rawResult.id),
324
+ url,
325
+ content: optionalString(rawResult.content) ?? "",
326
+ metadata,
327
+ });
328
+ }
329
+
330
+ const statuses = payload.statuses
331
+ .filter(isRecord)
332
+ .map((status) => ({
333
+ id: optionalString(status.id),
334
+ status: optionalString(status.status),
335
+ }));
336
+
337
+ return {
338
+ errorCode: optionalString(payload.error_code),
339
+ errorMessage: optionalString(payload.error_msg),
340
+ searchId,
341
+ results: [...deduplicated.values()],
342
+ statuses,
343
+ searchTime: optionalNumber(payload.searchTime),
344
+ };
345
+ }
346
+
347
+ function extractSearchId(text: string): string | undefined {
348
+ const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
349
+ const value = match?.[1] ?? match?.[2];
350
+ return value && /^-?\d+$/.test(value) ? value : undefined;
351
+ }
352
+
353
+ function normalizeHttpUrl(value: unknown): string | undefined {
354
+ if (typeof value !== "string") return undefined;
355
+ try {
356
+ const url = new URL(value);
357
+ if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
358
+ return url.toString();
359
+ } catch {
360
+ return undefined;
361
+ }
362
+ }
363
+
364
+ function redactSecret(text: string, secret: string): string {
365
+ const redacted = secret ? text.split(secret).join("[REDACTED]") : text;
366
+ return sanitizeTerminalText(redacted);
367
+ }
368
+
369
+ function optionalString(value: unknown): string | undefined {
370
+ if (typeof value === "string") return value;
371
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
372
+ return undefined;
373
+ }
374
+
375
+ function optionalNumber(value: unknown): number | undefined {
376
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
377
+ }
378
+
379
+ function isRecord(value: unknown): value is Record<string, unknown> {
380
+ return typeof value === "object" && value !== null && !Array.isArray(value);
381
+ }
382
+
383
+ function errorMessage(error: unknown): string {
384
+ return sanitizeTerminalText(error instanceof Error ? error.message : String(error));
385
+ }
package/src/config.ts ADDED
@@ -0,0 +1,254 @@
1
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
4
+
5
+ export const QUERIT_CONFIG_FILE = "querit-search.json";
6
+
7
+ export type SearchWorkflow = "raw" | "summary";
8
+
9
+ export const THINKING_LEVEL_VALUES = [
10
+ "off",
11
+ "minimal",
12
+ "low",
13
+ "medium",
14
+ "high",
15
+ "xhigh",
16
+ "max",
17
+ ] as const;
18
+
19
+ export type QueritThinkingLevel = (typeof THINKING_LEVEL_VALUES)[number];
20
+
21
+ export const COUNTRY_VALUES = [
22
+ "argentina",
23
+ "australia",
24
+ "brazil",
25
+ "canada",
26
+ "colombia",
27
+ "france",
28
+ "germany",
29
+ "india",
30
+ "indonesia",
31
+ "japan",
32
+ "mexico",
33
+ "nigeria",
34
+ "philippines",
35
+ "south korea",
36
+ "spain",
37
+ "united kingdom",
38
+ "united states",
39
+ ] as const;
40
+
41
+ export const LANGUAGE_VALUES = [
42
+ "english",
43
+ "japanese",
44
+ "korean",
45
+ "german",
46
+ "french",
47
+ "spanish",
48
+ "portuguese",
49
+ ] as const;
50
+
51
+ export type QueritCountry = (typeof COUNTRY_VALUES)[number];
52
+ export type QueritLanguage = (typeof LANGUAGE_VALUES)[number];
53
+
54
+ export interface QueritSearchDefaults {
55
+ count?: number;
56
+ includeDomains?: string[];
57
+ excludeDomains?: string[];
58
+ timeRange?: string;
59
+ countries?: QueritCountry[];
60
+ languages?: QueritLanguage[];
61
+ includeContent?: boolean;
62
+ chunksPerDoc?: number;
63
+ }
64
+
65
+ export interface QueritConfig {
66
+ apiKey: string;
67
+ defaultWorkflow?: SearchWorkflow;
68
+ summaryModel?: string;
69
+ summaryThinkingLevel?: QueritThinkingLevel;
70
+ search?: QueritSearchDefaults;
71
+ }
72
+
73
+ export interface QueritConfigSettings {
74
+ defaultWorkflow?: SearchWorkflow;
75
+ summaryModel?: string;
76
+ summaryThinkingLevel?: QueritThinkingLevel;
77
+ search?: QueritSearchDefaults;
78
+ }
79
+
80
+ export interface ApiKeyResolutionOptions {
81
+ configPath?: string;
82
+ env?: NodeJS.ProcessEnv;
83
+ }
84
+
85
+ export function getQueritConfigPath(agentDir = getAgentDir()): string {
86
+ return join(agentDir, QUERIT_CONFIG_FILE);
87
+ }
88
+
89
+ export async function loadQueritConfig(configPath = getQueritConfigPath()): Promise<QueritConfig | undefined> {
90
+ let text: string;
91
+ try {
92
+ text = await readFile(configPath, "utf8");
93
+ } catch (error) {
94
+ if (isNodeError(error) && error.code === "ENOENT") return undefined;
95
+ throw new Error(`Could not read Querit configuration at ${configPath}: ${errorMessage(error)}`, {
96
+ cause: error,
97
+ });
98
+ }
99
+
100
+ let parsed: unknown;
101
+ try {
102
+ parsed = JSON.parse(text);
103
+ } catch (error) {
104
+ throw new Error(`Querit configuration at ${configPath} is not valid JSON.`, { cause: error });
105
+ }
106
+
107
+ if (!isRecord(parsed) || typeof parsed.apiKey !== "string" || !parsed.apiKey.trim()) {
108
+ throw new Error(`Querit configuration at ${configPath} must contain a non-empty "apiKey" string.`);
109
+ }
110
+
111
+ const defaultWorkflow = parsed.defaultWorkflow === "raw" || parsed.defaultWorkflow === "summary"
112
+ ? parsed.defaultWorkflow
113
+ : undefined;
114
+ const summaryModel = typeof parsed.summaryModel === "string" && isModelReference(parsed.summaryModel)
115
+ ? parsed.summaryModel.trim()
116
+ : undefined;
117
+ const summaryThinkingLevel = isThinkingLevel(parsed.summaryThinkingLevel) ? parsed.summaryThinkingLevel : undefined;
118
+ const search = parseSearchDefaults(parsed.search);
119
+
120
+ return {
121
+ apiKey: parsed.apiKey.trim(),
122
+ ...(defaultWorkflow === undefined ? {} : { defaultWorkflow }),
123
+ ...(summaryModel === undefined ? {} : { summaryModel }),
124
+ ...(summaryThinkingLevel === undefined ? {} : { summaryThinkingLevel }),
125
+ ...(search === undefined ? {} : { search }),
126
+ };
127
+ }
128
+
129
+ export async function resolveQueritApiKey(options: ApiKeyResolutionOptions = {}): Promise<string | undefined> {
130
+ const config = await loadQueritConfig(options.configPath ?? getQueritConfigPath());
131
+ if (config?.apiKey) return config.apiKey;
132
+
133
+ const environmentKey = (options.env ?? process.env).QUERIT_API_KEY?.trim();
134
+ return environmentKey || undefined;
135
+ }
136
+
137
+ export async function saveQueritConfig(
138
+ apiKey: string,
139
+ configPath = getQueritConfigPath(),
140
+ settings: QueritConfigSettings = {},
141
+ ): Promise<void> {
142
+ const normalizedKey = apiKey.trim();
143
+ if (!normalizedKey) throw new Error("Cannot save an empty Querit API key.");
144
+ if (settings.defaultWorkflow !== undefined && settings.defaultWorkflow !== "raw" && settings.defaultWorkflow !== "summary") {
145
+ throw new Error("Cannot save an invalid Querit default workflow.");
146
+ }
147
+ const summaryModel = settings.summaryModel?.trim();
148
+ if (summaryModel !== undefined && !isModelReference(summaryModel)) {
149
+ throw new Error("Cannot save an invalid Querit summary model reference.");
150
+ }
151
+ const summaryThinkingLevel = settings.summaryThinkingLevel;
152
+ if (summaryThinkingLevel !== undefined && !isThinkingLevel(summaryThinkingLevel)) {
153
+ throw new Error("Cannot save an invalid Querit summary thinking level.");
154
+ }
155
+ const search = settings.search === undefined ? undefined : parseSearchDefaults(settings.search);
156
+ const serializedConfig: QueritConfig = {
157
+ apiKey: normalizedKey,
158
+ ...(settings.defaultWorkflow === undefined ? {} : { defaultWorkflow: settings.defaultWorkflow }),
159
+ ...(summaryModel === undefined ? {} : { summaryModel }),
160
+ ...(summaryThinkingLevel === undefined ? {} : { summaryThinkingLevel }),
161
+ ...(search === undefined ? {} : { search }),
162
+ };
163
+
164
+ await mkdir(dirname(configPath), { recursive: true });
165
+ await withFileMutationQueue(configPath, async () => {
166
+ const temporaryPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
167
+ try {
168
+ await writeFile(temporaryPath, `${JSON.stringify(serializedConfig, null, 2)}\n`, {
169
+ encoding: "utf8",
170
+ mode: 0o600,
171
+ });
172
+ await rename(temporaryPath, configPath);
173
+ if (process.platform !== "win32") {
174
+ await chmod(configPath, 0o600);
175
+ }
176
+ } finally {
177
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
178
+ }
179
+ });
180
+ }
181
+
182
+ function isModelReference(value: string): boolean {
183
+ const normalized = value.trim();
184
+ const slash = normalized.indexOf("/");
185
+ return slash > 0 && slash < normalized.length - 1 && !/\s/u.test(normalized);
186
+ }
187
+
188
+ function isThinkingLevel(value: unknown): value is QueritThinkingLevel {
189
+ return typeof value === "string" && (THINKING_LEVEL_VALUES as readonly string[]).includes(value);
190
+ }
191
+
192
+ export function parseSearchDefaults(value: unknown): QueritSearchDefaults | undefined {
193
+ if (!isRecord(value)) return undefined;
194
+ const defaults: QueritSearchDefaults = {};
195
+
196
+ if (isIntegerInRange(value.count, 1, 20)) defaults.count = value.count;
197
+ if (isIntegerInRange(value.chunksPerDoc, 1, 3)) defaults.chunksPerDoc = value.chunksPerDoc;
198
+ if (typeof value.includeContent === "boolean") defaults.includeContent = value.includeContent;
199
+ if (typeof value.timeRange === "string" && value.timeRange.trim()) {
200
+ defaults.timeRange = value.timeRange.trim().slice(0, 64);
201
+ }
202
+
203
+ const includeDomains = parseDomainList(value.includeDomains);
204
+ if (includeDomains !== undefined) defaults.includeDomains = includeDomains;
205
+ const excludeDomains = parseDomainList(value.excludeDomains);
206
+ if (excludeDomains !== undefined) defaults.excludeDomains = excludeDomains;
207
+ const countries = parseEnumList(value.countries, COUNTRY_VALUES);
208
+ if (countries !== undefined) defaults.countries = countries;
209
+ const languages = parseEnumList(value.languages, LANGUAGE_VALUES);
210
+ if (languages !== undefined) defaults.languages = languages;
211
+
212
+ return Object.keys(defaults).length > 0 ? defaults : undefined;
213
+ }
214
+
215
+ function isIntegerInRange(value: unknown, min: number, max: number): value is number {
216
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
217
+ }
218
+
219
+ function parseDomainList(value: unknown): string[] | undefined {
220
+ if (!Array.isArray(value)) return undefined;
221
+ const domains = new Set<string>();
222
+ for (const entry of value) {
223
+ if (typeof entry !== "string") continue;
224
+ const domain = entry.trim().toLowerCase();
225
+ if (!domain || domain.length > 253 || /\s/u.test(domain) || !domain.includes(".")) continue;
226
+ domains.add(domain);
227
+ if (domains.size >= 20) break;
228
+ }
229
+ return domains.size > 0 ? [...domains] : undefined;
230
+ }
231
+
232
+ function parseEnumList<T extends string>(value: unknown, allowed: readonly T[]): T[] | undefined {
233
+ if (!Array.isArray(value)) return undefined;
234
+ const allowedSet = new Set<string>(allowed);
235
+ const matched = new Set<T>();
236
+ for (const entry of value) {
237
+ if (typeof entry !== "string") continue;
238
+ const normalized = entry.trim().toLowerCase();
239
+ if (allowedSet.has(normalized)) matched.add(normalized as T);
240
+ }
241
+ return matched.size > 0 ? [...matched] : undefined;
242
+ }
243
+
244
+ function isRecord(value: unknown): value is Record<string, unknown> {
245
+ return typeof value === "object" && value !== null && !Array.isArray(value);
246
+ }
247
+
248
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
249
+ return error instanceof Error && "code" in error;
250
+ }
251
+
252
+ function errorMessage(error: unknown): string {
253
+ return error instanceof Error ? error.message : String(error);
254
+ }