pi-lean-host 0.4.0 → 0.6.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/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 { fillPathTemplate, joinUrl } from "./path-template.js";
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
- params: Record<string, string>;
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
- params: Record<string, string>;
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 serialization.
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
- // Nested objects/arrays serialize as JSON so structured query
167
- // params (e.g. BOE's ES query_string DSL) reach the wire as
168
- // JSON, not `[object Object]`. Scalars stay as String(val).
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
- query[key] =
213
- typeof v === "object" && v !== null ? JSON.stringify(v) : String(v);
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`, `$.items` prefix.
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
- // Normalise: strip leading $ or $., convert bracket notation.
250
- const normalised = path
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;
@@ -259,10 +372,13 @@ export function resolveJsonPath(obj: unknown, path: string): unknown {
259
372
  if (current === null || typeof current !== "object") return undefined;
260
373
  if (Array.isArray(current)) {
261
374
  const idx = parseInt(part, 10);
262
- if (isNaN(idx)) return undefined;
263
- current = current[idx];
375
+ if (Number.isNaN(idx)) return undefined;
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]; // nosemgrep: javascript.lang.security.audit.prototype-pollution.prototype-pollution-loop.prototype-pollution-loop
264
380
  } else {
265
- current = (current as Record<string, unknown>)[part];
381
+ current = (current as Record<string, unknown>)[part]; // nosemgrep: javascript.lang.security.audit.prototype-pollution.prototype-pollution-loop.prototype-pollution-loop
266
382
  }
267
383
  }
268
384
  return current;
@@ -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
- return joinUrl(apiHost, resolvedPath, new URLSearchParams(query).toString());
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
- const kind = auth.kind;
357
- if (kind === "none" || kind === "static-key") return;
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
- // oauth2 — unrealized seam. A parsed guide can't reach here (oauth2 is
360
- // rejected at parse), but guard for hand-constructed guides/tests.
361
- throw new HelperError(
362
- "auth.kind",
363
- `Auth kind "${kind}" is not supported in this version`,
364
- "one of: none | static-key",
365
- kind,
366
- "OAuth2 is not yet implemented. Use kind: none or kind: static-key.",
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
- * Helper to conditionally include `fresh` in FetchOptions (exactOptionalPropertyTypes).
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
- accept: string,
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 = { headers: { accept, ...extraHeaders } };
384
- if (fresh !== undefined) opts.fresh = fresh;
385
- if (guardRedirects) opts.guardRedirects = true;
386
- if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
387
- if (secretHeaderNames) opts.secretHeaderNames = secretHeaderNames;
388
- if (hasQuerySecret) opts.hasQuerySecret = true;
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,115 @@ 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
+ // Shared fetch-args base: the env-owned slice of the FetchWithOptsArgs
734
+ // literal, assembled once so a new secret channel can't be wired into one
735
+ // executor and missed in the other. Callers add the situational fields
736
+ // (accept, fresh, guardRedirects, fallbackCharset).
737
+ const baseFetchArgs: Omit<FetchWithOptsArgs, "accept"> = {
738
+ extraHeaders,
739
+ secretHeaderNames: opts?.secretHeaderNames,
740
+ hasQuerySecret,
741
+ secretQueryParamNames: opts?.secretQueryParamNames,
742
+ hasPathSecret: hasPathSecrets,
743
+ redactPathSecret,
744
+ };
745
+ return {
746
+ fillParams,
747
+ queryParamsForBuild,
748
+ pathValues,
749
+ secretParamNames,
750
+ secretParams,
751
+ baseFetchArgs,
752
+ };
753
+ }
754
+
450
755
  // ═══════════════════════════════════════════════════════════════════
451
756
  // restGet
452
757
  // ═══════════════════════════════════════════════════════════════════
453
758
 
454
- export interface RestGetOptions {
455
- /** Skip cache — force fresh fetch. */
456
- fresh?: boolean;
759
+ // ═══════════════════════════════════════════════════════════════════
760
+ // Store-injected secret auth opts (single source of truth)
761
+ // ═══════════════════════════════════════════════════════════════════
762
+
763
+ /** Store-injected auth opts, forwarded to the executor and reused by the
764
+ * caller for the output-channel audit (secret scrub). Declared once here;
765
+ * RestGetOptions / PaginateOptions / resolve-op's AuthOpts extend it so a
766
+ * producer-side field can't be silently dropped at the executor boundary. */
767
+ export interface SecretAuthOpts {
457
768
  /** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
458
769
  authHeaders?: Record<string, string>;
459
770
  /** Lowercased injected header names — stripped on cross-domain redirects. */
@@ -464,6 +775,17 @@ export interface RestGetOptions {
464
775
  secretQueryParams?: Record<string, string>;
465
776
  /** The injected query-param names — redacted from every surfaced URL. */
466
777
  secretQueryParamNames?: Set<string>;
778
+ /** Store-injected path tokens (kind: static-key secretPathRefs) — pathTokenName → resolved value. Fills {name} in the op path below the agent params map. */
779
+ secretPathParams?: Record<string, string>;
780
+ }
781
+
782
+ export interface RestGetOptions extends SecretAuthOpts {
783
+ /** Skip cache — force fresh fetch. */
784
+ fresh?: boolean;
785
+ /** Built-in post-response transform, applied when op.transform === true. */
786
+ transformFn?: TransformFn | undefined;
787
+ /** Guide directory name — transform context domain / helper routing. */
788
+ dirName?: string | undefined;
467
789
  }
468
790
 
469
791
  /**
@@ -487,33 +809,40 @@ export async function restGet(
487
809
  params: Record<string, unknown>,
488
810
  guide: ApiGuide,
489
811
  opts?: RestGetOptions,
490
- transformFn?: TransformFn,
491
- dirName?: string,
492
812
  ): Promise<RestGetResult> {
493
- // Steps 1/2 unchanged: fill path, build query (agent-supplied only —
494
- // secret param names are excluded, incl. from the passthrough branch).
495
- const resolvedPath = fillPathStrict(operation.path, params);
496
- const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
497
- const query = buildQueryParams(operation, params, secretParamNames);
813
+ const {
814
+ fillParams,
815
+ queryParamsForBuild,
816
+ pathValues,
817
+ secretParamNames,
818
+ secretParams,
819
+ baseFetchArgs,
820
+ } = buildExecutorEnv(guide, params, opts);
821
+
822
+ // Steps 1/2: fill path, build query (agent-supplied only — secret
823
+ // param names are excluded, incl. from the passthrough branch).
824
+ const resolvedPath = fillPathStrict(operation.path, fillParams);
825
+ const query = buildQueryParams(
826
+ operation,
827
+ queryParamsForBuild,
828
+ secretParamNames,
829
+ );
498
830
 
499
831
  // 3. Auth dispatch.
500
832
  checkAuth(guide.auth);
501
833
 
502
- // Merge store-injected secret headers with literal auth.headers. The
503
- // injected names are tracked for cross-domain redirect stripping.
504
- const extraHeaders = { ...guide.auth.headers, ...opts?.authHeaders };
505
-
506
- // 4. Build URL. Secret query params are injected BELOW the
507
- // agent-supplied map — never into it — so the returned `params` stays
508
- // agent-supplied-only. The fetch uses the raw URL; every surfaced copy
509
- // (result.url, the URL stored on HelperError.url) is redacted.
510
- const secretParams = opts?.secretQueryParams ?? {};
511
- const hasQuerySecret = Object.keys(secretParams).length > 0;
512
- const fetchUrlRaw = buildUrl(apiHost, resolvedPath, {
513
- ...query,
514
- ...secretParams,
515
- });
516
- const url = redactSecretParams(fetchUrlRaw, secretParamNames);
834
+ // 4. Build URL. The fetch uses the raw URL; every surfaced copy
835
+ // (result.url, the URL stored on HelperError.url) is redacted. Path
836
+ // secrets redact via redactSecretPathValues (value replace, raw +
837
+ // both hex forms); they ride the path, not the query, so
838
+ // redactSecretParams alone can't touch them.
839
+ const fetchUrlRaw = buildUrl(
840
+ apiHost,
841
+ resolvedPath,
842
+ { ...query, ...secretParams },
843
+ operation.params,
844
+ );
845
+ const url = redactSurfacedUrl(fetchUrlRaw, secretParamNames, pathValues);
517
846
 
518
847
  // 5. Build Accept header — json/xml shorthands expand; everything
519
848
  // else passes through as-is (e.g. application/atom+xml, */*).
@@ -523,16 +852,12 @@ export async function restGet(
523
852
  // for servers that omit a Content-Type charset (e.g. legacy Latin-1
524
853
  // APIs); an explicit header charset always wins.
525
854
  const shape = operation.parse ?? guide.responseShape;
526
- const result = await fetchWithOpts(
527
- fetchUrlRaw,
855
+ const result = await fetchWithOpts(fetchUrlRaw, {
856
+ ...baseFetchArgs,
528
857
  accept,
529
- opts?.fresh,
530
- extraHeaders,
531
- undefined,
532
- shape.charset,
533
- opts?.secretHeaderNames,
534
- hasQuerySecret,
535
- );
858
+ fresh: opts?.fresh,
859
+ fallbackCharset: shape.charset,
860
+ });
536
861
 
537
862
  // 7. Check HTTP status before attempting to parse the body.
538
863
  // This turns "Invalid JSON response: <?xml..." into a clean
@@ -545,17 +870,23 @@ export async function restGet(
545
870
  // 8. Parse response using the effective shape resolved above.
546
871
  let data = parseResponse(result.body, shape);
547
872
 
873
+ // 8b. 200-with-error-envelope check (op.errorPath) — post-parse,
874
+ // pre-transform: the error envelope is the raw parsed shape.
875
+ if (operation.errorPath !== undefined) {
876
+ checkErrorEnvelope(data, operation.errorPath, url, opts?.secretValues);
877
+ }
878
+
548
879
  // 9. Post-response transform (optional). When api-fetch supplied a
549
880
  // `transformFn` (op.transform === true), apply it. A throwing transform is
550
881
  // caught: keep the raw `data` and carry a `transformWarning` so the caller
551
882
  // can surface "⚠ Transform failed:" — the op is NOT disabled, so a
552
883
  // subsequent call re-attempts the transform.
553
884
  let transformWarning: string | undefined;
554
- if (transformFn) {
885
+ if (opts?.transformFn) {
555
886
  try {
556
- data = transformFn(data, {
887
+ data = opts.transformFn(data, {
557
888
  operation: operation.name,
558
- domain: dirName ?? "",
889
+ domain: opts.dirName ?? "",
559
890
  });
560
891
  } catch (err) {
561
892
  transformWarning = err instanceof Error ? err.message : String(err);
@@ -568,6 +899,7 @@ export async function restGet(
568
899
  url,
569
900
  params: query,
570
901
  ...(transformWarning === undefined ? {} : { transformWarning }),
902
+ ...(result.cached ? { cached: true } : {}),
571
903
  };
572
904
  }
573
905
 
@@ -575,7 +907,7 @@ export async function restGet(
575
907
  // paginate
576
908
  // ═══════════════════════════════════════════════════════════════════
577
909
 
578
- export interface PaginateOptions {
910
+ export interface PaginateOptions extends SecretAuthOpts {
579
911
  /** When true, gather items up to `gatherAllMax`. Default false. */
580
912
  gatherAll?: boolean;
581
913
  /** Max items to gather when `gatherAll` is true. Overrides guide/operation default. */
@@ -584,16 +916,10 @@ export interface PaginateOptions {
584
916
  fresh?: boolean;
585
917
  /** Bypass the nextLink SSRF guard (for testing against local servers). */
586
918
  skipSsrfGuard?: boolean;
587
- /** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
588
- authHeaders?: Record<string, string>;
589
- /** Lowercased injected header names — stripped on cross-domain redirects. */
590
- secretHeaderNames?: Set<string>;
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>;
919
+ /** Built-in per-item transform, applied when op.transform === true. */
920
+ transformFn?: TransformFn | undefined;
921
+ /** Guide directory name — transform context domain / helper routing. */
922
+ dirName?: string | undefined;
597
923
  }
598
924
 
599
925
  /**
@@ -615,8 +941,6 @@ export async function paginate(
615
941
  params: Record<string, unknown>,
616
942
  guide: ApiGuide,
617
943
  opts?: PaginateOptions,
618
- transformFn?: TransformFn,
619
- dirName?: string,
620
944
  ): Promise<PaginateResult> {
621
945
  const pagCfg = operation.pagination ?? guide.pagination;
622
946
  if (!pagCfg) {
@@ -644,10 +968,14 @@ export async function paginate(
644
968
  // Auth dispatch — checked once up front (auth is constant per guide).
645
969
  checkAuth(guide.auth);
646
970
 
647
- // Merge store-injected secret headers with literal auth.headers once,
648
- // reused for every page. Injected names are tracked for cross-domain
649
- // redirect stripping.
650
- const extraHeaders = { ...guide.auth.headers, ...opts?.authHeaders };
971
+ const {
972
+ fillParams,
973
+ queryParamsForBuild,
974
+ pathValues,
975
+ secretParamNames,
976
+ secretParams,
977
+ baseFetchArgs,
978
+ } = buildExecutorEnv(guide, params, opts);
651
979
 
652
980
  // State for the styles.
653
981
  let cursor: string | undefined;
@@ -673,13 +1001,16 @@ export async function paginate(
673
1001
  operation.params[pagCfg.pageParam!]?.default ??
674
1002
  fallback;
675
1003
  page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
676
- if (isNaN(page)) page = fallback;
1004
+ if (Number.isNaN(page)) page = fallback;
677
1005
  }
678
1006
 
679
1007
  // Compute effective params once — used for both per-page building and result transparency.
680
1008
  // Agent-supplied only (secret param names excluded, incl. passthrough).
681
- const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
682
- const effectiveParams = buildQueryParams(operation, params, secretParamNames);
1009
+ const effectiveParams = buildQueryParams(
1010
+ operation,
1011
+ queryParamsForBuild,
1012
+ secretParamNames,
1013
+ );
683
1014
 
684
1015
  // Resolve the effective page size once for the seeding styles — the
685
1016
  // caller's value, else the op's declared default (both already folded into
@@ -695,22 +1026,37 @@ export async function paginate(
695
1026
  : (params[pagCfg.pageSizeParam] ?? effectiveParams[pagCfg.pageSizeParam]);
696
1027
  effectivePageSize =
697
1028
  rawSize === undefined ? (pagCfg.pageSize ?? 50) : Number(rawSize);
698
- if (isNaN(effectivePageSize)) effectivePageSize = 50;
1029
+ if (Number.isNaN(effectivePageSize)) effectivePageSize = 50;
1030
+ } else if (style === "cursor") {
1031
+ // Terminal fallback for cursor is OMIT (server default applies) — no
1032
+ // fabricated 50 like offset-limit (which needs a real number to advance
1033
+ // row offsets; cursor's position comes from the response cursor). Seed
1034
+ // effectiveParams (not pageParams — rebuilt per iteration) so
1035
+ // result.params stays honest about what was sent.
1036
+ if (
1037
+ pagCfg.pageSizeParam !== undefined &&
1038
+ pagCfg.pageSize !== undefined &&
1039
+ params[pagCfg.pageSizeParam] === undefined &&
1040
+ effectiveParams[pagCfg.pageSizeParam] === undefined
1041
+ ) {
1042
+ effectiveParams[pagCfg.pageSizeParam] = String(pagCfg.pageSize);
1043
+ }
699
1044
  }
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
1045
  const urls: string[] = [];
704
1046
 
705
1047
  while (true) {
706
- // Build per-page params.
707
- const pageParams: Record<string, string> = {};
1048
+ // Build per-page params. Keyed supersession: pagination/tokenBag
1049
+ // writes below REPLACE same-named base values via plain overwrite —
1050
+ // only genuinely multi-value (listStyle) keys hold arrays, and the
1051
+ // parse-time collision guard guarantees those never collide with a
1052
+ // pagination/tokenBag wire name, so every write here is a scalar.
1053
+ const pageParams: Record<string, string | string[]> = {};
708
1054
  for (const [key, val] of Object.entries(effectiveParams)) {
709
1055
  pageParams[key] = val;
710
1056
  }
711
1057
 
712
1058
  if (style === "offset-limit" || style === "page") {
713
- pageParams[pagCfg.pageParam!] = String(page ?? 0);
1059
+ pageParams[pagCfg.pageParam!] = String(page);
714
1060
  // effectivePageSize is always resolved (a number) in this branch.
715
1061
  if (pagCfg.pageSizeParam) {
716
1062
  pageParams[pagCfg.pageSizeParam] = String(effectivePageSize);
@@ -724,7 +1070,7 @@ export async function paginate(
724
1070
  }
725
1071
 
726
1072
  // Build URL.
727
- const resolvedPath = fillPathStrict(operation.path, params);
1073
+ const resolvedPath = fillPathStrict(operation.path, fillParams);
728
1074
 
729
1075
  let url: string;
730
1076
  if (style === "nextLink" && nextUrl) {
@@ -734,15 +1080,20 @@ export async function paginate(
734
1080
  : new URL(nextUrl, apiHost).toString();
735
1081
  } else {
736
1082
  // Append secret query params below the agent-supplied page params.
737
- url = buildUrl(apiHost, resolvedPath, {
738
- ...pageParams,
739
- ...secretParams,
740
- });
1083
+ url = buildUrl(
1084
+ apiHost,
1085
+ resolvedPath,
1086
+ { ...pageParams, ...secretParams },
1087
+ operation.params,
1088
+ );
741
1089
  }
742
1090
 
743
1091
  // Every surfaced URL (incl. a server-supplied nextUrl that may
744
- // already carry the secret) is redacted at the capture point.
745
- urls.push(redactSecretParams(url, secretParamNames));
1092
+ // already carry the secret) is redacted at the capture point — query
1093
+ // params by name, path tokens by value. One redaction serves the
1094
+ // surfaced list, the status check, and the error-envelope URL below.
1095
+ const redactedUrl = redactSurfacedUrl(url, secretParamNames, pathValues);
1096
+ urls.push(redactedUrl);
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`
@@ -751,11 +1102,13 @@ export async function paginate(
751
1102
  // nextLink to an internal host; when auth headers ship, the
752
1103
  // Authorization header would attach to the redirect).
753
1104
  const guardThisFetch =
754
- style === "nextLink" && !!nextUrl && !opts?.skipSsrfGuard;
1105
+ style === "nextLink" && Boolean(nextUrl) && !opts?.skipSsrfGuard;
755
1106
  if (guardThisFetch) {
756
1107
  const guard = ssrfGuard(url);
757
1108
  if (!guard.ok) {
758
- const errUrl = redactSecretParams(url, secretParamNames);
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,42 @@ export async function paginate(
768
1121
  }
769
1122
 
770
1123
  // Fetch.
771
- const result = await fetchWithOpts(
772
- url,
1124
+ const result = await fetchWithOpts(url, {
1125
+ ...baseFetchArgs,
773
1126
  accept,
774
- opts?.fresh,
775
- extraHeaders,
776
- guardThisFetch,
777
- shape.charset,
778
- opts?.secretHeaderNames,
779
- hasQuerySecret,
780
- );
1127
+ fresh: opts?.fresh,
1128
+ guardRedirects: guardThisFetch,
1129
+ fallbackCharset: shape.charset,
1130
+ });
781
1131
 
782
1132
  // Check HTTP status before attempting to parse. Secret values scrubbed
783
1133
  // from the error excerpt (output-channel audit). The URL stored on
784
1134
  // the error object is redacted, computed upstream of checkResponseStatus.
785
- checkResponseStatus(
786
- { ...result, url: redactSecretParams(url, secretParamNames) },
787
- opts?.secretValues,
788
- );
1135
+ checkResponseStatus({ ...result, url: redactedUrl }, opts?.secretValues);
789
1136
 
790
1137
  // Parse.
791
1138
  const data = parseResponse(result.body, shape);
792
1139
 
793
- // Extract the server's reported total from the first page — before the
794
- // empty-page break below, so a zero-result page that still carries the
795
- // count (e.g. `total_count: 0`) surfaces it rather than losing it to the
796
- // early `break`. Accepts a number directly or a numeric string (coerced
797
- // via Number()); any other value (or an unresolved path) leaves it
798
- // undefined for that page and it stays unset for the whole run.
1140
+ // 200-with-error-envelope check (op.errorPath) — placement pin: the
1141
+ // very next statement after parseResponse, BEFORE the totalCountPath
1142
+ // extraction and both exhaustion breaks below. An error page often
1143
+ // misses itemsPath entirely, so a check after the breaks never fires
1144
+ // (the walk exits with silent items: []).
1145
+ if (operation.errorPath !== undefined) {
1146
+ checkErrorEnvelope(
1147
+ data,
1148
+ operation.errorPath,
1149
+ redactedUrl,
1150
+ opts?.secretValues,
1151
+ );
1152
+ }
1153
+
1154
+ // Extract the server's reported total from the first page that resolves
1155
+ // one — before the empty-page break below, so a zero-result page that
1156
+ // still carries the count (e.g. `total_count: 0`) surfaces it rather
1157
+ // than losing it to the early `break`. Accepts a number directly or a
1158
+ // numeric string (coerced via Number()); a page that misses the path
1159
+ // leaves it undefined and later pages can still supply it.
799
1160
  if (serverTotal === undefined && pagCfg.totalCountPath) {
800
1161
  const raw = resolveJsonPath(data, pagCfg.totalCountPath);
801
1162
  if (typeof raw === "number" && Number.isFinite(raw)) {
@@ -827,12 +1188,12 @@ export async function paginate(
827
1188
  ? pageItems.slice(0, remaining)
828
1189
  : pageItems;
829
1190
  for (const item of toProcess) {
830
- if (transformFn) {
1191
+ if (opts?.transformFn) {
831
1192
  try {
832
1193
  items.push(
833
- transformFn(item, {
1194
+ opts.transformFn(item, {
834
1195
  operation: operation.name,
835
- domain: dirName ?? "",
1196
+ domain: opts.dirName ?? "",
836
1197
  }),
837
1198
  );
838
1199
  } catch {
@@ -857,6 +1218,17 @@ export async function paginate(
857
1218
  break;
858
1219
  }
859
1220
 
1221
+ // hasMorePath done-flag (style-agnostic).
1222
+ // Sits after the ceiling checks so ceilingHit still wins when both fire
1223
+ // on the same page. The undefined carve-out is fail-open: a missing or
1224
+ // typo'd path never stops the walk (pre-existing exhaustion semantics
1225
+ // apply); a RESOLVED falsy value stops cleanly. Plain truthiness, no
1226
+ // coercion — the string "false" advances by design.
1227
+ if (pagCfg.hasMorePath !== undefined) {
1228
+ const v = resolveJsonPath(data, pagCfg.hasMorePath);
1229
+ if (v !== undefined && !v) break;
1230
+ }
1231
+
860
1232
  // Determine next page.
861
1233
  const advanced = advancePagination(
862
1234
  style,
@@ -930,13 +1302,20 @@ function advancePagination(
930
1302
  }
931
1303
 
932
1304
  if (style === "cursor") {
933
- const next = resolveJsonPath(data, cfg.cursorPath!);
1305
+ // Numeric cursors coerce to strings (tokenBag-style) BEFORE the
1306
+ // type/falsy check — a numeric 0 must advance like string "0", not die
1307
+ // at !next. nextLink stays string-strict (a numeric "next URL" is
1308
+ // garbage); booleans/objects don't coerce.
1309
+ const raw = resolveJsonPath(data, cfg.cursorPath!);
1310
+ const next = typeof raw === "number" ? String(raw) : raw;
934
1311
  if (!next || typeof next !== "string") return null;
935
1312
  return { cursor: next };
936
1313
  }
937
1314
 
938
1315
  if (style === "resumptionToken") {
939
- const t = resolveJsonPath(data, cfg.tokenPath!);
1316
+ // No !next guard here by design — "" and missing are exhaustion.
1317
+ const raw = resolveJsonPath(data, cfg.tokenPath!);
1318
+ const t = typeof raw === "number" ? String(raw) : raw; // coercion, before the check
940
1319
  if (typeof t !== "string" || t === "") return null;
941
1320
  return { token: t };
942
1321
  }
@@ -951,8 +1330,10 @@ function advancePagination(
951
1330
  for (const key of cfg.continuationParams ?? []) {
952
1331
  const v = resolveJsonPath(data, key);
953
1332
  if (v === undefined || v === null) continue;
954
- const param = key.includes(".") ? key.split(".").pop()! : key;
955
- collected[param] = String(v);
1333
+ // Wire param = wireParamName (last dot segment, bracket dress
1334
+ // stripped — shared with the parser's listStyle collision guard so
1335
+ // the derivation exists once).
1336
+ collected[wireParamName(key)] = String(v);
956
1337
  }
957
1338
  return Object.keys(collected).length > 0 ? { tokenBag: collected } : null;
958
1339
  }