pi-lean-host 0.4.0 → 0.5.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 +194 -557
- package/core/api-guide-types.ts +250 -47
- package/core/api-toggle.ts +244 -39
- package/core/auth.ts +996 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +2 -2
- package/core/helpers.ts +529 -142
- package/core/local-helpers.ts +7 -0
- package/core/oauth-command.ts +911 -0
- package/core/oauth-flow.ts +376 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1122 -591
- package/core/path-template.ts +101 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/transport.ts +321 -34
- package/core/verify-command.ts +93 -65
- package/docs/migration-v1.md +56 -0
- package/index.ts +12 -10
- package/package.json +16 -6
- package/tools/api-fetch.ts +45 -18
- package/tools/api-guide.ts +20 -11
- package/tools/api-learn.ts +131 -57
- package/tools/api-probe.ts +455 -282
- package/tools/api-scaffold.ts +15 -22
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +1 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -8
package/core/helpers.ts
CHANGED
|
@@ -26,14 +26,22 @@ import { serverMessage, isPlanGated } from "./status-hint.js";
|
|
|
26
26
|
import {
|
|
27
27
|
fetchUrl,
|
|
28
28
|
redactSecretParams,
|
|
29
|
+
redactSecretPathValues,
|
|
29
30
|
type FetchOptions,
|
|
30
31
|
} from "./transport.js";
|
|
31
|
-
import {
|
|
32
|
+
import {
|
|
33
|
+
fillPathTemplate,
|
|
34
|
+
joinUrl,
|
|
35
|
+
tokenizeJsonPath,
|
|
36
|
+
wireParamName,
|
|
37
|
+
} from "./path-template.js";
|
|
32
38
|
import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
|
|
33
39
|
import type {
|
|
34
40
|
ApiGuide,
|
|
35
41
|
DateParamFormat,
|
|
42
|
+
ListStyle,
|
|
36
43
|
Operation,
|
|
44
|
+
QueryParamSpec,
|
|
37
45
|
ResponseShape,
|
|
38
46
|
} from "./api-guide-types.js";
|
|
39
47
|
|
|
@@ -72,10 +80,15 @@ export interface RestGetResult {
|
|
|
72
80
|
headers: Record<string, string>;
|
|
73
81
|
/** The full resolved URL that was fetched. */
|
|
74
82
|
url: string;
|
|
75
|
-
/** Effective query params actually sent (post-defaults, post-validation).
|
|
76
|
-
|
|
83
|
+
/** Effective query params actually sent (post-defaults, post-validation).
|
|
84
|
+
* A `listStyle` param's multi-value array surfaces as a real `string[]`
|
|
85
|
+
* keyed by the declared param name (the URL shows the true wire form). */
|
|
86
|
+
params: Record<string, string | string[]>;
|
|
77
87
|
/** Set when a post-response transform throws (raw `data` preserved). */
|
|
78
88
|
transformWarning?: string;
|
|
89
|
+
/** True when the transport served this response from cache (header hit
|
|
90
|
+
* or 304 revalidation). Absent for live fetches. */
|
|
91
|
+
cached?: boolean;
|
|
79
92
|
}
|
|
80
93
|
|
|
81
94
|
export interface PaginateResult {
|
|
@@ -98,8 +111,10 @@ export interface PaginateResult {
|
|
|
98
111
|
urls: string[];
|
|
99
112
|
/** Number of pages fetched (= urls.length). */
|
|
100
113
|
pages: number;
|
|
101
|
-
/** Effective query params actually sent (post-defaults, post-validation).
|
|
102
|
-
|
|
114
|
+
/** Effective query params actually sent (post-defaults, post-validation).
|
|
115
|
+
* A `listStyle` param's multi-value array surfaces as a real `string[]`
|
|
116
|
+
* keyed by the declared param name (the URL shows the true wire form). */
|
|
117
|
+
params: Record<string, string | string[]>;
|
|
103
118
|
}
|
|
104
119
|
|
|
105
120
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -134,8 +149,8 @@ function buildQueryParams(
|
|
|
134
149
|
operation: Operation,
|
|
135
150
|
params: Record<string, unknown>,
|
|
136
151
|
secretParamNames?: Set<string>,
|
|
137
|
-
): Record<string, string> {
|
|
138
|
-
const query: Record<string, string> = {};
|
|
152
|
+
): Record<string, string | string[]> {
|
|
153
|
+
const query: Record<string, string | string[]> = {};
|
|
139
154
|
const pathParamSet = new Set(operation.pathParams);
|
|
140
155
|
|
|
141
156
|
for (const [key, spec] of Object.entries(operation.params)) {
|
|
@@ -159,15 +174,26 @@ function buildQueryParams(
|
|
|
159
174
|
}
|
|
160
175
|
|
|
161
176
|
if (val !== undefined) {
|
|
162
|
-
// Date param normalization — convert to target format before
|
|
177
|
+
// Date param normalization — convert to target format before
|
|
178
|
+
// serialization. An array here is a loud error BEFORE normalization
|
|
179
|
+
// (normalizeDateParam operates on scalars; an array would be
|
|
180
|
+
// silently mangled on the wire as String(val) garbage).
|
|
163
181
|
if (operation.dateParams && key in operation.dateParams) {
|
|
182
|
+
if (Array.isArray(val)) {
|
|
183
|
+
throw new HelperError(
|
|
184
|
+
`params.${key}`,
|
|
185
|
+
`Array value for date param "${key}" — date params are single-valued`,
|
|
186
|
+
"a scalar date value",
|
|
187
|
+
"an array",
|
|
188
|
+
`Pass one date for params.${key} (remove it from dateParams if the API truly accepts multi-value dates — then declare listStyle:).`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
164
191
|
val = normalizeDateParam(val, operation.dateParams[key]!);
|
|
165
192
|
}
|
|
166
|
-
//
|
|
167
|
-
//
|
|
168
|
-
//
|
|
169
|
-
query[key] =
|
|
170
|
-
typeof val === "object" && val !== null ? JSON.stringify(val) : String(val);
|
|
193
|
+
// Scalars as today; nested objects as JSON (BOE's query_string DSL);
|
|
194
|
+
// arrays only with a declared listStyle (multi-value). Shared with
|
|
195
|
+
// the passthrough loop below — one validator, both sites.
|
|
196
|
+
query[key] = serializeParamValue(key, val, spec.listStyle);
|
|
171
197
|
}
|
|
172
198
|
}
|
|
173
199
|
|
|
@@ -207,16 +233,105 @@ function buildQueryParams(
|
|
|
207
233
|
if (val === undefined) continue;
|
|
208
234
|
let v: unknown = val;
|
|
209
235
|
if (operation.dateParams && key in operation.dateParams) {
|
|
236
|
+
if (Array.isArray(v)) {
|
|
237
|
+
throw new HelperError(
|
|
238
|
+
`params.${key}`,
|
|
239
|
+
`Array value for date param "${key}" — date params are single-valued`,
|
|
240
|
+
"a scalar date value",
|
|
241
|
+
"an array",
|
|
242
|
+
);
|
|
243
|
+
}
|
|
210
244
|
v = normalizeDateParam(v, operation.dateParams[key]!);
|
|
211
245
|
}
|
|
212
|
-
|
|
213
|
-
|
|
246
|
+
// Passthrough keys have no schema and can't declare a listStyle —
|
|
247
|
+
// passing `undefined` makes any array a loud error. Escape valve:
|
|
248
|
+
// declare the param (with a style) instead of passing it undeclared.
|
|
249
|
+
query[key] = serializeParamValue(key, v, undefined);
|
|
214
250
|
}
|
|
215
251
|
}
|
|
216
252
|
|
|
217
253
|
return query;
|
|
218
254
|
}
|
|
219
255
|
|
|
256
|
+
/**
|
|
257
|
+
* Serialize one query-param value — the shared array-rules validator used by
|
|
258
|
+
* BOTH serialization loops (declared params + passthrough) in
|
|
259
|
+
* `buildQueryParams`. The parser's array-`default` validation mirrors these
|
|
260
|
+
* rules at authoring time.
|
|
261
|
+
*
|
|
262
|
+
* - Scalars: exactly as today (`String(val)`).
|
|
263
|
+
* - Nested objects: JSON (BOE's `query_string` DSL must not regress).
|
|
264
|
+
* - Arrays: multi-value, only on a `listStyle`-declared param. Empty arrays
|
|
265
|
+
* and arrays of non-scalars are loud errors (an empty array would silently
|
|
266
|
+
* drop a param that already passed the `required`/`requiresAnyOf` guards;
|
|
267
|
+
* `[object Object]` on the wire is the silent-wrong-wire class this
|
|
268
|
+
* exists to kill). For `comma`, an element containing a `,` is also loud:
|
|
269
|
+
* the joined wire form is indistinguishable from a longer list.
|
|
270
|
+
* - An array without a `listStyle` (including every passthrough array) is a
|
|
271
|
+
* loud error naming the param and the fix.
|
|
272
|
+
*
|
|
273
|
+
* Returns the stored value: a scalar string, or a real `string[]` for
|
|
274
|
+
* multi-value (expanded to wire pairs in `buildUrl`, the one
|
|
275
|
+
* Record→query-string boundary).
|
|
276
|
+
*/
|
|
277
|
+
function serializeParamValue(
|
|
278
|
+
key: string,
|
|
279
|
+
val: unknown,
|
|
280
|
+
listStyle: ListStyle | undefined,
|
|
281
|
+
): string | string[] {
|
|
282
|
+
if (Array.isArray(val)) {
|
|
283
|
+
if (listStyle === undefined) {
|
|
284
|
+
throw new HelperError(
|
|
285
|
+
`params.${key}`,
|
|
286
|
+
`Array value for query param "${key}" but the param declares no listStyle`,
|
|
287
|
+
"a scalar, or an array on a listStyle-declared param",
|
|
288
|
+
"an array",
|
|
289
|
+
`Declare listStyle: comma | repeat | bracket on params.${key}, or pass a scalar`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
if (val.length === 0) {
|
|
293
|
+
throw new HelperError(
|
|
294
|
+
`params.${key}`,
|
|
295
|
+
`Empty array for multi-value query param "${key}" — the param would be silently dropped from the request`,
|
|
296
|
+
"a non-empty array of scalar (string | number | boolean) elements",
|
|
297
|
+
"[]",
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
const out: string[] = [];
|
|
301
|
+
for (const el of val) {
|
|
302
|
+
if (
|
|
303
|
+
el === null ||
|
|
304
|
+
(typeof el !== "string" &&
|
|
305
|
+
typeof el !== "number" &&
|
|
306
|
+
typeof el !== "boolean")
|
|
307
|
+
) {
|
|
308
|
+
throw new HelperError(
|
|
309
|
+
`params.${key}`,
|
|
310
|
+
`Non-scalar element in multi-value query param "${key}"`,
|
|
311
|
+
"an array of scalar (string | number | boolean) elements",
|
|
312
|
+
typeof el === "object" && el !== null ? "an object" : String(el),
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
if (listStyle === "comma" && typeof el === "string" && el.includes(",")) {
|
|
316
|
+
throw new HelperError(
|
|
317
|
+
`params.${key}`,
|
|
318
|
+
`Element of "${key}" contains a comma — listStyle: comma joins with ',' and the joined wire form would be indistinguishable from a longer list`,
|
|
319
|
+
"comma-free elements",
|
|
320
|
+
`"${el}"`,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
out.push(String(el));
|
|
324
|
+
}
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
// Nested objects/arrays-of-last-resort serialize as JSON so structured
|
|
328
|
+
// query params (e.g. BOE's ES query_string DSL) reach the wire as JSON,
|
|
329
|
+
// not `[object Object]`. Scalars stay as String(val).
|
|
330
|
+
return typeof val === "object" && val !== null
|
|
331
|
+
? JSON.stringify(val)
|
|
332
|
+
: String(val);
|
|
333
|
+
}
|
|
334
|
+
|
|
220
335
|
/**
|
|
221
336
|
* Normalize a date string to a target format.
|
|
222
337
|
* Accepts ISO 8601 (YYYY-MM-DD or with time tail), already-target format,
|
|
@@ -239,19 +354,17 @@ export function normalizeDateParam(
|
|
|
239
354
|
|
|
240
355
|
/**
|
|
241
356
|
* Resolve a simple dot-delimited JSON path against an object.
|
|
242
|
-
* Supports `data.items`, `resultados[0].campo`,
|
|
357
|
+
* Supports `data.items`, `resultados[0].campo`, negative array indexes
|
|
358
|
+
* addressing from the end (`results[-1].id`), `$.items` prefix, and
|
|
359
|
+
* quoted-bracket atomic keys for dot-containing names (`['@odata.nextLink']`).
|
|
243
360
|
*
|
|
244
361
|
* Returns `unknown` by design — the value at an arbitrary JSON path has no
|
|
245
362
|
* named domain type until the caller knows the path they asked for.
|
|
246
363
|
*/
|
|
247
364
|
// pi-lens-ignore: ast-grep:no-unknown-returns
|
|
248
365
|
export function resolveJsonPath(obj: unknown, path: string): unknown {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
.replace(/^\$\.?/, "")
|
|
252
|
-
.replace(/\[['"](.*?)['"]\]/g, ".$1")
|
|
253
|
-
.replace(/\[(\d+)\]/g, ".$1");
|
|
254
|
-
const parts = normalised.split(".").filter((p) => p.length > 0);
|
|
366
|
+
const parts = tokenizeJsonPath(path);
|
|
367
|
+
if (parts === null) return undefined; // malformed path → miss, never a wrong match
|
|
255
368
|
if (parts.length === 0) return obj;
|
|
256
369
|
|
|
257
370
|
let current: unknown = obj;
|
|
@@ -260,7 +373,10 @@ export function resolveJsonPath(obj: unknown, path: string): unknown {
|
|
|
260
373
|
if (Array.isArray(current)) {
|
|
261
374
|
const idx = parseInt(part, 10);
|
|
262
375
|
if (isNaN(idx)) return undefined;
|
|
263
|
-
|
|
376
|
+
// Negative index addresses from the end; out of bounds → miss.
|
|
377
|
+
const j = idx < 0 ? idx + current.length : idx;
|
|
378
|
+
if (j < 0 || j >= current.length) return undefined;
|
|
379
|
+
current = current[j];
|
|
264
380
|
} else {
|
|
265
381
|
current = (current as Record<string, unknown>)[part];
|
|
266
382
|
}
|
|
@@ -337,9 +453,33 @@ export function parseResponse(body: string, shape: ResponseShape): unknown {
|
|
|
337
453
|
function buildUrl(
|
|
338
454
|
apiHost: string,
|
|
339
455
|
resolvedPath: string,
|
|
340
|
-
query: Record<string, string>,
|
|
456
|
+
query: Record<string, string | string[]>,
|
|
457
|
+
paramSpecs?: Record<string, QueryParamSpec>,
|
|
341
458
|
): string {
|
|
342
|
-
|
|
459
|
+
// The one Record→query-string boundary. Scalars pass through as one
|
|
460
|
+
// pair; a listStyle param's array expands here — `comma` joins (one
|
|
461
|
+
// pair; elements were validated comma-free at build time), `repeat`
|
|
462
|
+
// fans out one pair per element under the declared name, `bracket`
|
|
463
|
+
// fans out with the wire key dressed +"[]". URLSearchParams encodes the
|
|
464
|
+
// brackets (`id%5B%5D=`) and preserves insertion order (secret params
|
|
465
|
+
// ride below the agent pairs — merge-order contract).
|
|
466
|
+
const pairs: [string, string][] = [];
|
|
467
|
+
for (const [key, val] of Object.entries(query)) {
|
|
468
|
+
if (Array.isArray(val)) {
|
|
469
|
+
const style = paramSpecs?.[key]?.listStyle;
|
|
470
|
+
if (style === "comma") {
|
|
471
|
+
pairs.push([key, val.join(",")]);
|
|
472
|
+
} else if (style === "bracket") {
|
|
473
|
+
const wireKey = `${key}[]`;
|
|
474
|
+
for (const el of val) pairs.push([wireKey, el]);
|
|
475
|
+
} else {
|
|
476
|
+
for (const el of val) pairs.push([key, el]); // repeat
|
|
477
|
+
}
|
|
478
|
+
} else {
|
|
479
|
+
pairs.push([key, val]);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return joinUrl(apiHost, resolvedPath, new URLSearchParams(pairs).toString());
|
|
343
483
|
}
|
|
344
484
|
|
|
345
485
|
/**
|
|
@@ -353,39 +493,108 @@ function buildUrl(
|
|
|
353
493
|
* `paginate` call site and the guide schema.
|
|
354
494
|
*/
|
|
355
495
|
function checkAuth(auth: ApiGuide["auth"]): void {
|
|
356
|
-
|
|
357
|
-
|
|
496
|
+
switch (auth.kind) {
|
|
497
|
+
case "none":
|
|
498
|
+
case "static-key":
|
|
499
|
+
case "oauth2":
|
|
500
|
+
return;
|
|
501
|
+
default: {
|
|
502
|
+
// Exhaustiveness: a future fourth kind is a compile error here.
|
|
503
|
+
const _exhaustive: never = auth;
|
|
504
|
+
throw new HelperError(
|
|
505
|
+
"auth.kind",
|
|
506
|
+
`Auth kind "${_exhaustive}" is not supported in this version`,
|
|
507
|
+
"one of: none | static-key | oauth2",
|
|
508
|
+
String(_exhaustive),
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
358
513
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
514
|
+
/**
|
|
515
|
+
* Split the caller params around secret-owned path tokens: the
|
|
516
|
+
* path fill sees the merged map (store value wins; any agent-supplied value
|
|
517
|
+
* for a secret-owned token is dropped), while the query builder gets a
|
|
518
|
+
* deletion-only copy. The merged map must never reach buildQueryParams — a
|
|
519
|
+
* `passthrough: true` op without {token} in its path would otherwise leak
|
|
520
|
+
* the plaintext token into the query string and result.params.
|
|
521
|
+
*/
|
|
522
|
+
export function splitPathSecretParams(
|
|
523
|
+
params: Record<string, unknown>,
|
|
524
|
+
pathSecrets: Record<string, string>,
|
|
525
|
+
): {
|
|
526
|
+
fillParams: Record<string, unknown>;
|
|
527
|
+
queryParamsForBuild: Record<string, unknown>;
|
|
528
|
+
} {
|
|
529
|
+
if (Object.keys(pathSecrets).length === 0)
|
|
530
|
+
return { fillParams: params, queryParamsForBuild: params };
|
|
531
|
+
return {
|
|
532
|
+
fillParams: { ...params, ...pathSecrets },
|
|
533
|
+
queryParamsForBuild: Object.fromEntries(
|
|
534
|
+
Object.entries(params).filter(([k]) => !(k in pathSecrets)),
|
|
535
|
+
),
|
|
536
|
+
};
|
|
368
537
|
}
|
|
369
538
|
|
|
370
539
|
/**
|
|
371
|
-
*
|
|
540
|
+
* Compose the two URL redaction channels for a surfaced URL — query params
|
|
541
|
+
* by name, path tokens by value. Both helpers early-return when their
|
|
542
|
+
* input is empty, so callers may pass values/set unconditionally.
|
|
372
543
|
*/
|
|
544
|
+
function redactSurfacedUrl(
|
|
545
|
+
url: string,
|
|
546
|
+
secretParamNames: Set<string>,
|
|
547
|
+
pathValues: string[],
|
|
548
|
+
): string {
|
|
549
|
+
return redactSecretPathValues(
|
|
550
|
+
redactSecretParams(url, secretParamNames),
|
|
551
|
+
pathValues,
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Named args for fetchWithOpts — replaced an 11-param positional tail
|
|
556
|
+
* (review nit #4). Optional fields carry `| undefined` so callers can pass
|
|
557
|
+
* through possibly-undefined values without spreads; falsy booleans are
|
|
558
|
+
* no-ops (truthiness-checked below). */
|
|
559
|
+
interface FetchWithOptsArgs {
|
|
560
|
+
/** Expanded Accept header value. */
|
|
561
|
+
accept: string;
|
|
562
|
+
/** Store-injected secret headers + literal auth.headers, merged. */
|
|
563
|
+
extraHeaders?: Record<string, string> | undefined;
|
|
564
|
+
/** Skip cache — force fresh fetch. */
|
|
565
|
+
fresh?: boolean | undefined;
|
|
566
|
+
/** Route through the transport's SSRF-guarded redirect path. */
|
|
567
|
+
guardRedirects?: boolean | undefined;
|
|
568
|
+
/** Charset fallback for servers that omit Content-Type charset. */
|
|
569
|
+
fallbackCharset?: string | undefined;
|
|
570
|
+
/** Lowercased injected header names — stripped on cross-domain redirects. */
|
|
571
|
+
secretHeaderNames?: Set<string> | undefined;
|
|
572
|
+
/** Suppress ETag cache when query secrets ride the URL. */
|
|
573
|
+
hasQuerySecret?: boolean | undefined;
|
|
574
|
+
/** Injected query-secret names — redacted from every surfaced URL. */
|
|
575
|
+
secretQueryParamNames?: Set<string> | undefined;
|
|
576
|
+
/** Path secrets present — cache-skip + guarded redirects. */
|
|
577
|
+
hasPathSecret?: boolean | undefined;
|
|
578
|
+
/** Redaction closure for cross-domain redirect hops. */
|
|
579
|
+
redactPathSecret?: ((url: string) => string) | undefined;
|
|
580
|
+
}
|
|
581
|
+
|
|
373
582
|
function fetchWithOpts(
|
|
374
583
|
url: string,
|
|
375
|
-
|
|
376
|
-
fresh: boolean | undefined,
|
|
377
|
-
extraHeaders?: Record<string, string>,
|
|
378
|
-
guardRedirects?: boolean,
|
|
379
|
-
fallbackCharset?: string,
|
|
380
|
-
secretHeaderNames?: Set<string>,
|
|
381
|
-
hasQuerySecret?: boolean,
|
|
584
|
+
args: FetchWithOptsArgs,
|
|
382
585
|
): ReturnType<typeof fetchUrl> {
|
|
383
|
-
const opts: FetchOptions = {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
if (
|
|
387
|
-
if (
|
|
388
|
-
if (
|
|
586
|
+
const opts: FetchOptions = {
|
|
587
|
+
headers: { accept: args.accept, ...args.extraHeaders },
|
|
588
|
+
};
|
|
589
|
+
if (args.fresh !== undefined) opts.fresh = args.fresh;
|
|
590
|
+
if (args.guardRedirects) opts.guardRedirects = true;
|
|
591
|
+
if (args.fallbackCharset) opts.fallbackCharset = args.fallbackCharset;
|
|
592
|
+
if (args.secretHeaderNames) opts.secretHeaderNames = args.secretHeaderNames;
|
|
593
|
+
if (args.hasQuerySecret) opts.hasQuerySecret = true;
|
|
594
|
+
if (args.secretQueryParamNames)
|
|
595
|
+
opts.secretQueryParamNames = args.secretQueryParamNames;
|
|
596
|
+
if (args.hasPathSecret) opts.hasPathSecret = true;
|
|
597
|
+
if (args.redactPathSecret) opts.redactPathSecret = args.redactPathSecret;
|
|
389
598
|
return fetchUrl(url, opts);
|
|
390
599
|
}
|
|
391
600
|
|
|
@@ -447,13 +656,106 @@ function checkResponseStatus(
|
|
|
447
656
|
);
|
|
448
657
|
}
|
|
449
658
|
|
|
659
|
+
/**
|
|
660
|
+
* Check a parsed 200 body for a declared present-only-on-error envelope
|
|
661
|
+
* element (`Operation.errorPath`). Resolution of anything other than
|
|
662
|
+
* `undefined` fails the call — presence is the signal, so `null`/""/`0`/
|
|
663
|
+
* `false` all fire (an empty XML element parses to "" and must not read as
|
|
664
|
+
* success); declared-absent is the API's not-an-error signal. Deliberately
|
|
665
|
+
* the inverse of hasMorePath's truthiness (where a RESOLVED falsy value is
|
|
666
|
+
* the stop signal).
|
|
667
|
+
*
|
|
668
|
+
* Generic capped stringify — no API-specific shape sniffing. Known secret
|
|
669
|
+
* values are scrubbed and the (already-redacted) request URL rides the
|
|
670
|
+
* error, same output-channel contract as checkResponseStatus.
|
|
671
|
+
*
|
|
672
|
+
* Placement (paginate loop): the very next statement after parseResponse —
|
|
673
|
+
* BEFORE totalCountPath extraction and both exhaustion breaks. An error page
|
|
674
|
+
* often misses itemsPath entirely (World Bank: error `[{"message":[…]}]` vs
|
|
675
|
+
* success `[meta, records]`), so a check after the breaks never fires — the
|
|
676
|
+
* walk exits with silent `items: []`.
|
|
677
|
+
*/
|
|
678
|
+
function checkErrorEnvelope(
|
|
679
|
+
data: unknown,
|
|
680
|
+
errorPath: string,
|
|
681
|
+
url: string | undefined,
|
|
682
|
+
secretValues?: string[],
|
|
683
|
+
): void {
|
|
684
|
+
const resolved = resolveJsonPath(data, errorPath);
|
|
685
|
+
if (resolved === undefined) return;
|
|
686
|
+
const scrubbed = scrubSecretValues(JSON.stringify(resolved), secretValues);
|
|
687
|
+
throw new HelperError(
|
|
688
|
+
"response",
|
|
689
|
+
`API error envelope at ${errorPath} (HTTP status was 200): ${scrubbed.slice(0, 500)}`,
|
|
690
|
+
`nothing at ${errorPath} (declared-absent = not an error)`,
|
|
691
|
+
undefined,
|
|
692
|
+
undefined,
|
|
693
|
+
url,
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/** Shared secret-handling prelude for both executors (restGet + paginate).
|
|
698
|
+
* Derives every store-secret-derived value the executors need — path-token
|
|
699
|
+
* fill, query assembly inputs, redaction inputs, and the merged header set —
|
|
700
|
+
* from the same inputs in the same way, so a hardening change to one
|
|
701
|
+
* executor can't silently miss the other. Security-critical: keep both
|
|
702
|
+
* executors on this one implementation. */
|
|
703
|
+
function buildExecutorEnv(
|
|
704
|
+
guide: ApiGuide,
|
|
705
|
+
params: Record<string, unknown>,
|
|
706
|
+
opts?: SecretAuthOpts,
|
|
707
|
+
) {
|
|
708
|
+
// Secret-owned path tokens (see splitPathSecretParams): the store fills
|
|
709
|
+
// them BELOW the agent params map — agent-supplied values are dropped.
|
|
710
|
+
const pathSecrets = opts?.secretPathParams ?? {};
|
|
711
|
+
const pathValues = Object.values(pathSecrets);
|
|
712
|
+
const hasPathSecrets = pathValues.length > 0;
|
|
713
|
+
const { fillParams, queryParamsForBuild } = splitPathSecretParams(
|
|
714
|
+
params,
|
|
715
|
+
pathSecrets,
|
|
716
|
+
);
|
|
717
|
+
// Secret query params are injected BELOW the agent-supplied map — never
|
|
718
|
+
// into it — so the returned `params` stays agent-supplied-only.
|
|
719
|
+
const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
|
|
720
|
+
const secretParams = opts?.secretQueryParams ?? {};
|
|
721
|
+
const hasQuerySecret = Object.keys(secretParams).length > 0;
|
|
722
|
+
// Redaction closure for cross-domain redirect hops — built here where
|
|
723
|
+
// the values are already in scope; the transport stays value-agnostic.
|
|
724
|
+
const redactPathSecret = hasPathSecrets
|
|
725
|
+
? (u: string) => redactSecretPathValues(u, pathValues)
|
|
726
|
+
: undefined;
|
|
727
|
+
// Merge store-injected secret headers with literal auth.headers. oauth2
|
|
728
|
+
// carries no literal headers (the resolved Bearer token arrives via
|
|
729
|
+
// opts.authHeaders).
|
|
730
|
+
const literalHeaders =
|
|
731
|
+
guide.auth.kind === "oauth2" ? undefined : guide.auth.headers;
|
|
732
|
+
const extraHeaders = { ...literalHeaders, ...opts?.authHeaders };
|
|
733
|
+
return {
|
|
734
|
+
fillParams,
|
|
735
|
+
queryParamsForBuild,
|
|
736
|
+
pathValues,
|
|
737
|
+
secretParamNames,
|
|
738
|
+
secretParams,
|
|
739
|
+
hasQuerySecret,
|
|
740
|
+
hasPathSecrets,
|
|
741
|
+
redactPathSecret,
|
|
742
|
+
extraHeaders,
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
450
746
|
// ═══════════════════════════════════════════════════════════════════
|
|
451
747
|
// restGet
|
|
452
748
|
// ═══════════════════════════════════════════════════════════════════
|
|
453
749
|
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
750
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
751
|
+
// Store-injected secret auth opts (single source of truth)
|
|
752
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
753
|
+
|
|
754
|
+
/** Store-injected auth opts, forwarded to the executor and reused by the
|
|
755
|
+
* caller for the output-channel audit (secret scrub). Declared once here;
|
|
756
|
+
* RestGetOptions / PaginateOptions / resolve-op's AuthOpts extend it so a
|
|
757
|
+
* producer-side field can't be silently dropped at the executor boundary. */
|
|
758
|
+
export interface SecretAuthOpts {
|
|
457
759
|
/** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
|
|
458
760
|
authHeaders?: Record<string, string>;
|
|
459
761
|
/** Lowercased injected header names — stripped on cross-domain redirects. */
|
|
@@ -464,6 +766,17 @@ export interface RestGetOptions {
|
|
|
464
766
|
secretQueryParams?: Record<string, string>;
|
|
465
767
|
/** The injected query-param names — redacted from every surfaced URL. */
|
|
466
768
|
secretQueryParamNames?: Set<string>;
|
|
769
|
+
/** Store-injected path tokens (kind: static-key secretPathRefs) — pathTokenName → resolved value. Fills {name} in the op path below the agent params map. */
|
|
770
|
+
secretPathParams?: Record<string, string>;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
export interface RestGetOptions extends SecretAuthOpts {
|
|
774
|
+
/** Skip cache — force fresh fetch. */
|
|
775
|
+
fresh?: boolean;
|
|
776
|
+
/** Built-in post-response transform, applied when op.transform === true. */
|
|
777
|
+
transformFn?: TransformFn | undefined;
|
|
778
|
+
/** Guide directory name — transform context domain / helper routing. */
|
|
779
|
+
dirName?: string | undefined;
|
|
467
780
|
}
|
|
468
781
|
|
|
469
782
|
/**
|
|
@@ -487,33 +800,43 @@ export async function restGet(
|
|
|
487
800
|
params: Record<string, unknown>,
|
|
488
801
|
guide: ApiGuide,
|
|
489
802
|
opts?: RestGetOptions,
|
|
490
|
-
transformFn?: TransformFn,
|
|
491
|
-
dirName?: string,
|
|
492
803
|
): Promise<RestGetResult> {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
804
|
+
const {
|
|
805
|
+
fillParams,
|
|
806
|
+
queryParamsForBuild,
|
|
807
|
+
pathValues,
|
|
808
|
+
secretParamNames,
|
|
809
|
+
secretParams,
|
|
810
|
+
hasQuerySecret,
|
|
811
|
+
hasPathSecrets,
|
|
812
|
+
redactPathSecret,
|
|
813
|
+
extraHeaders,
|
|
814
|
+
} = buildExecutorEnv(guide, params, opts);
|
|
815
|
+
|
|
816
|
+
// Steps 1/2: fill path, build query (agent-supplied only — secret
|
|
817
|
+
// param names are excluded, incl. from the passthrough branch).
|
|
818
|
+
const resolvedPath = fillPathStrict(operation.path, fillParams);
|
|
819
|
+
const query = buildQueryParams(
|
|
820
|
+
operation,
|
|
821
|
+
queryParamsForBuild,
|
|
822
|
+
secretParamNames,
|
|
823
|
+
);
|
|
498
824
|
|
|
499
825
|
// 3. Auth dispatch.
|
|
500
826
|
checkAuth(guide.auth);
|
|
501
827
|
|
|
502
|
-
//
|
|
503
|
-
//
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
//
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
...secretParams,
|
|
515
|
-
});
|
|
516
|
-
const url = redactSecretParams(fetchUrlRaw, secretParamNames);
|
|
828
|
+
// 4. Build URL. The fetch uses the raw URL; every surfaced copy
|
|
829
|
+
// (result.url, the URL stored on HelperError.url) is redacted. Path
|
|
830
|
+
// secrets redact via redactSecretPathValues (value replace, raw +
|
|
831
|
+
// both hex forms); they ride the path, not the query, so
|
|
832
|
+
// redactSecretParams alone can't touch them.
|
|
833
|
+
const fetchUrlRaw = buildUrl(
|
|
834
|
+
apiHost,
|
|
835
|
+
resolvedPath,
|
|
836
|
+
{ ...query, ...secretParams },
|
|
837
|
+
operation.params,
|
|
838
|
+
);
|
|
839
|
+
const url = redactSurfacedUrl(fetchUrlRaw, secretParamNames, pathValues);
|
|
517
840
|
|
|
518
841
|
// 5. Build Accept header — json/xml shorthands expand; everything
|
|
519
842
|
// else passes through as-is (e.g. application/atom+xml, */*).
|
|
@@ -523,16 +846,17 @@ export async function restGet(
|
|
|
523
846
|
// for servers that omit a Content-Type charset (e.g. legacy Latin-1
|
|
524
847
|
// APIs); an explicit header charset always wins.
|
|
525
848
|
const shape = operation.parse ?? guide.responseShape;
|
|
526
|
-
const result = await fetchWithOpts(
|
|
527
|
-
fetchUrlRaw,
|
|
849
|
+
const result = await fetchWithOpts(fetchUrlRaw, {
|
|
528
850
|
accept,
|
|
529
|
-
opts?.fresh,
|
|
530
851
|
extraHeaders,
|
|
531
|
-
|
|
532
|
-
shape.charset,
|
|
533
|
-
opts?.secretHeaderNames,
|
|
852
|
+
fresh: opts?.fresh,
|
|
853
|
+
fallbackCharset: shape.charset,
|
|
854
|
+
secretHeaderNames: opts?.secretHeaderNames,
|
|
534
855
|
hasQuerySecret,
|
|
535
|
-
|
|
856
|
+
secretQueryParamNames: opts?.secretQueryParamNames,
|
|
857
|
+
hasPathSecret: hasPathSecrets,
|
|
858
|
+
redactPathSecret,
|
|
859
|
+
});
|
|
536
860
|
|
|
537
861
|
// 7. Check HTTP status before attempting to parse the body.
|
|
538
862
|
// This turns "Invalid JSON response: <?xml..." into a clean
|
|
@@ -545,17 +869,23 @@ export async function restGet(
|
|
|
545
869
|
// 8. Parse response using the effective shape resolved above.
|
|
546
870
|
let data = parseResponse(result.body, shape);
|
|
547
871
|
|
|
872
|
+
// 8b. 200-with-error-envelope check (op.errorPath) — post-parse,
|
|
873
|
+
// pre-transform: the error envelope is the raw parsed shape.
|
|
874
|
+
if (operation.errorPath !== undefined) {
|
|
875
|
+
checkErrorEnvelope(data, operation.errorPath, url, opts?.secretValues);
|
|
876
|
+
}
|
|
877
|
+
|
|
548
878
|
// 9. Post-response transform (optional). When api-fetch supplied a
|
|
549
879
|
// `transformFn` (op.transform === true), apply it. A throwing transform is
|
|
550
880
|
// caught: keep the raw `data` and carry a `transformWarning` so the caller
|
|
551
881
|
// can surface "⚠ Transform failed:" — the op is NOT disabled, so a
|
|
552
882
|
// subsequent call re-attempts the transform.
|
|
553
883
|
let transformWarning: string | undefined;
|
|
554
|
-
if (transformFn) {
|
|
884
|
+
if (opts?.transformFn) {
|
|
555
885
|
try {
|
|
556
|
-
data = transformFn(data, {
|
|
886
|
+
data = opts.transformFn(data, {
|
|
557
887
|
operation: operation.name,
|
|
558
|
-
domain: dirName ?? "",
|
|
888
|
+
domain: opts.dirName ?? "",
|
|
559
889
|
});
|
|
560
890
|
} catch (err) {
|
|
561
891
|
transformWarning = err instanceof Error ? err.message : String(err);
|
|
@@ -568,6 +898,7 @@ export async function restGet(
|
|
|
568
898
|
url,
|
|
569
899
|
params: query,
|
|
570
900
|
...(transformWarning === undefined ? {} : { transformWarning }),
|
|
901
|
+
...(result.cached ? { cached: true } : {}),
|
|
571
902
|
};
|
|
572
903
|
}
|
|
573
904
|
|
|
@@ -575,7 +906,7 @@ export async function restGet(
|
|
|
575
906
|
// paginate
|
|
576
907
|
// ═══════════════════════════════════════════════════════════════════
|
|
577
908
|
|
|
578
|
-
export interface PaginateOptions {
|
|
909
|
+
export interface PaginateOptions extends SecretAuthOpts {
|
|
579
910
|
/** When true, gather items up to `gatherAllMax`. Default false. */
|
|
580
911
|
gatherAll?: boolean;
|
|
581
912
|
/** Max items to gather when `gatherAll` is true. Overrides guide/operation default. */
|
|
@@ -584,16 +915,10 @@ export interface PaginateOptions {
|
|
|
584
915
|
fresh?: boolean;
|
|
585
916
|
/** Bypass the nextLink SSRF guard (for testing against local servers). */
|
|
586
917
|
skipSsrfGuard?: boolean;
|
|
587
|
-
/**
|
|
588
|
-
|
|
589
|
-
/**
|
|
590
|
-
|
|
591
|
-
/** Store-injected secret values — scrubbed from error bodies (output-channel audit). */
|
|
592
|
-
secretValues?: string[];
|
|
593
|
-
/** Store-injected secret query params — appended below the agent params map. */
|
|
594
|
-
secretQueryParams?: Record<string, string>;
|
|
595
|
-
/** The injected query-param names — redacted from every surfaced URL. */
|
|
596
|
-
secretQueryParamNames?: Set<string>;
|
|
918
|
+
/** Built-in per-item transform, applied when op.transform === true. */
|
|
919
|
+
transformFn?: TransformFn | undefined;
|
|
920
|
+
/** Guide directory name — transform context domain / helper routing. */
|
|
921
|
+
dirName?: string | undefined;
|
|
597
922
|
}
|
|
598
923
|
|
|
599
924
|
/**
|
|
@@ -615,8 +940,6 @@ export async function paginate(
|
|
|
615
940
|
params: Record<string, unknown>,
|
|
616
941
|
guide: ApiGuide,
|
|
617
942
|
opts?: PaginateOptions,
|
|
618
|
-
transformFn?: TransformFn,
|
|
619
|
-
dirName?: string,
|
|
620
943
|
): Promise<PaginateResult> {
|
|
621
944
|
const pagCfg = operation.pagination ?? guide.pagination;
|
|
622
945
|
if (!pagCfg) {
|
|
@@ -644,10 +967,17 @@ export async function paginate(
|
|
|
644
967
|
// Auth dispatch — checked once up front (auth is constant per guide).
|
|
645
968
|
checkAuth(guide.auth);
|
|
646
969
|
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
970
|
+
const {
|
|
971
|
+
fillParams,
|
|
972
|
+
queryParamsForBuild,
|
|
973
|
+
pathValues,
|
|
974
|
+
secretParamNames,
|
|
975
|
+
secretParams,
|
|
976
|
+
hasQuerySecret,
|
|
977
|
+
hasPathSecrets,
|
|
978
|
+
redactPathSecret,
|
|
979
|
+
extraHeaders,
|
|
980
|
+
} = buildExecutorEnv(guide, params, opts);
|
|
651
981
|
|
|
652
982
|
// State for the styles.
|
|
653
983
|
let cursor: string | undefined;
|
|
@@ -678,8 +1008,11 @@ export async function paginate(
|
|
|
678
1008
|
|
|
679
1009
|
// Compute effective params once — used for both per-page building and result transparency.
|
|
680
1010
|
// Agent-supplied only (secret param names excluded, incl. passthrough).
|
|
681
|
-
const
|
|
682
|
-
|
|
1011
|
+
const effectiveParams = buildQueryParams(
|
|
1012
|
+
operation,
|
|
1013
|
+
queryParamsForBuild,
|
|
1014
|
+
secretParamNames,
|
|
1015
|
+
);
|
|
683
1016
|
|
|
684
1017
|
// Resolve the effective page size once for the seeding styles — the
|
|
685
1018
|
// caller's value, else the op's declared default (both already folded into
|
|
@@ -696,21 +1029,36 @@ export async function paginate(
|
|
|
696
1029
|
effectivePageSize =
|
|
697
1030
|
rawSize === undefined ? (pagCfg.pageSize ?? 50) : Number(rawSize);
|
|
698
1031
|
if (isNaN(effectivePageSize)) effectivePageSize = 50;
|
|
1032
|
+
} else if (style === "cursor") {
|
|
1033
|
+
// Terminal fallback for cursor is OMIT (server default applies) — no
|
|
1034
|
+
// fabricated 50 like offset-limit (which needs a real number to advance
|
|
1035
|
+
// row offsets; cursor's position comes from the response cursor). Seed
|
|
1036
|
+
// effectiveParams (not pageParams — rebuilt per iteration) so
|
|
1037
|
+
// result.params stays honest about what was sent.
|
|
1038
|
+
if (
|
|
1039
|
+
pagCfg.pageSizeParam !== undefined &&
|
|
1040
|
+
pagCfg.pageSize !== undefined &&
|
|
1041
|
+
params[pagCfg.pageSizeParam] === undefined &&
|
|
1042
|
+
effectiveParams[pagCfg.pageSizeParam] === undefined
|
|
1043
|
+
) {
|
|
1044
|
+
effectiveParams[pagCfg.pageSizeParam] = String(pagCfg.pageSize);
|
|
1045
|
+
}
|
|
699
1046
|
}
|
|
700
|
-
// Secret query params injected below the agent map on every page's fetch URL.
|
|
701
|
-
const secretParams = opts?.secretQueryParams ?? {};
|
|
702
|
-
const hasQuerySecret = Object.keys(secretParams).length > 0;
|
|
703
1047
|
const urls: string[] = [];
|
|
704
1048
|
|
|
705
1049
|
while (true) {
|
|
706
|
-
// Build per-page params.
|
|
707
|
-
|
|
1050
|
+
// Build per-page params. Keyed supersession: pagination/tokenBag
|
|
1051
|
+
// writes below REPLACE same-named base values via plain overwrite —
|
|
1052
|
+
// only genuinely multi-value (listStyle) keys hold arrays, and the
|
|
1053
|
+
// parse-time collision guard guarantees those never collide with a
|
|
1054
|
+
// pagination/tokenBag wire name, so every write here is a scalar.
|
|
1055
|
+
const pageParams: Record<string, string | string[]> = {};
|
|
708
1056
|
for (const [key, val] of Object.entries(effectiveParams)) {
|
|
709
1057
|
pageParams[key] = val;
|
|
710
1058
|
}
|
|
711
1059
|
|
|
712
1060
|
if (style === "offset-limit" || style === "page") {
|
|
713
|
-
pageParams[pagCfg.pageParam!] = String(page
|
|
1061
|
+
pageParams[pagCfg.pageParam!] = String(page);
|
|
714
1062
|
// effectivePageSize is always resolved (a number) in this branch.
|
|
715
1063
|
if (pagCfg.pageSizeParam) {
|
|
716
1064
|
pageParams[pagCfg.pageSizeParam] = String(effectivePageSize);
|
|
@@ -724,7 +1072,7 @@ export async function paginate(
|
|
|
724
1072
|
}
|
|
725
1073
|
|
|
726
1074
|
// Build URL.
|
|
727
|
-
const resolvedPath = fillPathStrict(operation.path,
|
|
1075
|
+
const resolvedPath = fillPathStrict(operation.path, fillParams);
|
|
728
1076
|
|
|
729
1077
|
let url: string;
|
|
730
1078
|
if (style === "nextLink" && nextUrl) {
|
|
@@ -734,15 +1082,18 @@ export async function paginate(
|
|
|
734
1082
|
: new URL(nextUrl, apiHost).toString();
|
|
735
1083
|
} else {
|
|
736
1084
|
// Append secret query params below the agent-supplied page params.
|
|
737
|
-
url = buildUrl(
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
1085
|
+
url = buildUrl(
|
|
1086
|
+
apiHost,
|
|
1087
|
+
resolvedPath,
|
|
1088
|
+
{ ...pageParams, ...secretParams },
|
|
1089
|
+
operation.params,
|
|
1090
|
+
);
|
|
741
1091
|
}
|
|
742
1092
|
|
|
743
1093
|
// Every surfaced URL (incl. a server-supplied nextUrl that may
|
|
744
|
-
// already carry the secret) is redacted at the capture point
|
|
745
|
-
|
|
1094
|
+
// already carry the secret) is redacted at the capture point — query
|
|
1095
|
+
// params by name, path tokens by value.
|
|
1096
|
+
urls.push(redactSurfacedUrl(url, secretParamNames, pathValues));
|
|
746
1097
|
|
|
747
1098
|
// NextLink guard — the URL comes from the remote server, so this is
|
|
748
1099
|
// the one place SSRF protection is load-bearing. `guardThisFetch`
|
|
@@ -755,7 +1106,9 @@ export async function paginate(
|
|
|
755
1106
|
if (guardThisFetch) {
|
|
756
1107
|
const guard = ssrfGuard(url);
|
|
757
1108
|
if (!guard.ok) {
|
|
758
|
-
|
|
1109
|
+
// The SSRF-block error's errUrl is built separately from the other
|
|
1110
|
+
// surfaced URLs — redact it the same way (query by name, path by value).
|
|
1111
|
+
const errUrl = redactSurfacedUrl(url, secretParamNames, pathValues);
|
|
759
1112
|
throw new HelperError(
|
|
760
1113
|
"url",
|
|
761
1114
|
`URL blocked during pagination: ${guard.reason}`,
|
|
@@ -768,34 +1121,48 @@ export async function paginate(
|
|
|
768
1121
|
}
|
|
769
1122
|
|
|
770
1123
|
// Fetch.
|
|
771
|
-
const result = await fetchWithOpts(
|
|
772
|
-
url,
|
|
1124
|
+
const result = await fetchWithOpts(url, {
|
|
773
1125
|
accept,
|
|
774
|
-
opts?.fresh,
|
|
775
1126
|
extraHeaders,
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
1127
|
+
fresh: opts?.fresh,
|
|
1128
|
+
guardRedirects: guardThisFetch,
|
|
1129
|
+
fallbackCharset: shape.charset,
|
|
1130
|
+
secretHeaderNames: opts?.secretHeaderNames,
|
|
779
1131
|
hasQuerySecret,
|
|
780
|
-
|
|
1132
|
+
secretQueryParamNames: opts?.secretQueryParamNames,
|
|
1133
|
+
hasPathSecret: hasPathSecrets,
|
|
1134
|
+
redactPathSecret,
|
|
1135
|
+
});
|
|
781
1136
|
|
|
782
1137
|
// Check HTTP status before attempting to parse. Secret values scrubbed
|
|
783
1138
|
// from the error excerpt (output-channel audit). The URL stored on
|
|
784
1139
|
// the error object is redacted, computed upstream of checkResponseStatus.
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
opts?.secretValues,
|
|
788
|
-
);
|
|
1140
|
+
const redactedPageUrl = redactSurfacedUrl(url, secretParamNames, pathValues);
|
|
1141
|
+
checkResponseStatus({ ...result, url: redactedPageUrl }, opts?.secretValues);
|
|
789
1142
|
|
|
790
1143
|
// Parse.
|
|
791
1144
|
const data = parseResponse(result.body, shape);
|
|
792
1145
|
|
|
793
|
-
//
|
|
794
|
-
//
|
|
795
|
-
//
|
|
796
|
-
//
|
|
797
|
-
//
|
|
798
|
-
|
|
1146
|
+
// 200-with-error-envelope check (op.errorPath) — placement pin: the
|
|
1147
|
+
// very next statement after parseResponse, BEFORE the totalCountPath
|
|
1148
|
+
// extraction and both exhaustion breaks below. An error page often
|
|
1149
|
+
// misses itemsPath entirely, so a check after the breaks never fires
|
|
1150
|
+
// (the walk exits with silent items: []).
|
|
1151
|
+
if (operation.errorPath !== undefined) {
|
|
1152
|
+
checkErrorEnvelope(
|
|
1153
|
+
data,
|
|
1154
|
+
operation.errorPath,
|
|
1155
|
+
redactedPageUrl,
|
|
1156
|
+
opts?.secretValues,
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
// Extract the server's reported total from the first page that resolves
|
|
1161
|
+
// one — before the empty-page break below, so a zero-result page that
|
|
1162
|
+
// still carries the count (e.g. `total_count: 0`) surfaces it rather
|
|
1163
|
+
// than losing it to the early `break`. Accepts a number directly or a
|
|
1164
|
+
// numeric string (coerced via Number()); a page that misses the path
|
|
1165
|
+
// leaves it undefined and later pages can still supply it.
|
|
799
1166
|
if (serverTotal === undefined && pagCfg.totalCountPath) {
|
|
800
1167
|
const raw = resolveJsonPath(data, pagCfg.totalCountPath);
|
|
801
1168
|
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
@@ -827,12 +1194,12 @@ export async function paginate(
|
|
|
827
1194
|
? pageItems.slice(0, remaining)
|
|
828
1195
|
: pageItems;
|
|
829
1196
|
for (const item of toProcess) {
|
|
830
|
-
if (transformFn) {
|
|
1197
|
+
if (opts?.transformFn) {
|
|
831
1198
|
try {
|
|
832
1199
|
items.push(
|
|
833
|
-
transformFn(item, {
|
|
1200
|
+
opts.transformFn(item, {
|
|
834
1201
|
operation: operation.name,
|
|
835
|
-
domain: dirName ?? "",
|
|
1202
|
+
domain: opts.dirName ?? "",
|
|
836
1203
|
}),
|
|
837
1204
|
);
|
|
838
1205
|
} catch {
|
|
@@ -857,6 +1224,17 @@ export async function paginate(
|
|
|
857
1224
|
break;
|
|
858
1225
|
}
|
|
859
1226
|
|
|
1227
|
+
// hasMorePath done-flag (style-agnostic).
|
|
1228
|
+
// Sits after the ceiling checks so ceilingHit still wins when both fire
|
|
1229
|
+
// on the same page. The undefined carve-out is fail-open: a missing or
|
|
1230
|
+
// typo'd path never stops the walk (pre-existing exhaustion semantics
|
|
1231
|
+
// apply); a RESOLVED falsy value stops cleanly. Plain truthiness, no
|
|
1232
|
+
// coercion — the string "false" advances by design.
|
|
1233
|
+
if (pagCfg.hasMorePath !== undefined) {
|
|
1234
|
+
const v = resolveJsonPath(data, pagCfg.hasMorePath);
|
|
1235
|
+
if (v !== undefined && !v) break;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
860
1238
|
// Determine next page.
|
|
861
1239
|
const advanced = advancePagination(
|
|
862
1240
|
style,
|
|
@@ -930,13 +1308,20 @@ function advancePagination(
|
|
|
930
1308
|
}
|
|
931
1309
|
|
|
932
1310
|
if (style === "cursor") {
|
|
933
|
-
|
|
1311
|
+
// Numeric cursors coerce to strings (tokenBag-style) BEFORE the
|
|
1312
|
+
// type/falsy check — a numeric 0 must advance like string "0", not die
|
|
1313
|
+
// at !next. nextLink stays string-strict (a numeric "next URL" is
|
|
1314
|
+
// garbage); booleans/objects don't coerce.
|
|
1315
|
+
const raw = resolveJsonPath(data, cfg.cursorPath!);
|
|
1316
|
+
const next = typeof raw === "number" ? String(raw) : raw;
|
|
934
1317
|
if (!next || typeof next !== "string") return null;
|
|
935
1318
|
return { cursor: next };
|
|
936
1319
|
}
|
|
937
1320
|
|
|
938
1321
|
if (style === "resumptionToken") {
|
|
939
|
-
|
|
1322
|
+
// No !next guard here by design — "" and missing are exhaustion.
|
|
1323
|
+
const raw = resolveJsonPath(data, cfg.tokenPath!);
|
|
1324
|
+
const t = typeof raw === "number" ? String(raw) : raw; // coercion, before the check
|
|
940
1325
|
if (typeof t !== "string" || t === "") return null;
|
|
941
1326
|
return { token: t };
|
|
942
1327
|
}
|
|
@@ -951,8 +1336,10 @@ function advancePagination(
|
|
|
951
1336
|
for (const key of cfg.continuationParams ?? []) {
|
|
952
1337
|
const v = resolveJsonPath(data, key);
|
|
953
1338
|
if (v === undefined || v === null) continue;
|
|
954
|
-
|
|
955
|
-
|
|
1339
|
+
// Wire param = wireParamName (last dot segment, bracket dress
|
|
1340
|
+
// stripped — shared with the parser's listStyle collision guard so
|
|
1341
|
+
// the derivation exists once).
|
|
1342
|
+
collected[wireParamName(key)] = String(v);
|
|
956
1343
|
}
|
|
957
1344
|
return Object.keys(collected).length > 0 ? { tokenBag: collected } : null;
|
|
958
1345
|
}
|