pi-lean-host 0.0.1 → 0.1.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 +761 -30
- package/core/api-guide-types.ts +244 -0
- package/core/api-toggle.ts +313 -0
- package/core/guide-loader.ts +80 -0
- package/core/guide-store.ts +125 -0
- package/core/helpers-command.ts +110 -0
- package/core/helpers.ts +792 -0
- package/core/local-helpers.ts +246 -0
- package/core/parse-api-guide.ts +1218 -0
- package/core/path-template.ts +50 -0
- package/core/portal-projection.ts +69 -0
- package/core/response-spill.ts +185 -0
- package/core/ssrf-guard.ts +99 -0
- package/core/transport.ts +440 -0
- package/core/verify-ship-manifest.ts +118 -0
- package/index.ts +46 -0
- package/package.json +42 -13
- package/tools/api-fetch.ts +578 -0
- package/tools/api-guide.ts +320 -0
- package/tools/api-learn.ts +348 -0
- package/tools/api-probe.ts +500 -0
- package/tools/index.ts +7 -0
- package/tools/utils.ts +34 -0
- package/AGENTS.md +0 -22
package/core/helpers.ts
ADDED
|
@@ -0,0 +1,792 @@
|
|
|
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
|
+
});
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Parse a response body according to the guide's response shape.
|
|
248
|
+
*
|
|
249
|
+
* The body is already decoded to a JavaScript string by the transport
|
|
250
|
+
* layer, which uses the response's Content-Type charset with the recipe's
|
|
251
|
+
* `shape.charset` as a fallback when the header omits one (an explicit
|
|
252
|
+
* header charset wins). `parseResponse` itself does no decoding — the
|
|
253
|
+
* `charset` field is consumed by the transport, not here.
|
|
254
|
+
*
|
|
255
|
+
* @param body The response body string (correctly decoded).
|
|
256
|
+
* @param shape The response shape (format dictates XML vs JSON parsing).
|
|
257
|
+
* @returns Parsed JSON value or XML-converted object.
|
|
258
|
+
*/
|
|
259
|
+
export function parseResponse(body: string, shape: ResponseShape): unknown {
|
|
260
|
+
if (shape.format === "text") {
|
|
261
|
+
// Raw passthrough — returned as-is, no trim (matches xml/json branches).
|
|
262
|
+
return body;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (shape.format === "xml") {
|
|
266
|
+
return xmlParser.parse(body);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// JSON
|
|
270
|
+
try {
|
|
271
|
+
return JSON.parse(body);
|
|
272
|
+
} catch (e) {
|
|
273
|
+
throw new HelperError(
|
|
274
|
+
"response",
|
|
275
|
+
`Invalid JSON response: ${e instanceof Error ? e.message : String(e)}`,
|
|
276
|
+
"valid JSON",
|
|
277
|
+
body.slice(0, 200),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
283
|
+
// URL construction & auth dispatch
|
|
284
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Construct the full URL from apiHost + operation path + query params.
|
|
288
|
+
*
|
|
289
|
+
* Agent-supplied URLs are not SSRF-guarded here — the guard lives in
|
|
290
|
+
* `paginate`'s nextLink branch (the one place the URL comes from the
|
|
291
|
+
* remote server).
|
|
292
|
+
*/
|
|
293
|
+
function buildUrl(
|
|
294
|
+
apiHost: string,
|
|
295
|
+
resolvedPath: string,
|
|
296
|
+
query: Record<string, string>,
|
|
297
|
+
): string {
|
|
298
|
+
return joinUrl(apiHost, resolvedPath, new URLSearchParams(query).toString());
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Check auth.kind and branch accordingly.
|
|
303
|
+
* v1 realizes only `none`; any other kind throws a structured error.
|
|
304
|
+
*
|
|
305
|
+
* This dispatch is a deliberate seam, not dead code: keeping the field +
|
|
306
|
+
* dispatch now makes the future keyed-auth build additive (a new `kind`
|
|
307
|
+
* behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
|
|
308
|
+
* `paginate` call site and the guide schema. Do not inline "none" into the
|
|
309
|
+
* callers to "simplify" — that burns the additive path. See
|
|
310
|
+
* `docs/design/api-secrets-roadmap.md` for the build-out plan.
|
|
311
|
+
*/
|
|
312
|
+
function checkAuth(auth: ApiGuide["auth"]): void {
|
|
313
|
+
const kind = auth.kind;
|
|
314
|
+
if (kind === "none") return; // no auth header needed
|
|
315
|
+
|
|
316
|
+
// V1 only realizes `none`. The seam exists; error informingly.
|
|
317
|
+
throw new HelperError(
|
|
318
|
+
"auth.kind",
|
|
319
|
+
`Auth kind "${kind}" is not supported in this version`,
|
|
320
|
+
"one of: none",
|
|
321
|
+
kind,
|
|
322
|
+
kind === "static-key"
|
|
323
|
+
? "Static-key auth is not yet implemented. Use kind: none for public APIs."
|
|
324
|
+
: kind === "oauth2"
|
|
325
|
+
? "OAuth2 is not yet implemented. Use kind: none for public APIs."
|
|
326
|
+
: "Use auth.kind: none for public APIs",
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Helper to conditionally include `fresh` in FetchOptions (exactOptionalPropertyTypes).
|
|
332
|
+
*/
|
|
333
|
+
function fetchWithOpts(
|
|
334
|
+
url: string,
|
|
335
|
+
accept: string,
|
|
336
|
+
fresh: boolean | undefined,
|
|
337
|
+
extraHeaders?: Record<string, string>,
|
|
338
|
+
guardRedirects?: boolean,
|
|
339
|
+
fallbackCharset?: string,
|
|
340
|
+
): ReturnType<typeof fetchUrl> {
|
|
341
|
+
const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
|
|
342
|
+
if (fresh !== undefined) opts.fresh = fresh;
|
|
343
|
+
if (guardRedirects) opts.guardRedirects = true;
|
|
344
|
+
if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
|
|
345
|
+
return fetchUrl(url, opts);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Check fetch result status and throw a structured error on 4xx/5xx.
|
|
350
|
+
*
|
|
351
|
+
* Without this check, a non-2xx response is passed to `parseResponse`
|
|
352
|
+
* which tries to JSON.parse an XML error body, producing a misleading
|
|
353
|
+
* "Invalid JSON response" message.
|
|
354
|
+
*
|
|
355
|
+
* For XML error bodies (common in REST APIs), the `<text>` element is
|
|
356
|
+
* extracted for a cleaner human message.
|
|
357
|
+
*/
|
|
358
|
+
function checkResponseStatus(result: {
|
|
359
|
+
status: number;
|
|
360
|
+
body: string;
|
|
361
|
+
url?: string;
|
|
362
|
+
}): void {
|
|
363
|
+
if (result.status < 400) return;
|
|
364
|
+
|
|
365
|
+
// Cap the raw body to avoid flooding the error output.
|
|
366
|
+
let message = result.body.slice(0, 500);
|
|
367
|
+
// Try to extract <text> from BOE-style XML error bodies.
|
|
368
|
+
const textMatch = result.body.match(/<text>([\s\S]*?)<\/text>/i);
|
|
369
|
+
if (textMatch) {
|
|
370
|
+
message = textMatch[1]!.trim();
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
throw new HelperError(
|
|
374
|
+
"response",
|
|
375
|
+
`Unexpected HTTP ${result.status}: ${message}`,
|
|
376
|
+
"HTTP 2xx",
|
|
377
|
+
String(result.status),
|
|
378
|
+
undefined,
|
|
379
|
+
result.url,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
384
|
+
// restGet
|
|
385
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
386
|
+
|
|
387
|
+
export interface RestGetOptions {
|
|
388
|
+
/** Skip cache — force fresh fetch. */
|
|
389
|
+
fresh?: boolean;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Execute a single `restGet` operation.
|
|
394
|
+
*
|
|
395
|
+
* 1. Replaces `{token}` path params from `params`.
|
|
396
|
+
* 2. Assembles query params with defaults and required validation.
|
|
397
|
+
* 3. Checks auth dispatch (only `none` realised in v1).
|
|
398
|
+
* 4. Constructs the full URL.
|
|
399
|
+
* 5. Builds the Accept header.
|
|
400
|
+
* 6. Fetches via the transport layer.
|
|
401
|
+
* 7. Checks HTTP status — raises HelperError on 4xx/5xx.
|
|
402
|
+
* 8. Parses the response based on the operation's `parse` override or
|
|
403
|
+
* the guide's `responseShape`.
|
|
404
|
+
*
|
|
405
|
+
* @returns The parsed response data and response headers.
|
|
406
|
+
*/
|
|
407
|
+
export async function restGet(
|
|
408
|
+
apiHost: string,
|
|
409
|
+
operation: Operation,
|
|
410
|
+
params: Record<string, unknown>,
|
|
411
|
+
guide: ApiGuide,
|
|
412
|
+
opts?: RestGetOptions,
|
|
413
|
+
transformFn?: TransformFn,
|
|
414
|
+
dirName?: string,
|
|
415
|
+
): Promise<RestGetResult> {
|
|
416
|
+
// 1. Fill path template.
|
|
417
|
+
const resolvedPath = fillPathStrict(operation.path, params);
|
|
418
|
+
|
|
419
|
+
// 2. Build query params.
|
|
420
|
+
const query = buildQueryParams(operation, params);
|
|
421
|
+
|
|
422
|
+
// 3. Auth dispatch.
|
|
423
|
+
checkAuth(guide.auth);
|
|
424
|
+
|
|
425
|
+
// 4. Build URL.
|
|
426
|
+
const url = buildUrl(apiHost, resolvedPath, query);
|
|
427
|
+
|
|
428
|
+
// 5. Build Accept header — json/xml shorthands expand; everything
|
|
429
|
+
// else passes through as-is (e.g. application/atom+xml, */*).
|
|
430
|
+
const accept = expandAccept(operation.accept);
|
|
431
|
+
|
|
432
|
+
// 6. Fetch. Pass the effective shape's charset as a transport fallback
|
|
433
|
+
// for servers that omit a Content-Type charset (e.g. legacy Latin-1
|
|
434
|
+
// APIs); an explicit header charset always wins.
|
|
435
|
+
const shape = operation.parse ?? guide.responseShape;
|
|
436
|
+
const result = await fetchWithOpts(
|
|
437
|
+
url,
|
|
438
|
+
accept,
|
|
439
|
+
opts?.fresh,
|
|
440
|
+
guide.auth.headers,
|
|
441
|
+
undefined,
|
|
442
|
+
shape.charset,
|
|
443
|
+
);
|
|
444
|
+
|
|
445
|
+
// 7. Check HTTP status before attempting to parse the body.
|
|
446
|
+
// This turns "Invalid JSON response: <?xml..." into a clean
|
|
447
|
+
// "Unexpected HTTP 400: El parámetro fecha..." message.
|
|
448
|
+
checkResponseStatus({ ...result, url });
|
|
449
|
+
|
|
450
|
+
// 8. Parse response using the effective shape resolved above.
|
|
451
|
+
let data = parseResponse(result.body, shape);
|
|
452
|
+
|
|
453
|
+
// 9. Post-response transform (optional). When api-fetch supplied a
|
|
454
|
+
// `transformFn` (op.transform === true), apply it. A throwing transform is
|
|
455
|
+
// caught: keep the raw `data` and carry a `transformWarning` so the caller
|
|
456
|
+
// can surface "⚠ Transform failed:" — the op is NOT disabled, so a
|
|
457
|
+
// subsequent call re-attempts the transform.
|
|
458
|
+
let transformWarning: string | undefined;
|
|
459
|
+
if (transformFn) {
|
|
460
|
+
try {
|
|
461
|
+
data = transformFn(data, {
|
|
462
|
+
operation: operation.name,
|
|
463
|
+
domain: dirName ?? "",
|
|
464
|
+
});
|
|
465
|
+
} catch (err) {
|
|
466
|
+
transformWarning = err instanceof Error ? err.message : String(err);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return {
|
|
471
|
+
data,
|
|
472
|
+
headers: result.headers,
|
|
473
|
+
url,
|
|
474
|
+
params: query,
|
|
475
|
+
...(transformWarning !== undefined ? { transformWarning } : {}),
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
480
|
+
// paginate
|
|
481
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
482
|
+
|
|
483
|
+
export interface PaginateOptions {
|
|
484
|
+
/** When true, gather items up to `gatherAllMax`. Default false. */
|
|
485
|
+
gatherAll?: boolean;
|
|
486
|
+
/** Max items to gather when `gatherAll` is true. Overrides guide/operation default. */
|
|
487
|
+
gatherAllMax?: number;
|
|
488
|
+
/** Skip cache — force fresh fetch for each page. */
|
|
489
|
+
fresh?: boolean;
|
|
490
|
+
/** Bypass the nextLink SSRF guard (for testing against local servers). */
|
|
491
|
+
skipSsrfGuard?: boolean;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Execute a paginated operation.
|
|
496
|
+
*
|
|
497
|
+
* Supports six pagination styles:
|
|
498
|
+
* - `offset-limit`: advance the `offset` param by the page size (row offset).
|
|
499
|
+
* - `nextLink`: follow the `next` URL from each page response.
|
|
500
|
+
* - `cursor`: pass the cursor from each page to the next.
|
|
501
|
+
* - `page`: incrementing page number + fixed page size.
|
|
502
|
+
* - `resumptionToken`: echo an opaque token from each page into a query param.
|
|
503
|
+
* - `tokenBag`: merge a set of continuation keys from each page into the next request.
|
|
504
|
+
*
|
|
505
|
+
* @returns Accumulated items across all pages.
|
|
506
|
+
*/
|
|
507
|
+
export async function paginate(
|
|
508
|
+
apiHost: string,
|
|
509
|
+
operation: Operation,
|
|
510
|
+
params: Record<string, unknown>,
|
|
511
|
+
guide: ApiGuide,
|
|
512
|
+
opts?: PaginateOptions,
|
|
513
|
+
transformFn?: TransformFn,
|
|
514
|
+
dirName?: string,
|
|
515
|
+
): Promise<PaginateResult> {
|
|
516
|
+
const pagCfg = operation.pagination ?? guide.pagination;
|
|
517
|
+
if (!pagCfg) {
|
|
518
|
+
throw new HelperError(
|
|
519
|
+
"pagination",
|
|
520
|
+
"Cannot paginate — no pagination config in operation or guide",
|
|
521
|
+
"a pagination block",
|
|
522
|
+
"missing",
|
|
523
|
+
"Add a pagination: block to the operation or the guide's top-level config",
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const gatherAll = opts?.gatherAll ?? false;
|
|
528
|
+
const ceiling =
|
|
529
|
+
opts?.gatherAllMax ?? operation.gatherAllMax ?? guide.gatherAllMax;
|
|
530
|
+
const items: unknown[] = [];
|
|
531
|
+
const failed: unknown[] = [];
|
|
532
|
+
let ceilingHit = false;
|
|
533
|
+
let serverTotal: number | undefined;
|
|
534
|
+
|
|
535
|
+
// Resolve effective response shape (op-level parse or guide-level).
|
|
536
|
+
const shape = operation.parse ?? guide.responseShape;
|
|
537
|
+
const accept = expandAccept(operation.accept);
|
|
538
|
+
|
|
539
|
+
// Auth dispatch — checked once up front (auth is constant per guide).
|
|
540
|
+
checkAuth(guide.auth);
|
|
541
|
+
|
|
542
|
+
// State for the styles.
|
|
543
|
+
let cursor: string | undefined;
|
|
544
|
+
let nextUrl: string | undefined;
|
|
545
|
+
let page: number | undefined;
|
|
546
|
+
let token: string | undefined;
|
|
547
|
+
let tokenBag: Record<string, string> | undefined;
|
|
548
|
+
|
|
549
|
+
const style = pagCfg.style;
|
|
550
|
+
|
|
551
|
+
// Seed offset/page params.
|
|
552
|
+
if (style === "offset-limit" || style === "page") {
|
|
553
|
+
// Caller value, else the recipe's declared default for this page param,
|
|
554
|
+
// else 0. Some APIs are 1-based and reject offset=0 (USGS FDSN); a
|
|
555
|
+
// recipe expresses that as `params: { offset: { default: 1 } }`.
|
|
556
|
+
const rawPage =
|
|
557
|
+
params[pagCfg.pageParam!] ??
|
|
558
|
+
operation.params[pagCfg.pageParam!]?.default ??
|
|
559
|
+
0;
|
|
560
|
+
page =
|
|
561
|
+
typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
|
|
562
|
+
if (isNaN(page)) page = 0;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// Compute effective params once — used for both per-page building and result transparency.
|
|
566
|
+
const effectiveParams = buildQueryParams(operation, params);
|
|
567
|
+
const urls: string[] = [];
|
|
568
|
+
|
|
569
|
+
while (true) {
|
|
570
|
+
// Build per-page params.
|
|
571
|
+
const pageParams: Record<string, string> = {};
|
|
572
|
+
for (const [key, val] of Object.entries(effectiveParams)) {
|
|
573
|
+
pageParams[key] = val;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
if (style === "offset-limit" || style === "page") {
|
|
577
|
+
pageParams[pagCfg.pageParam!] = String(page ?? 0);
|
|
578
|
+
if (pagCfg.pageSizeParam) {
|
|
579
|
+
pageParams[pagCfg.pageSizeParam] = String(pagCfg.pageSize ?? 50);
|
|
580
|
+
}
|
|
581
|
+
} else if (style === "cursor" && cursor !== undefined) {
|
|
582
|
+
pageParams[pagCfg.cursorParam!] = cursor;
|
|
583
|
+
} else if (style === "resumptionToken" && token !== undefined) {
|
|
584
|
+
pageParams[pagCfg.tokenParam!] = token;
|
|
585
|
+
} else if (style === "tokenBag" && tokenBag) {
|
|
586
|
+
Object.assign(pageParams, tokenBag);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// Build URL.
|
|
590
|
+
const resolvedPath = fillPathStrict(operation.path, params);
|
|
591
|
+
|
|
592
|
+
let url: string;
|
|
593
|
+
if (style === "nextLink" && nextUrl) {
|
|
594
|
+
// If nextUrl is relative, resolve against apiHost.
|
|
595
|
+
url = nextUrl.startsWith("http")
|
|
596
|
+
? nextUrl
|
|
597
|
+
: new URL(nextUrl, apiHost).toString();
|
|
598
|
+
} else {
|
|
599
|
+
url = buildUrl(apiHost, resolvedPath, pageParams);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
urls.push(url);
|
|
603
|
+
|
|
604
|
+
// NextLink guard — the URL comes from the remote server, so this is
|
|
605
|
+
// the one place SSRF protection is load-bearing. `guardThisFetch`
|
|
606
|
+
// both blocks the nextLink URL itself and turns on redirect-target
|
|
607
|
+
// guarding in the transport layer (a malicious API can 302 a
|
|
608
|
+
// nextLink to an internal host; when auth headers ship, the
|
|
609
|
+
// Authorization header would attach to the redirect).
|
|
610
|
+
const guardThisFetch =
|
|
611
|
+
style === "nextLink" && !!nextUrl && !opts?.skipSsrfGuard;
|
|
612
|
+
if (guardThisFetch) {
|
|
613
|
+
const guard = ssrfGuard(url);
|
|
614
|
+
if (!guard.ok) {
|
|
615
|
+
throw new HelperError(
|
|
616
|
+
"url",
|
|
617
|
+
`URL blocked during pagination: ${guard.reason}`,
|
|
618
|
+
"a safe, public URL",
|
|
619
|
+
url,
|
|
620
|
+
undefined,
|
|
621
|
+
url,
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// Fetch.
|
|
627
|
+
const result = await fetchWithOpts(
|
|
628
|
+
url,
|
|
629
|
+
accept,
|
|
630
|
+
opts?.fresh,
|
|
631
|
+
guide.auth.headers,
|
|
632
|
+
guardThisFetch,
|
|
633
|
+
shape.charset,
|
|
634
|
+
);
|
|
635
|
+
|
|
636
|
+
// Check HTTP status before attempting to parse.
|
|
637
|
+
checkResponseStatus({ ...result, url });
|
|
638
|
+
|
|
639
|
+
// Parse.
|
|
640
|
+
const data = parseResponse(result.body, shape);
|
|
641
|
+
|
|
642
|
+
// Extract the server's reported total from the first page — before the
|
|
643
|
+
// empty-page break below, so a zero-result page that still carries the
|
|
644
|
+
// count (e.g. `total_count: 0`) surfaces it rather than losing it to the
|
|
645
|
+
// early `break`. Accepts a number directly or a numeric string (coerced
|
|
646
|
+
// via Number()); any other value (or an unresolved path) leaves it
|
|
647
|
+
// undefined for that page and it stays unset for the whole run.
|
|
648
|
+
if (serverTotal === undefined && pagCfg.totalCountPath) {
|
|
649
|
+
const raw = resolveJsonPath(data, pagCfg.totalCountPath);
|
|
650
|
+
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
651
|
+
serverTotal = raw;
|
|
652
|
+
} else if (typeof raw === "string" && raw.trim() !== "") {
|
|
653
|
+
const n = Number(raw);
|
|
654
|
+
if (Number.isFinite(n)) serverTotal = n;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// Extract items from this page.
|
|
659
|
+
const pageItems = resolveJsonPath(data, pagCfg.itemsPath);
|
|
660
|
+
if (Array.isArray(pageItems)) {
|
|
661
|
+
if (pageItems.length === 0) break; // empty page → exhaustion
|
|
662
|
+
// Apply the post-response transform per item. A throwing transform
|
|
663
|
+
// keeps the raw item in `failed` — no item is dropped. The ceiling is
|
|
664
|
+
// evaluated against total raw items processed (items + failed), so
|
|
665
|
+
// partial failures cannot exceed the ceiling.
|
|
666
|
+
const totalProcessed = items.length + failed.length;
|
|
667
|
+
const remaining = ceiling - totalProcessed;
|
|
668
|
+
const toProcess =
|
|
669
|
+
gatherAll && pageItems.length > remaining
|
|
670
|
+
? pageItems.slice(0, remaining)
|
|
671
|
+
: pageItems;
|
|
672
|
+
for (const item of toProcess) {
|
|
673
|
+
if (transformFn) {
|
|
674
|
+
try {
|
|
675
|
+
items.push(
|
|
676
|
+
transformFn(item, {
|
|
677
|
+
operation: operation.name,
|
|
678
|
+
domain: dirName ?? "",
|
|
679
|
+
}),
|
|
680
|
+
);
|
|
681
|
+
} catch {
|
|
682
|
+
failed.push(item);
|
|
683
|
+
}
|
|
684
|
+
} else {
|
|
685
|
+
items.push(item);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
if (gatherAll && pageItems.length > remaining) {
|
|
689
|
+
ceilingHit = true;
|
|
690
|
+
break;
|
|
691
|
+
}
|
|
692
|
+
if (!gatherAll) break; // default = single page; gatherAll:true walks on
|
|
693
|
+
} else {
|
|
694
|
+
break; // items path didn't resolve to an array → stop
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// Ceiling check.
|
|
698
|
+
if (gatherAll && items.length + failed.length >= ceiling) {
|
|
699
|
+
ceilingHit = true;
|
|
700
|
+
break;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// Determine next page.
|
|
704
|
+
const advanced = advancePagination(style, pagCfg, data, page);
|
|
705
|
+
|
|
706
|
+
if (!advanced) break;
|
|
707
|
+
|
|
708
|
+
page = advanced.page;
|
|
709
|
+
cursor = advanced.cursor;
|
|
710
|
+
nextUrl = advanced.nextUrl;
|
|
711
|
+
token = advanced.token;
|
|
712
|
+
tokenBag = advanced.tokenBag;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
return {
|
|
716
|
+
items,
|
|
717
|
+
totalFetched: items.length + failed.length,
|
|
718
|
+
...(failed.length > 0 ? { failedItems: failed } : {}),
|
|
719
|
+
...(serverTotal !== undefined ? { serverTotal } : {}),
|
|
720
|
+
ceilingHit,
|
|
721
|
+
urls,
|
|
722
|
+
pages: urls.length,
|
|
723
|
+
params: effectiveParams,
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
728
|
+
// Pagination advance logic
|
|
729
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
730
|
+
|
|
731
|
+
interface PaginationState {
|
|
732
|
+
page?: number;
|
|
733
|
+
cursor?: string;
|
|
734
|
+
nextUrl?: string;
|
|
735
|
+
token?: string;
|
|
736
|
+
tokenBag?: Record<string, string>;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function advancePagination(
|
|
740
|
+
style: string,
|
|
741
|
+
cfg: NonNullable<Operation["pagination"]>,
|
|
742
|
+
data: unknown,
|
|
743
|
+
prevPage?: number,
|
|
744
|
+
): PaginationState | null {
|
|
745
|
+
if (style === "offset-limit") {
|
|
746
|
+
// Row-offset semantics: the API skips `offset` items, so the next page
|
|
747
|
+
// must advance by the page size, not by 1 (a +1 advance re-reads the
|
|
748
|
+
// same rows and overlaps pages). APIs whose param is a true page index
|
|
749
|
+
// use style: page, which keeps the +1 advance.
|
|
750
|
+
return { page: (prevPage ?? 0) + (cfg.pageSize ?? 50) };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (style === "page") {
|
|
754
|
+
return { page: (prevPage ?? 0) + 1 };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
if (style === "nextLink") {
|
|
758
|
+
const next = resolveJsonPath(data, cfg.nextLinkPath!);
|
|
759
|
+
if (!next || typeof next !== "string") return null;
|
|
760
|
+
return { nextUrl: next };
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
if (style === "cursor") {
|
|
764
|
+
const next = resolveJsonPath(data, cfg.cursorPath!);
|
|
765
|
+
if (!next || typeof next !== "string") return null;
|
|
766
|
+
return { cursor: next };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
if (style === "resumptionToken") {
|
|
770
|
+
const t = resolveJsonPath(data, cfg.tokenPath!);
|
|
771
|
+
if (typeof t !== "string" || t === "") return null;
|
|
772
|
+
return { token: t };
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
if (style === "tokenBag") {
|
|
776
|
+
// ponytail: one resolveJsonPath call per continuation key — O(keys) per
|
|
777
|
+
// page, keys ≈ 1–2 in practice. Fine. Revisit if an API emits a 50-key bag.
|
|
778
|
+
// The path may be nested (e.g. "continue.rccontinue") but the param name
|
|
779
|
+
// resent to the API is the last segment ("rccontinue") — matching the
|
|
780
|
+
// key names inside the continuation object.
|
|
781
|
+
const collected: Record<string, string> = {};
|
|
782
|
+
for (const key of cfg.continuationParams ?? []) {
|
|
783
|
+
const v = resolveJsonPath(data, key);
|
|
784
|
+
if (v === undefined || v === null) continue;
|
|
785
|
+
const param = key.includes(".") ? key.split(".").pop()! : key;
|
|
786
|
+
collected[param] = String(v);
|
|
787
|
+
}
|
|
788
|
+
return Object.keys(collected).length > 0 ? { tokenBag: collected } : null;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
return null;
|
|
792
|
+
}
|