pi-lean-host 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,801 @@
1
+ /** Expand shorthand Accept names: json → application/json, xml → application/xml; else pass through. */
2
+ function expandAccept(accept: string): string {
3
+ return accept === "json"
4
+ ? "application/json"
5
+ : accept === "xml"
6
+ ? "application/xml"
7
+ : accept;
8
+ }
9
+
10
+ /**
11
+ * Built-in executor helpers — the three-helper v1 set.
12
+ *
13
+ * `restGet` — single-request fetch with path templating, query assembly,
14
+ * Accept negotiation, and auth dispatch.
15
+ * `paginate` — paginated fetch supporting offset-limit, nextLink, cursor,
16
+ * and page styles; optional `gatherAll` with ceiling.
17
+ * `parseResponse` — XML→JSON conversion with charset correction.
18
+ *
19
+ * Every helper returns a structured `HelperResult` or throws `HelperError`.
20
+ */
21
+
22
+ import { XMLParser } from "fast-xml-parser";
23
+ import { ssrfGuard } from "./ssrf-guard.js";
24
+ import { fetchUrl, type FetchOptions } from "./transport.js";
25
+ import { fillPathTemplate, joinUrl } from "./path-template.js";
26
+ import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
27
+ import type {
28
+ ApiGuide,
29
+ DateParamFormat,
30
+ Operation,
31
+ ResponseShape,
32
+ } from "./api-guide-types.js";
33
+
34
+ // ═══════════════════════════════════════════════════════════════════
35
+ // Error type
36
+ // ═══════════════════════════════════════════════════════════════════
37
+
38
+ export class HelperError extends Error {
39
+ override name = "HelperError";
40
+
41
+ constructor(
42
+ /** Dotted field path, e.g. "params.date" or "auth.kind". */
43
+ public readonly field: string,
44
+ message: string,
45
+ /** Human-readable description of what was expected. */
46
+ public readonly expected?: string,
47
+ /** What was actually found. */
48
+ public readonly found?: string,
49
+ /** Suggested fix, if the helper can offer one. */
50
+ public readonly fix?: string,
51
+ /** The full resolved URL that caused the error, if known. */
52
+ public readonly url?: string,
53
+ ) {
54
+ super(message);
55
+ }
56
+ }
57
+
58
+ // ═══════════════════════════════════════════════════════════════════
59
+ // Result types
60
+ // ═══════════════════════════════════════════════════════════════════
61
+
62
+ export interface RestGetResult {
63
+ /** Full parsed response body (JSON object/array or XML-converted). */
64
+ data: unknown;
65
+ /** Response headers. */
66
+ headers: Record<string, string>;
67
+ /** The full resolved URL that was fetched. */
68
+ url: string;
69
+ /** Effective query params actually sent (post-defaults, post-validation). */
70
+ params: Record<string, string>;
71
+ /** Set when a post-response transform throws (raw `data` preserved). */
72
+ transformWarning?: string;
73
+ }
74
+
75
+ export interface PaginateResult {
76
+ /** Accumulated items across all fetched pages. */
77
+ items: unknown[];
78
+ /** Total count of items fetched (may be less than server total due to ceiling). */
79
+ totalFetched: number;
80
+ /**
81
+ * Raw (untransformed) items whose post-response transform threw. Absent
82
+ * when no item fails — no item is ever dropped. Total raw items processed
83
+ * = `items.length + failedItems.length`.
84
+ */
85
+ failedItems?: unknown[];
86
+ /** Server-reported total count from the first page (when the guide
87
+ * declares `totalCountPath` and it resolves to a number/numeric string). */
88
+ serverTotal?: number;
89
+ /** True when `gatherAllMax` ceiling halted pagination. */
90
+ ceilingHit: boolean;
91
+ /** Every page URL fetched (bounded by page count). */
92
+ urls: string[];
93
+ /** Number of pages fetched (= urls.length). */
94
+ pages: number;
95
+ /** Effective query params actually sent (post-defaults, post-validation). */
96
+ params: Record<string, string>;
97
+ }
98
+
99
+ // ═══════════════════════════════════════════════════════════════════
100
+ // Internal helpers
101
+ // ═══════════════════════════════════════════════════════════════════
102
+
103
+ /**
104
+ * Strict path templating for execution — a missing `{token}` throws.
105
+ * (The shared `fillPathTemplate` keeps missing tokens literal for probing.)
106
+ */
107
+ function fillPathStrict(path: string, params: Record<string, unknown>): string {
108
+ return fillPathTemplate(path, params, (token) => {
109
+ throw new HelperError(
110
+ `params.${token}`,
111
+ `Missing path parameter: ${token}`,
112
+ `a value for "{${token}}" in path "${path}"`,
113
+ "missing",
114
+ );
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Build query-string params: apply defaults for query params,
120
+ * validate required params, and exclude path params.
121
+ */
122
+ function buildQueryParams(
123
+ operation: Operation,
124
+ params: Record<string, unknown>,
125
+ ): Record<string, string> {
126
+ const query: Record<string, string> = {};
127
+ const pathParamSet = new Set(operation.pathParams);
128
+
129
+ for (const [key, spec] of Object.entries(operation.params)) {
130
+ if (pathParamSet.has(key)) continue; // already in path
131
+
132
+ let val = params[key];
133
+
134
+ // Apply default if not provided.
135
+ if (val === undefined && spec.default !== undefined) {
136
+ val = spec.default;
137
+ }
138
+
139
+ // Validate required.
140
+ if (val === undefined && spec.required) {
141
+ throw new HelperError(
142
+ `params.${key}`,
143
+ `Missing required query parameter: ${key}`,
144
+ `a value for required param "${key}"`,
145
+ "missing",
146
+ );
147
+ }
148
+
149
+ if (val !== undefined) {
150
+ // Date param normalization — convert to target format before serialization.
151
+ if (operation.dateParams && key in operation.dateParams) {
152
+ val = normalizeDateParam(val, operation.dateParams[key]!);
153
+ }
154
+ // Nested objects/arrays serialize as JSON so structured query
155
+ // params (e.g. BOE's ES query_string DSL) reach the wire as
156
+ // JSON, not `[object Object]`. Scalars stay as String(val).
157
+ query[key] =
158
+ typeof val === "object" && val !== null
159
+ ? JSON.stringify(val)
160
+ : String(val);
161
+ }
162
+ }
163
+
164
+ // `passthrough`: forward caller-supplied params not declared in the
165
+ // recipe's `params` map onto the query string as-is. For APIs with an
166
+ // open param surface (Infogami /query.json flat form, CKAN, OAI-PMH)
167
+ // where the caller supplies type-specific keys at query time. Default
168
+ // is a closed contract: extras are dropped so the agent gets a
169
+ // predictable request, not a silent miss on an undeclared key.
170
+ if (operation.passthrough) {
171
+ for (const [key, val] of Object.entries(params)) {
172
+ if (pathParamSet.has(key)) continue; // path params stay in path
173
+ if (key in operation.params) continue; // already handled above
174
+ if (val === undefined) continue;
175
+ let v: unknown = val;
176
+ if (operation.dateParams && key in operation.dateParams) {
177
+ v = normalizeDateParam(v, operation.dateParams[key]!);
178
+ }
179
+ query[key] =
180
+ typeof v === "object" && v !== null ? JSON.stringify(v) : String(v);
181
+ }
182
+ }
183
+
184
+ return query;
185
+ }
186
+
187
+ /**
188
+ * Normalize a date string to a target format.
189
+ * Accepts ISO 8601 (YYYY-MM-DD or with time tail), already-target format,
190
+ * or non-date strings (passed through as-is).
191
+ */
192
+ export function normalizeDateParam(
193
+ val: unknown,
194
+ format: DateParamFormat,
195
+ ): string {
196
+ const s = typeof val === "string" ? val : String(val ?? "");
197
+ const m = s.match(/^(\d{4})-?(\d{1,2})-?(\d{1,2})(.*)$/);
198
+ if (!m) return s;
199
+ const [, y, mo, d] = m;
200
+ const mm = mo!.padStart(2, "0");
201
+ const dd = d!.padStart(2, "0");
202
+ if (format === "yyyymmdd") return `${y}${mm}${dd}`;
203
+ if (format === "yyyy-mm-dd") return `${y}-${mm}-${dd}`;
204
+ return format === "iso8601" ? `${y}-${mm}-${dd}${m[4] ?? ""}` : s;
205
+ }
206
+
207
+ /**
208
+ * Resolve a simple dot-delimited JSON path against an object.
209
+ * Supports `data.items`, `resultados[0].campo`, `$.items` prefix.
210
+ */
211
+ export function resolveJsonPath(obj: unknown, path: string): unknown {
212
+ // Normalise: strip leading $ or $., convert bracket notation.
213
+ const normalised = path
214
+ .replace(/^\$\.?/, "")
215
+ .replace(/\[['"](.*?)['"]\]/g, ".$1")
216
+ .replace(/\[(\d+)\]/g, ".$1");
217
+ const parts = normalised.split(".").filter((p) => p.length > 0);
218
+ if (parts.length === 0) return obj;
219
+
220
+ let current: unknown = obj;
221
+ for (const part of parts) {
222
+ if (current === null || typeof current !== "object") return undefined;
223
+ if (Array.isArray(current)) {
224
+ const idx = parseInt(part, 10);
225
+ if (isNaN(idx)) return undefined;
226
+ current = current[idx];
227
+ } else {
228
+ current = (current as Record<string, unknown>)[part];
229
+ }
230
+ }
231
+ return current;
232
+ }
233
+
234
+ // ═══════════════════════════════════════════════════════════════════
235
+ // parseResponse
236
+ // ═══════════════════════════════════════════════════════════════════
237
+
238
+ const xmlParser = new XMLParser({
239
+ ignoreAttributes: false,
240
+ attributeNamePrefix: "@_",
241
+ textNodeName: "#text",
242
+ parseAttributeValue: true,
243
+ trimValues: true,
244
+ // A2: strip element-name prefixes (message:GenericData → GenericData) so
245
+ // itemsPath/totalCountPath use stable local names across XML providers.
246
+ removeNSPrefix: true,
247
+ });
248
+
249
+ /**
250
+ * Parse a response body according to the guide's response shape.
251
+ *
252
+ * The body is already decoded to a JavaScript string by the transport
253
+ * layer, which uses the response's Content-Type charset with the recipe's
254
+ * `shape.charset` as a fallback when the header omits one (an explicit
255
+ * header charset wins). `parseResponse` itself does no decoding — the
256
+ * `charset` field is consumed by the transport, not here.
257
+ *
258
+ * @param body The response body string (correctly decoded).
259
+ * @param shape The response shape (format dictates XML vs JSON parsing).
260
+ * @returns Parsed JSON value or XML-converted object.
261
+ */
262
+ export function parseResponse(body: string, shape: ResponseShape): unknown {
263
+ if (shape.format === "text") {
264
+ // Raw passthrough — returned as-is, no trim (matches xml/json branches).
265
+ return body;
266
+ }
267
+
268
+ if (shape.format === "xml") {
269
+ return xmlParser.parse(body);
270
+ }
271
+
272
+ // JSON
273
+ try {
274
+ return JSON.parse(body);
275
+ } catch (e) {
276
+ throw new HelperError(
277
+ "response",
278
+ `Invalid JSON response: ${e instanceof Error ? e.message : String(e)}`,
279
+ "valid JSON",
280
+ body.slice(0, 200),
281
+ );
282
+ }
283
+ }
284
+
285
+ // ═══════════════════════════════════════════════════════════════════
286
+ // URL construction & auth dispatch
287
+ // ═══════════════════════════════════════════════════════════════════
288
+
289
+ /**
290
+ * Construct the full URL from apiHost + operation path + query params.
291
+ *
292
+ * Agent-supplied URLs are not SSRF-guarded here — the guard lives in
293
+ * `paginate`'s nextLink branch (the one place the URL comes from the
294
+ * remote server).
295
+ */
296
+ function buildUrl(
297
+ apiHost: string,
298
+ resolvedPath: string,
299
+ query: Record<string, string>,
300
+ ): string {
301
+ return joinUrl(apiHost, resolvedPath, new URLSearchParams(query).toString());
302
+ }
303
+
304
+ /**
305
+ * Check auth.kind and branch accordingly.
306
+ * v1 realizes only `none`; any other kind throws a structured error.
307
+ *
308
+ * This dispatch is a deliberate seam, not dead code: keeping the field +
309
+ * dispatch now makes the future keyed-auth build additive (a new `kind`
310
+ * behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
311
+ * `paginate` call site and the guide schema. Do not inline "none" into the
312
+ * callers to "simplify" — that burns the additive path. See
313
+ * `docs/design/api-secrets-roadmap.md` for the build-out plan.
314
+ */
315
+ function checkAuth(auth: ApiGuide["auth"]): void {
316
+ const kind = auth.kind;
317
+ if (kind === "none") return; // no auth header needed
318
+
319
+ // V1 only realizes `none`. The seam exists; error informingly.
320
+ throw new HelperError(
321
+ "auth.kind",
322
+ `Auth kind "${kind}" is not supported in this version`,
323
+ "one of: none",
324
+ kind,
325
+ kind === "static-key"
326
+ ? "Static-key auth is not yet implemented. Use kind: none for public APIs."
327
+ : kind === "oauth2"
328
+ ? "OAuth2 is not yet implemented. Use kind: none for public APIs."
329
+ : "Use auth.kind: none for public APIs",
330
+ );
331
+ }
332
+
333
+ /**
334
+ * Helper to conditionally include `fresh` in FetchOptions (exactOptionalPropertyTypes).
335
+ */
336
+ function fetchWithOpts(
337
+ url: string,
338
+ accept: string,
339
+ fresh: boolean | undefined,
340
+ extraHeaders?: Record<string, string>,
341
+ guardRedirects?: boolean,
342
+ fallbackCharset?: string,
343
+ ): ReturnType<typeof fetchUrl> {
344
+ const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
345
+ if (fresh !== undefined) opts.fresh = fresh;
346
+ if (guardRedirects) opts.guardRedirects = true;
347
+ if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
348
+ return fetchUrl(url, opts);
349
+ }
350
+
351
+ /**
352
+ * Check fetch result status and throw a structured error on 4xx/5xx.
353
+ *
354
+ * Without this check, a non-2xx response is passed to `parseResponse`
355
+ * which tries to JSON.parse an XML error body, producing a misleading
356
+ * "Invalid JSON response" message.
357
+ *
358
+ * For XML error bodies (common in REST APIs), the `<text>` element is
359
+ * extracted for a cleaner human message.
360
+ */
361
+ function checkResponseStatus(result: {
362
+ status: number;
363
+ body: string;
364
+ url?: string;
365
+ }): void {
366
+ if (result.status < 400) return;
367
+
368
+ // Cap the raw body to avoid flooding the error output.
369
+ let message = result.body.slice(0, 500);
370
+ // Try to extract <text> from BOE-style XML error bodies.
371
+ const textMatch = result.body.match(/<text>([\s\S]*?)<\/text>/i);
372
+ if (textMatch) {
373
+ message = textMatch[1]!.trim();
374
+ }
375
+
376
+ throw new HelperError(
377
+ "response",
378
+ `Unexpected HTTP ${result.status}: ${message}`,
379
+ "HTTP 2xx",
380
+ String(result.status),
381
+ undefined,
382
+ result.url,
383
+ );
384
+ }
385
+
386
+ // ═══════════════════════════════════════════════════════════════════
387
+ // restGet
388
+ // ═══════════════════════════════════════════════════════════════════
389
+
390
+ export interface RestGetOptions {
391
+ /** Skip cache — force fresh fetch. */
392
+ fresh?: boolean;
393
+ }
394
+
395
+ /**
396
+ * Execute a single `restGet` operation.
397
+ *
398
+ * 1. Replaces `{token}` path params from `params`.
399
+ * 2. Assembles query params with defaults and required validation.
400
+ * 3. Checks auth dispatch (only `none` realised in v1).
401
+ * 4. Constructs the full URL.
402
+ * 5. Builds the Accept header.
403
+ * 6. Fetches via the transport layer.
404
+ * 7. Checks HTTP status — raises HelperError on 4xx/5xx.
405
+ * 8. Parses the response based on the operation's `parse` override or
406
+ * the guide's `responseShape`.
407
+ *
408
+ * @returns The parsed response data and response headers.
409
+ */
410
+ export async function restGet(
411
+ apiHost: string,
412
+ operation: Operation,
413
+ params: Record<string, unknown>,
414
+ guide: ApiGuide,
415
+ opts?: RestGetOptions,
416
+ transformFn?: TransformFn,
417
+ dirName?: string,
418
+ ): Promise<RestGetResult> {
419
+ // 1. Fill path template.
420
+ const resolvedPath = fillPathStrict(operation.path, params);
421
+
422
+ // 2. Build query params.
423
+ const query = buildQueryParams(operation, params);
424
+
425
+ // 3. Auth dispatch.
426
+ checkAuth(guide.auth);
427
+
428
+ // 4. Build URL.
429
+ const url = buildUrl(apiHost, resolvedPath, query);
430
+
431
+ // 5. Build Accept header — json/xml shorthands expand; everything
432
+ // else passes through as-is (e.g. application/atom+xml, */*).
433
+ const accept = expandAccept(operation.accept);
434
+
435
+ // 6. Fetch. Pass the effective shape's charset as a transport fallback
436
+ // for servers that omit a Content-Type charset (e.g. legacy Latin-1
437
+ // APIs); an explicit header charset always wins.
438
+ const shape = operation.parse ?? guide.responseShape;
439
+ const result = await fetchWithOpts(
440
+ url,
441
+ accept,
442
+ opts?.fresh,
443
+ guide.auth.headers,
444
+ undefined,
445
+ shape.charset,
446
+ );
447
+
448
+ // 7. Check HTTP status before attempting to parse the body.
449
+ // This turns "Invalid JSON response: <?xml..." into a clean
450
+ // "Unexpected HTTP 400: El parámetro fecha..." message.
451
+ checkResponseStatus({ ...result, url });
452
+
453
+ // 8. Parse response using the effective shape resolved above.
454
+ let data = parseResponse(result.body, shape);
455
+
456
+ // 9. Post-response transform (optional). When api-fetch supplied a
457
+ // `transformFn` (op.transform === true), apply it. A throwing transform is
458
+ // caught: keep the raw `data` and carry a `transformWarning` so the caller
459
+ // can surface "⚠ Transform failed:" — the op is NOT disabled, so a
460
+ // subsequent call re-attempts the transform.
461
+ let transformWarning: string | undefined;
462
+ if (transformFn) {
463
+ try {
464
+ data = transformFn(data, {
465
+ operation: operation.name,
466
+ domain: dirName ?? "",
467
+ });
468
+ } catch (err) {
469
+ transformWarning = err instanceof Error ? err.message : String(err);
470
+ }
471
+ }
472
+
473
+ return {
474
+ data,
475
+ headers: result.headers,
476
+ url,
477
+ params: query,
478
+ ...(transformWarning !== undefined ? { transformWarning } : {}),
479
+ };
480
+ }
481
+
482
+ // ═══════════════════════════════════════════════════════════════════
483
+ // paginate
484
+ // ═══════════════════════════════════════════════════════════════════
485
+
486
+ export interface PaginateOptions {
487
+ /** When true, gather items up to `gatherAllMax`. Default false. */
488
+ gatherAll?: boolean;
489
+ /** Max items to gather when `gatherAll` is true. Overrides guide/operation default. */
490
+ gatherAllMax?: number;
491
+ /** Skip cache — force fresh fetch for each page. */
492
+ fresh?: boolean;
493
+ /** Bypass the nextLink SSRF guard (for testing against local servers). */
494
+ skipSsrfGuard?: boolean;
495
+ }
496
+
497
+ /**
498
+ * Execute a paginated operation.
499
+ *
500
+ * Supports six pagination styles:
501
+ * - `offset-limit`: advance the `offset` param by the page size (row offset).
502
+ * - `nextLink`: follow the `next` URL from each page response.
503
+ * - `cursor`: pass the cursor from each page to the next.
504
+ * - `page`: incrementing page number + fixed page size.
505
+ * - `resumptionToken`: echo an opaque token from each page into a query param.
506
+ * - `tokenBag`: merge a set of continuation keys from each page into the next request.
507
+ *
508
+ * @returns Accumulated items across all pages.
509
+ */
510
+ export async function paginate(
511
+ apiHost: string,
512
+ operation: Operation,
513
+ params: Record<string, unknown>,
514
+ guide: ApiGuide,
515
+ opts?: PaginateOptions,
516
+ transformFn?: TransformFn,
517
+ dirName?: string,
518
+ ): Promise<PaginateResult> {
519
+ const pagCfg = operation.pagination ?? guide.pagination;
520
+ if (!pagCfg) {
521
+ throw new HelperError(
522
+ "pagination",
523
+ "Cannot paginate — no pagination config in operation or guide",
524
+ "a pagination block",
525
+ "missing",
526
+ "Add a pagination: block to the operation or the guide's top-level config",
527
+ );
528
+ }
529
+
530
+ const gatherAll = opts?.gatherAll ?? false;
531
+ const ceiling =
532
+ opts?.gatherAllMax ?? operation.gatherAllMax ?? guide.gatherAllMax;
533
+ const items: unknown[] = [];
534
+ const failed: unknown[] = [];
535
+ let ceilingHit = false;
536
+ let serverTotal: number | undefined;
537
+
538
+ // Resolve effective response shape (op-level parse or guide-level).
539
+ const shape = operation.parse ?? guide.responseShape;
540
+ const accept = expandAccept(operation.accept);
541
+
542
+ // Auth dispatch — checked once up front (auth is constant per guide).
543
+ checkAuth(guide.auth);
544
+
545
+ // State for the styles.
546
+ let cursor: string | undefined;
547
+ let nextUrl: string | undefined;
548
+ let page: number | undefined;
549
+ let token: string | undefined;
550
+ let tokenBag: Record<string, string> | undefined;
551
+
552
+ const style = pagCfg.style;
553
+
554
+ // Seed offset/page params.
555
+ if (style === "offset-limit" || style === "page") {
556
+ // Caller value, else the recipe's declared default for this page param,
557
+ // else 0. Some APIs are 1-based and reject offset=0 (USGS FDSN); a
558
+ // recipe expresses that as `params: { offset: { default: 1 } }`.
559
+ const rawPage =
560
+ params[pagCfg.pageParam!] ??
561
+ operation.params[pagCfg.pageParam!]?.default ??
562
+ 0;
563
+ page =
564
+ typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
565
+ if (isNaN(page)) page = 0;
566
+ }
567
+
568
+ // Compute effective params once — used for both per-page building and result transparency.
569
+ const effectiveParams = buildQueryParams(operation, params);
570
+ const urls: string[] = [];
571
+
572
+ while (true) {
573
+ // Build per-page params.
574
+ const pageParams: Record<string, string> = {};
575
+ for (const [key, val] of Object.entries(effectiveParams)) {
576
+ pageParams[key] = val;
577
+ }
578
+
579
+ if (style === "offset-limit" || style === "page") {
580
+ pageParams[pagCfg.pageParam!] = String(page ?? 0);
581
+ if (pagCfg.pageSizeParam) {
582
+ pageParams[pagCfg.pageSizeParam] = String(pagCfg.pageSize ?? 50);
583
+ }
584
+ } else if (style === "cursor" && cursor !== undefined) {
585
+ pageParams[pagCfg.cursorParam!] = cursor;
586
+ } else if (style === "resumptionToken" && token !== undefined) {
587
+ pageParams[pagCfg.tokenParam!] = token;
588
+ } else if (style === "tokenBag" && tokenBag) {
589
+ Object.assign(pageParams, tokenBag);
590
+ }
591
+
592
+ // Build URL.
593
+ const resolvedPath = fillPathStrict(operation.path, params);
594
+
595
+ let url: string;
596
+ if (style === "nextLink" && nextUrl) {
597
+ // If nextUrl is relative, resolve against apiHost.
598
+ url = nextUrl.startsWith("http")
599
+ ? nextUrl
600
+ : new URL(nextUrl, apiHost).toString();
601
+ } else {
602
+ url = buildUrl(apiHost, resolvedPath, pageParams);
603
+ }
604
+
605
+ urls.push(url);
606
+
607
+ // NextLink guard — the URL comes from the remote server, so this is
608
+ // the one place SSRF protection is load-bearing. `guardThisFetch`
609
+ // both blocks the nextLink URL itself and turns on redirect-target
610
+ // guarding in the transport layer (a malicious API can 302 a
611
+ // nextLink to an internal host; when auth headers ship, the
612
+ // Authorization header would attach to the redirect).
613
+ const guardThisFetch =
614
+ style === "nextLink" && !!nextUrl && !opts?.skipSsrfGuard;
615
+ if (guardThisFetch) {
616
+ const guard = ssrfGuard(url);
617
+ if (!guard.ok) {
618
+ throw new HelperError(
619
+ "url",
620
+ `URL blocked during pagination: ${guard.reason}`,
621
+ "a safe, public URL",
622
+ url,
623
+ undefined,
624
+ url,
625
+ );
626
+ }
627
+ }
628
+
629
+ // Fetch.
630
+ const result = await fetchWithOpts(
631
+ url,
632
+ accept,
633
+ opts?.fresh,
634
+ guide.auth.headers,
635
+ guardThisFetch,
636
+ shape.charset,
637
+ );
638
+
639
+ // Check HTTP status before attempting to parse.
640
+ checkResponseStatus({ ...result, url });
641
+
642
+ // Parse.
643
+ const data = parseResponse(result.body, shape);
644
+
645
+ // Extract the server's reported total from the first page — before the
646
+ // empty-page break below, so a zero-result page that still carries the
647
+ // count (e.g. `total_count: 0`) surfaces it rather than losing it to the
648
+ // early `break`. Accepts a number directly or a numeric string (coerced
649
+ // via Number()); any other value (or an unresolved path) leaves it
650
+ // undefined for that page and it stays unset for the whole run.
651
+ if (serverTotal === undefined && pagCfg.totalCountPath) {
652
+ const raw = resolveJsonPath(data, pagCfg.totalCountPath);
653
+ if (typeof raw === "number" && Number.isFinite(raw)) {
654
+ serverTotal = raw;
655
+ } else if (typeof raw === "string" && raw.trim() !== "") {
656
+ const n = Number(raw);
657
+ if (Number.isFinite(n)) serverTotal = n;
658
+ }
659
+ }
660
+
661
+ // Extract items from this page.
662
+ let pageItems = resolveJsonPath(data, pagCfg.itemsPath);
663
+ // A1: normalize a single XML record (or scalar) into an array so the
664
+ // declared list path always yields an array even with one element
665
+ // (e.g. arXiv max_results=1, PubMed retmax=1 box a single record).
666
+ if (pageItems != null && !Array.isArray(pageItems)) {
667
+ pageItems = [pageItems];
668
+ }
669
+ if (Array.isArray(pageItems)) {
670
+ if (pageItems.length === 0) break; // empty page → exhaustion
671
+ // Apply the post-response transform per item. A throwing transform
672
+ // keeps the raw item in `failed` — no item is dropped. The ceiling is
673
+ // evaluated against total raw items processed (items + failed), so
674
+ // partial failures cannot exceed the ceiling.
675
+ const totalProcessed = items.length + failed.length;
676
+ const remaining = ceiling - totalProcessed;
677
+ const toProcess =
678
+ gatherAll && pageItems.length > remaining
679
+ ? pageItems.slice(0, remaining)
680
+ : pageItems;
681
+ for (const item of toProcess) {
682
+ if (transformFn) {
683
+ try {
684
+ items.push(
685
+ transformFn(item, {
686
+ operation: operation.name,
687
+ domain: dirName ?? "",
688
+ }),
689
+ );
690
+ } catch {
691
+ failed.push(item);
692
+ }
693
+ } else {
694
+ items.push(item);
695
+ }
696
+ }
697
+ if (gatherAll && pageItems.length > remaining) {
698
+ ceilingHit = true;
699
+ break;
700
+ }
701
+ if (!gatherAll) break; // default = single page; gatherAll:true walks on
702
+ } else {
703
+ break; // items path didn't resolve to an array → stop
704
+ }
705
+
706
+ // Ceiling check.
707
+ if (gatherAll && items.length + failed.length >= ceiling) {
708
+ ceilingHit = true;
709
+ break;
710
+ }
711
+
712
+ // Determine next page.
713
+ const advanced = advancePagination(style, pagCfg, data, page);
714
+
715
+ if (!advanced) break;
716
+
717
+ page = advanced.page;
718
+ cursor = advanced.cursor;
719
+ nextUrl = advanced.nextUrl;
720
+ token = advanced.token;
721
+ tokenBag = advanced.tokenBag;
722
+ }
723
+
724
+ return {
725
+ items,
726
+ totalFetched: items.length + failed.length,
727
+ ...(failed.length > 0 ? { failedItems: failed } : {}),
728
+ ...(serverTotal !== undefined ? { serverTotal } : {}),
729
+ ceilingHit,
730
+ urls,
731
+ pages: urls.length,
732
+ params: effectiveParams,
733
+ };
734
+ }
735
+
736
+ // ═══════════════════════════════════════════════════════════════════
737
+ // Pagination advance logic
738
+ // ═══════════════════════════════════════════════════════════════════
739
+
740
+ interface PaginationState {
741
+ page?: number;
742
+ cursor?: string;
743
+ nextUrl?: string;
744
+ token?: string;
745
+ tokenBag?: Record<string, string>;
746
+ }
747
+
748
+ function advancePagination(
749
+ style: string,
750
+ cfg: NonNullable<Operation["pagination"]>,
751
+ data: unknown,
752
+ prevPage?: number,
753
+ ): PaginationState | null {
754
+ if (style === "offset-limit") {
755
+ // Row-offset semantics: the API skips `offset` items, so the next page
756
+ // must advance by the page size, not by 1 (a +1 advance re-reads the
757
+ // same rows and overlaps pages). APIs whose param is a true page index
758
+ // use style: page, which keeps the +1 advance.
759
+ return { page: (prevPage ?? 0) + (cfg.pageSize ?? 50) };
760
+ }
761
+
762
+ if (style === "page") {
763
+ return { page: (prevPage ?? 0) + 1 };
764
+ }
765
+
766
+ if (style === "nextLink") {
767
+ const next = resolveJsonPath(data, cfg.nextLinkPath!);
768
+ if (!next || typeof next !== "string") return null;
769
+ return { nextUrl: next };
770
+ }
771
+
772
+ if (style === "cursor") {
773
+ const next = resolveJsonPath(data, cfg.cursorPath!);
774
+ if (!next || typeof next !== "string") return null;
775
+ return { cursor: next };
776
+ }
777
+
778
+ if (style === "resumptionToken") {
779
+ const t = resolveJsonPath(data, cfg.tokenPath!);
780
+ if (typeof t !== "string" || t === "") return null;
781
+ return { token: t };
782
+ }
783
+
784
+ if (style === "tokenBag") {
785
+ // ponytail: one resolveJsonPath call per continuation key — O(keys) per
786
+ // page, keys ≈ 1–2 in practice. Fine. Revisit if an API emits a 50-key bag.
787
+ // The path may be nested (e.g. "continue.rccontinue") but the param name
788
+ // resent to the API is the last segment ("rccontinue") — matching the
789
+ // key names inside the continuation object.
790
+ const collected: Record<string, string> = {};
791
+ for (const key of cfg.continuationParams ?? []) {
792
+ const v = resolveJsonPath(data, key);
793
+ if (v === undefined || v === null) continue;
794
+ const param = key.includes(".") ? key.split(".").pop()! : key;
795
+ collected[param] = String(v);
796
+ }
797
+ return Object.keys(collected).length > 0 ? { tokenBag: collected } : null;
798
+ }
799
+
800
+ return null;
801
+ }