@layervai/qurl 0.3.1 → 0.4.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.
Files changed (72) hide show
  1. package/README.md +187 -7
  2. package/dist/cjs/client.d.ts +17 -10
  3. package/dist/cjs/client.js +649 -96
  4. package/dist/cjs/errors.d.ts +11 -11
  5. package/dist/cjs/errors.js +25 -20
  6. package/dist/cjs/index.d.ts +1 -1
  7. package/dist/cjs/internal.d.ts +4 -0
  8. package/dist/cjs/internal.js +16 -0
  9. package/dist/cjs/node/deployment.d.ts +44 -0
  10. package/dist/cjs/node/deployment.js +167 -0
  11. package/dist/cjs/node/native-udp.d.ts +37 -0
  12. package/dist/cjs/node/native-udp.js +294 -0
  13. package/dist/cjs/node/nhp-wire.d.ts +35 -0
  14. package/dist/cjs/node/nhp-wire.js +261 -0
  15. package/dist/cjs/node/portal-opener.d.ts +83 -0
  16. package/dist/cjs/node/portal-opener.js +767 -0
  17. package/dist/cjs/node/qv2.d.ts +38 -0
  18. package/dist/cjs/node/qv2.js +292 -0
  19. package/dist/cjs/node/strict-json.d.ts +12 -0
  20. package/dist/cjs/node/strict-json.js +174 -0
  21. package/dist/cjs/node.d.ts +3 -0
  22. package/dist/cjs/node.js +11 -0
  23. package/dist/cjs/types.d.ts +7 -18
  24. package/dist/cjs/version.d.ts +1 -1
  25. package/dist/cjs/version.js +1 -1
  26. package/dist/esm/client.d.ts +17 -10
  27. package/dist/esm/client.d.ts.map +1 -1
  28. package/dist/esm/client.js +647 -94
  29. package/dist/esm/client.js.map +1 -1
  30. package/dist/esm/errors.d.ts +11 -11
  31. package/dist/esm/errors.d.ts.map +1 -1
  32. package/dist/esm/errors.js +25 -20
  33. package/dist/esm/errors.js.map +1 -1
  34. package/dist/esm/index.d.ts +1 -1
  35. package/dist/esm/index.d.ts.map +1 -1
  36. package/dist/esm/internal.d.ts +5 -0
  37. package/dist/esm/internal.d.ts.map +1 -0
  38. package/dist/esm/internal.js +14 -0
  39. package/dist/esm/internal.js.map +1 -0
  40. package/dist/esm/node/deployment.d.ts +45 -0
  41. package/dist/esm/node/deployment.d.ts.map +1 -0
  42. package/dist/esm/node/deployment.js +163 -0
  43. package/dist/esm/node/deployment.js.map +1 -0
  44. package/dist/esm/node/native-udp.d.ts +38 -0
  45. package/dist/esm/node/native-udp.d.ts.map +1 -0
  46. package/dist/esm/node/native-udp.js +291 -0
  47. package/dist/esm/node/native-udp.js.map +1 -0
  48. package/dist/esm/node/nhp-wire.d.ts +36 -0
  49. package/dist/esm/node/nhp-wire.d.ts.map +1 -0
  50. package/dist/esm/node/nhp-wire.js +257 -0
  51. package/dist/esm/node/nhp-wire.js.map +1 -0
  52. package/dist/esm/node/portal-opener.d.ts +84 -0
  53. package/dist/esm/node/portal-opener.d.ts.map +1 -0
  54. package/dist/esm/node/portal-opener.js +757 -0
  55. package/dist/esm/node/portal-opener.js.map +1 -0
  56. package/dist/esm/node/qv2.d.ts +39 -0
  57. package/dist/esm/node/qv2.d.ts.map +1 -0
  58. package/dist/esm/node/qv2.js +286 -0
  59. package/dist/esm/node/qv2.js.map +1 -0
  60. package/dist/esm/node/strict-json.d.ts +13 -0
  61. package/dist/esm/node/strict-json.d.ts.map +1 -0
  62. package/dist/esm/node/strict-json.js +171 -0
  63. package/dist/esm/node/strict-json.js.map +1 -0
  64. package/dist/esm/node.d.ts +4 -0
  65. package/dist/esm/node.d.ts.map +1 -0
  66. package/dist/esm/node.js +2 -0
  67. package/dist/esm/node.js.map +1 -0
  68. package/dist/esm/types.d.ts +7 -18
  69. package/dist/esm/types.d.ts.map +1 -1
  70. package/dist/esm/version.d.ts +1 -1
  71. package/dist/esm/version.js +1 -1
  72. package/package.json +25 -6
@@ -1,8 +1,35 @@
1
1
  import { createError, ERROR_CODE_AMBIGUOUS_RESOURCE, ERROR_CODE_CLIENT_VALIDATION, ERROR_CODE_RESOURCE_NOT_FOUND, ERROR_CODE_UNEXPECTED_RESPONSE, ERROR_CODE_UNKNOWN, NetworkError, NotFoundError, QURLError, RuntimeError, TimeoutError, ValidationError, } from "./errors.js";
2
+ import { stripTrailingSlashes } from "./internal.js";
2
3
  import { VERSION } from "./version.js";
3
4
  const DEFAULT_BASE_URL = "https://api.layerv.ai";
4
5
  const DEFAULT_MAX_RETRIES = 3;
5
6
  const DEFAULT_TIMEOUT = 30_000;
7
+ // Match qurl-go c4f2f98's exact API response cap. Current qurl-service list
8
+ // routes cap pages at 100 items. A caller can still exceed this cap with a
9
+ // large, heavily escaped webhook-delivery page, so list callers must request a
10
+ // smaller page if the service reports the body-limit error. This cap is fixed:
11
+ // do not add an override or widen one SDK independently from the other.
12
+ // The limit is enforced from Content-Length when usable and again while
13
+ // consuming the response stream.
14
+ const MAX_RESPONSE_BODY_BYTES = 1 << 20;
15
+ const MAX_ERROR_SNIPPET_BYTES = 512;
16
+ // UTF-8 uses at least one byte per UTF-16 code unit. Reading more source units
17
+ // cannot add a byte that fits in a 512-byte retained diagnostic.
18
+ const MAX_ERROR_SNIPPET_SOURCE_CODE_UNITS = MAX_ERROR_SNIPPET_BYTES;
19
+ const MAX_INVALID_FIELD_ENTRIES = 100;
20
+ const MAX_DEBUG_BODY_KEYS = 100;
21
+ // Bound each retained diagnostic collection as well as each string. Without
22
+ // this aggregate cap, 100 valid 512-byte keys and values could turn a small
23
+ // server error into a large caller-visible object. This is a diagnostic budget,
24
+ // not part of the API wire contract.
25
+ const MAX_DIAGNOSTIC_COLLECTION_BYTES = 8 << 10;
26
+ const TEXT_ENCODER = new TextEncoder();
27
+ const ERROR_SNIPPET_ELLIPSIS = "...";
28
+ const ERROR_SNIPPET_ELLIPSIS_BYTES = 3;
29
+ // RFC 8259 JSON exchanged between systems must be valid UTF-8. A non-fatal
30
+ // decoder would replace malformed bytes with U+FFFD before JSON.parse and hide
31
+ // the producer's exact contract violation.
32
+ const TEXT_DECODER = new TextDecoder("utf-8", { fatal: true });
6
33
  const RETRY_BASE_DELAY_MS = 500;
7
34
  // Bounds local exponential backoff (NOT server-asserted Retry-After —
8
35
  // see `RETRY_AFTER_HARD_CAP_MS` for that).
@@ -15,13 +42,33 @@ const RETRY_AFTER_PARSE_LIMIT_S = RETRY_AFTER_HARD_CAP_MS / 1000;
15
42
  const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
16
43
  // Keep mutating status retries 429-only until the service-side idempotency
17
44
  // cache contract is proven across 5xx, TTL, and replay-window edge cases.
18
- // Network-error retries still reuse Idempotency-Key below.
45
+ // Fetch-level POST/PATCH retries still reuse Idempotency-Key below.
19
46
  const RETRYABLE_STATUS_MUTATING = new Set([429]);
47
+ const REDIRECT_RESPONSE_STATUSES = new Set([300, 301, 302, 303, 305, 307, 308]);
48
+ const NO_RETRYABLE_STATUSES = new Set();
20
49
  const IDEMPOTENCY_KEY_METHODS = new Set(["POST", "PATCH"]);
21
50
  const MUTATING_RETRY_METHODS = new Set(["POST", "PATCH"]);
22
51
  const MAX_IDEMPOTENCY_KEY = 256;
23
52
  const IDEMPOTENCY_KEY_VALUE_RE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/;
24
53
  const UUID_HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
54
+ class ResponseBodyTooLargeError extends Error {
55
+ constructor() {
56
+ super(`Response body exceeds ${MAX_RESPONSE_BODY_BYTES}-byte limit`);
57
+ this.name = "ResponseBodyTooLargeError";
58
+ }
59
+ }
60
+ class InvalidResponseEncodingError extends Error {
61
+ constructor() {
62
+ super("Response body is not valid UTF-8");
63
+ this.name = "InvalidResponseEncodingError";
64
+ }
65
+ }
66
+ class ResponseBodyMaterializationError extends Error {
67
+ constructor(message = "Response-like fetch returned a value that cannot be serialized as JSON") {
68
+ super(message);
69
+ this.name = "ResponseBodyMaterializationError";
70
+ }
71
+ }
25
72
  const NO_PASSTHROUGH_STATUSES = [];
26
73
  const BATCH_PASSTHROUGH_STATUSES = [400];
27
74
  /** Allowlist of known query-param keys for the `list()` endpoint. */
@@ -157,13 +204,6 @@ const UPDATE_RESOURCE_QURL_FIELD_KEYS = [
157
204
  "session_duration",
158
205
  ];
159
206
  assertExhaustive(true);
160
- const AGENT_BOOTSTRAP_FIELD_KEYS = [
161
- "public_key",
162
- "agent_id",
163
- "hostname",
164
- "version",
165
- ];
166
- assertExhaustive(true);
167
207
  const UPDATE_CUSTOMER_FIELD_KEYS = [
168
208
  "spending_cap_cents",
169
209
  ];
@@ -339,23 +379,330 @@ function fillRandomBytes(bytes) {
339
379
  * Distinct from {@link clientValidationError} so callers can `.code`-branch
340
380
  * between "I passed bad input locally" (`"client_validation"`) and "the
341
381
  * server returned a body I can't interpret" (`"unexpected_response"`).
342
- * Uses `status: 0` because the offending HTTP status (400/207/etc.) isn't
343
- * the thing being reported — the shape mismatch is.
382
+ * Uses `status: 0` by default because a logical shape mismatch is not tied to
383
+ * the HTTP classification. Callers that enforce an observed HTTP contract
384
+ * pass that status explicitly.
344
385
  *
345
386
  * Threads `request_id` through to {@link QURLError.requestId} when the
346
387
  * server-side correlation ID is available — operators debugging
347
388
  * "unexpected response" tickets need it on the *error* path too, not
348
389
  * just on success/passthrough returns.
349
390
  */
350
- function unexpectedResponseError(detail, request_id) {
391
+ function unexpectedResponseError(detail, options = {}) {
392
+ // Every detail passed here is an SDK-authored contract message whose dynamic
393
+ // inputs were validated by the caller-side shape guards. Do not pass raw
394
+ // server strings to this helper. Server diagnostics use boundedErrorSnippet.
395
+ const safeRequestId = boundedErrorIdentifier(options.requestId);
351
396
  return new ValidationError({
352
- status: 0,
397
+ status: options.status ?? 0,
353
398
  code: ERROR_CODE_UNEXPECTED_RESPONSE,
354
399
  title: "Unexpected Response",
355
400
  detail,
356
- request_id,
401
+ request_id: safeRequestId,
357
402
  });
358
403
  }
404
+ function withErrorCause(error, cause) {
405
+ // Match the native Error `cause` descriptor. In particular, do not leak a
406
+ // transport object through Object.keys(), object spread, or JSON logging.
407
+ Object.defineProperty(error, "cause", {
408
+ value: cause,
409
+ writable: true,
410
+ configurable: true,
411
+ });
412
+ return error;
413
+ }
414
+ function isIndependentAbort(error, requestSignal) {
415
+ return (error instanceof Error &&
416
+ (error.name === "AbortError" || error.name === "TimeoutError") &&
417
+ !requestSignal.aborted);
418
+ }
419
+ function isSdkTimeout(error, requestSignal) {
420
+ return (error instanceof Error &&
421
+ requestSignal.aborted &&
422
+ (error.name === "TimeoutError" || error.name === "AbortError"));
423
+ }
424
+ /**
425
+ * Normalize a server-provided problem title/detail into a single-line,
426
+ * UTF-8-safe snippet. Error messages must stay bounded even when a proxy or
427
+ * compromised upstream returns very large structured problem fields.
428
+ */
429
+ function normalizedErrorSnippet(value) {
430
+ if (typeof value !== "string")
431
+ return undefined;
432
+ // Bound source work before the Unicode regular expressions allocate
433
+ // normalized copies. The response body cap is much larger than one retained
434
+ // diagnostic, so processing the full server string would waste memory.
435
+ const normalized = value
436
+ .slice(0, MAX_ERROR_SNIPPET_SOURCE_CODE_UNITS)
437
+ // Strip control characters plus bidi override/isolate controls that can
438
+ // visually reorder diagnostics. Preserve other formatting characters
439
+ // such as ZWJ/ZWNJ, which are required by legitimate scripts and emoji.
440
+ .replace(/[\p{Cc}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu, " ")
441
+ .trim()
442
+ .replace(/\s+/g, " ");
443
+ return normalized === "" ? undefined : normalized;
444
+ }
445
+ function boundedErrorSnippet(value) {
446
+ const sourceTruncated = typeof value === "string" && value.length > MAX_ERROR_SNIPPET_SOURCE_CODE_UNITS;
447
+ const normalized = normalizedErrorSnippet(value);
448
+ if (normalized === undefined)
449
+ return undefined;
450
+ const contentLimit = sourceTruncated
451
+ ? MAX_ERROR_SNIPPET_BYTES - ERROR_SNIPPET_ELLIPSIS_BYTES
452
+ : MAX_ERROR_SNIPPET_BYTES;
453
+ // UTF-8 uses at most three bytes per UTF-16 code unit. Most diagnostics are
454
+ // short ASCII, so avoid an allocation only to prove they fit.
455
+ if (normalized.length * 3 <= contentLimit) {
456
+ return sourceTruncated ? `${normalized}${ERROR_SNIPPET_ELLIPSIS}` : normalized;
457
+ }
458
+ const encoded = TEXT_ENCODER.encode(normalized);
459
+ if (encoded.byteLength <= contentLimit) {
460
+ return sourceTruncated ? `${normalized}${ERROR_SNIPPET_ELLIPSIS}` : normalized;
461
+ }
462
+ let end = MAX_ERROR_SNIPPET_BYTES - ERROR_SNIPPET_ELLIPSIS_BYTES;
463
+ // Do not split a multi-byte UTF-8 sequence at the cap.
464
+ while (end > 0 && (encoded[end] & 0xc0) === 0x80)
465
+ end--;
466
+ return `${TEXT_DECODER.decode(encoded.subarray(0, end))}${ERROR_SNIPPET_ELLIPSIS}`;
467
+ }
468
+ /** Keep server identifiers useful as exact machine-readable discriminants. */
469
+ function boundedErrorIdentifier(value) {
470
+ if (typeof value !== "string" || value.length > MAX_ERROR_SNIPPET_SOURCE_CODE_UNITS) {
471
+ return undefined;
472
+ }
473
+ const normalized = normalizedErrorSnippet(value);
474
+ if (normalized === undefined ||
475
+ normalized !== value ||
476
+ TEXT_ENCODER.encode(value).byteLength > MAX_ERROR_SNIPPET_BYTES) {
477
+ return undefined;
478
+ }
479
+ return value;
480
+ }
481
+ /** Collect at most the first N enumerable own string keys without a full key-array copy. */
482
+ function firstEnumerableOwnKeys(value, limit) {
483
+ const keys = [];
484
+ for (const key in value) {
485
+ if (!Object.prototype.hasOwnProperty.call(value, key))
486
+ continue;
487
+ keys.push(key);
488
+ if (keys.length === limit)
489
+ break;
490
+ }
491
+ return keys;
492
+ }
493
+ /** Bound the structured per-field diagnostics exposed on ValidationError. */
494
+ function boundedInvalidFields(value) {
495
+ if (typeof value !== "object" || value === null || Array.isArray(value))
496
+ return undefined;
497
+ const entries = [];
498
+ const retainedKeys = new Set();
499
+ let retainedBytes = 0;
500
+ // Bound inspected entries as well as retained entries. A hostile envelope
501
+ // whose values all have the wrong type must not make diagnostics scan every
502
+ // key in the response body.
503
+ for (const rawKey of firstEnumerableOwnKeys(value, MAX_INVALID_FIELD_ENTRIES)) {
504
+ const rawValue = value[rawKey];
505
+ const key = boundedErrorSnippet(rawKey);
506
+ const fieldDetail = boundedErrorSnippet(rawValue);
507
+ if (key !== undefined && fieldDetail !== undefined && !retainedKeys.has(key)) {
508
+ const entryBytes = TEXT_ENCODER.encode(key).byteLength + TEXT_ENCODER.encode(fieldDetail).byteLength;
509
+ // A later, smaller entry can still fit even when this one cannot.
510
+ if (retainedBytes + entryBytes > MAX_DIAGNOSTIC_COLLECTION_BYTES)
511
+ continue;
512
+ retainedKeys.add(key);
513
+ entries.push([key, fieldDetail]);
514
+ retainedBytes += entryBytes;
515
+ }
516
+ }
517
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
518
+ }
519
+ /** Bound server-controlled object keys before forwarding them to a debug sink. */
520
+ function boundedObjectKeys(value) {
521
+ // Stop before normalization so a hostile envelope cannot force work over
522
+ // every enumerable own key. Some early keys may normalize away; bounded
523
+ // diagnostics are more important here than filling every available slot.
524
+ const retained = [];
525
+ let retainedBytes = 0;
526
+ for (const rawKey of firstEnumerableOwnKeys(value, MAX_DEBUG_BODY_KEYS)) {
527
+ const key = boundedErrorSnippet(rawKey);
528
+ if (key === undefined)
529
+ continue;
530
+ const keyBytes = TEXT_ENCODER.encode(key).byteLength;
531
+ // A later, smaller key can still fit even when this one cannot.
532
+ if (retainedBytes + keyBytes > MAX_DIAGNOSTIC_COLLECTION_BYTES)
533
+ continue;
534
+ retained.push(key);
535
+ retainedBytes += keyBytes;
536
+ }
537
+ return retained;
538
+ }
539
+ async function cancelResponseBody(body) {
540
+ if (!body)
541
+ return;
542
+ try {
543
+ await body.cancel();
544
+ }
545
+ catch {
546
+ // Best-effort resource cleanup must not replace the deterministic SDK error.
547
+ }
548
+ }
549
+ function materializedResponseBodyExceedsLimit(value) {
550
+ if (value.length > MAX_RESPONSE_BODY_BYTES)
551
+ return true;
552
+ // Encoding creates another buffer. UTF-8 uses at most three bytes per
553
+ // UTF-16 code unit, so shorter strings are provably safe without that copy.
554
+ return (value.length * 3 > MAX_RESPONSE_BODY_BYTES &&
555
+ TEXT_ENCODER.encode(value).byteLength > MAX_RESPONSE_BODY_BYTES);
556
+ }
557
+ function contentLengthExceedsLimit(response) {
558
+ // 204/205 never carry content, and a 304 Content-Length describes the
559
+ // selected representation rather than a response body. Do not reject those
560
+ // statuses for metadata about bytes that fetch will not deliver.
561
+ if (response.status === 204 || response.status === 205 || response.status === 304)
562
+ return false;
563
+ const value = response.headers.get("content-length");
564
+ if (value === null || !/^\d+$/.test(value.trim()))
565
+ return false;
566
+ return Number(value) > MAX_RESPONSE_BODY_BYTES;
567
+ }
568
+ /** Detect a followed redirect from fetch implementations that expose only the final URL. */
569
+ function responseUrlState(responseUrl, requestUrl) {
570
+ if (typeof responseUrl !== "string" || responseUrl === "")
571
+ return "same";
572
+ if (responseUrl === requestUrl)
573
+ return "same";
574
+ try {
575
+ // URL serialization normalizes equivalent spellings such as host case and
576
+ // an explicit default port, so they do not create false redirect reports.
577
+ return new URL(responseUrl).href === new URL(requestUrl).href ? "same" : "changed";
578
+ }
579
+ catch {
580
+ // A non-empty invalid response URL cannot prove that credentials stayed on
581
+ // the requested endpoint. Fail closed without reflecting it in diagnostics.
582
+ return "invalid";
583
+ }
584
+ }
585
+ /**
586
+ * Read a response body while retaining accepted chunks up to the documented
587
+ * cap. A fetch implementation can still hand us one arbitrarily large,
588
+ * already-materialized chunk before we can reject it. For a compliant body,
589
+ * final assembly transiently holds the chunks plus the combined output buffer
590
+ * (roughly twice the cap) before decoding. Content-Length is an early-rejection
591
+ * optimization only; streaming byte accounting remains authoritative because
592
+ * that header may be absent or false.
593
+ */
594
+ async function readBoundedResponseBody(response) {
595
+ // `headers.get` is part of the documented injected-fetch contract. Detect a
596
+ // malformed local shim before it can be mistaken for a retryable body-stream
597
+ // failure and replay an otherwise deterministic GET programming error.
598
+ if (typeof response.headers?.get !== "function") {
599
+ throw new ResponseBodyMaterializationError("Response-like fetch must provide headers.get(name)");
600
+ }
601
+ if (contentLengthExceedsLimit(response)) {
602
+ await cancelResponseBody(response.body);
603
+ throw new ResponseBodyTooLargeError();
604
+ }
605
+ const body = response.body;
606
+ if (body === null)
607
+ return "";
608
+ // Standards-compliant fetch implementations always expose a ReadableStream
609
+ // for a non-empty body. Retain compatibility with Response-like test/custom
610
+ // fetch implementations while still checking their materialized text before
611
+ // this SDK parses it as JSON.
612
+ if (body === undefined || typeof body.getReader !== "function") {
613
+ let materializedText = "";
614
+ if (typeof response.text === "function") {
615
+ try {
616
+ materializedText = await response.text();
617
+ }
618
+ catch {
619
+ // Native fetch exposes a body stream above. A failing text() here is a
620
+ // deterministic custom Response contract error, not a retryable reset.
621
+ throw new ResponseBodyMaterializationError("Response-like fetch text() failed");
622
+ }
623
+ }
624
+ const text = typeof materializedText === "string" ? materializedText : "";
625
+ if (materializedResponseBodyExceedsLimit(text)) {
626
+ throw new ResponseBodyTooLargeError();
627
+ }
628
+ if (text !== "" ||
629
+ response.status === 204 ||
630
+ response.status === 205 ||
631
+ response.status === 304) {
632
+ return text;
633
+ }
634
+ // Older injected Response-like objects may implement json() but return an
635
+ // empty placeholder from text(). This path is never used by native fetch.
636
+ let parsed;
637
+ try {
638
+ parsed = await response.json();
639
+ }
640
+ catch {
641
+ // A Response-like shim may expose json() but reject on an empty 204
642
+ // body. Native fetch represents that body as null and returns above.
643
+ return "";
644
+ }
645
+ let serialized;
646
+ try {
647
+ serialized = JSON.stringify(parsed);
648
+ }
649
+ catch {
650
+ throw new ResponseBodyMaterializationError();
651
+ }
652
+ if (serialized === undefined)
653
+ return "";
654
+ if (materializedResponseBodyExceedsLimit(serialized)) {
655
+ throw new ResponseBodyTooLargeError();
656
+ }
657
+ return serialized;
658
+ }
659
+ const reader = body.getReader();
660
+ const chunks = [];
661
+ let total = 0;
662
+ try {
663
+ while (true) {
664
+ const { done, value } = await reader.read();
665
+ if (done)
666
+ break;
667
+ if (!(value instanceof Uint8Array)) {
668
+ throw new ResponseBodyMaterializationError("Response-like fetch body stream must yield Uint8Array chunks");
669
+ }
670
+ const nextTotal = total + value.byteLength;
671
+ if (nextTotal > MAX_RESPONSE_BODY_BYTES) {
672
+ try {
673
+ await reader.cancel();
674
+ }
675
+ catch {
676
+ // Preserve the body-limit failure even if stream cancellation fails.
677
+ }
678
+ throw new ResponseBodyTooLargeError();
679
+ }
680
+ chunks.push(value);
681
+ total = nextTotal;
682
+ }
683
+ }
684
+ finally {
685
+ reader.releaseLock();
686
+ }
687
+ let bytes;
688
+ if (chunks.length === 1) {
689
+ bytes = chunks[0];
690
+ }
691
+ else {
692
+ bytes = new Uint8Array(total);
693
+ let offset = 0;
694
+ for (const chunk of chunks) {
695
+ bytes.set(chunk, offset);
696
+ offset += chunk.byteLength;
697
+ }
698
+ }
699
+ try {
700
+ return TEXT_DECODER.decode(bytes);
701
+ }
702
+ catch {
703
+ throw new InvalidResponseEncodingError();
704
+ }
705
+ }
359
706
  // ---- Spec-derived validation helpers ------------------------------------
360
707
  // These mirror constraints documented on each request schema in
361
708
  // `openapi.yaml` so obvious mistakes fail fast instead of round-tripping
@@ -925,10 +1272,14 @@ const MIN_PORTAL_VALID_FOR_SECONDS = 60;
925
1272
  * treated as the server default).
926
1273
  */
927
1274
  const MIN_SESSION_DURATION_SECONDS = 1;
928
- // Shape of qurl-go's offline signed-fragment links: three or more
929
- // dot-separated base64url parts (<version>.<claims>.<secret>.<sig>).
930
- // Detected only to give those links a precise error in extractAccessToken.
931
- const SIGNED_FRAGMENT_RE = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){2,}$/;
1275
+ /**
1276
+ * Shape of qurl-go's offline signed-fragment links: three or more
1277
+ * dot-separated base64url parts (<version>.<claims>.<secret>.<sig>).
1278
+ * Detected only to give those links a precise error in extractAccessToken.
1279
+ *
1280
+ * @internal Exported for in-package tests; not re-exported from index.ts.
1281
+ */
1282
+ export const SIGNED_FRAGMENT_RE = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){2,}$/;
932
1283
  // Access-token grammar accepted by enterPortal (base64url charset).
933
1284
  const ACCESS_TOKEN_RE = /^[A-Za-z0-9_-]+$/;
934
1285
  /**
@@ -1117,7 +1468,7 @@ export class QURLClient {
1117
1468
  throw clientValidationError("apiKey: must not contain CR/LF characters");
1118
1469
  }
1119
1470
  this.apiKey = options.apiKey;
1120
- const rawBaseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
1471
+ const rawBaseUrl = stripTrailingSlashes(options.baseUrl ?? DEFAULT_BASE_URL);
1121
1472
  // Parse the URL so the loopback exemption matches on the hostname,
1122
1473
  // not a string prefix. `startsWith("http://localhost")` would
1123
1474
  // accept `http://localhost.attacker.com` and silently send the
@@ -1272,7 +1623,7 @@ export class QURLClient {
1272
1623
  // .requestId property AND the message string so a stack trace
1273
1624
  // pasted into a support ticket carries the correlation handle
1274
1625
  // without a follow-up round-trip.
1275
- const requestId = envelope.meta?.request_id;
1626
+ const requestId = boundedErrorIdentifier(envelope.meta?.request_id);
1276
1627
  const requestIdSuffix = requestId !== undefined ? ` [request_id=${requestId}]` : "";
1277
1628
  // `Number.isInteger` rejects NaN, Infinity, and floats. Combined
1278
1629
  // with `>= 0`, this rules out pathological proxy bodies (e.g.
@@ -1285,12 +1636,12 @@ export class QURLClient {
1285
1636
  !Number.isInteger(result.failed) ||
1286
1637
  result.failed < 0 ||
1287
1638
  !Array.isArray(result.results)) {
1288
- throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}${requestIdSuffix}`, requestId);
1639
+ throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}${requestIdSuffix}`, { requestId });
1289
1640
  }
1290
1641
  if (result.succeeded + result.failed !== result.results.length) {
1291
1642
  throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: ` +
1292
1643
  `counts/results length mismatch (succeeded=${result.succeeded}, ` +
1293
- `failed=${result.failed}, results.length=${result.results.length})${requestIdSuffix}`, requestId);
1644
+ `failed=${result.failed}, results.length=${result.results.length})${requestIdSuffix}`, { requestId });
1294
1645
  }
1295
1646
  // OpenAPI contract: one result per input item. Without this check, a
1296
1647
  // server that drops items (e.g. sends 2 results for 3 inputs with
@@ -1301,7 +1652,7 @@ export class QURLClient {
1301
1652
  // exactly [0, requestItemCount).
1302
1653
  if (result.results.length !== requestItemCount) {
1303
1654
  throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: ` +
1304
- `results.length (${result.results.length}) does not match request item count (${requestItemCount})${requestIdSuffix}`, requestId);
1655
+ `results.length (${result.results.length}) does not match request item count (${requestItemCount})${requestIdSuffix}`, { requestId });
1305
1656
  }
1306
1657
  // Per-entry discriminated-union contract. Reason strings report
1307
1658
  // field NAMES only, never values — safe for observability pipelines.
@@ -1313,14 +1664,14 @@ export class QURLClient {
1313
1664
  for (let i = 0; i < result.results.length; i++) {
1314
1665
  const reason = batchItemResultValidationReason(result.results[i]);
1315
1666
  if (reason !== null) {
1316
- throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: results[${i}] ${reason}${requestIdSuffix}`, requestId);
1667
+ throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: results[${i}] ${reason}${requestIdSuffix}`, { requestId });
1317
1668
  }
1318
1669
  const entry = result.results[i];
1319
1670
  if (entry.index >= requestItemCount) {
1320
- throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: results[${i}] index out of range (sent ${requestItemCount} items)${requestIdSuffix}`, requestId);
1671
+ throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: results[${i}] index out of range (sent ${requestItemCount} items)${requestIdSuffix}`, { requestId });
1321
1672
  }
1322
1673
  if (seenIndices.has(entry.index)) {
1323
- throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: results[${i}] duplicate index${requestIdSuffix}`, requestId);
1674
+ throw unexpectedResponseError(`Unexpected response shape from POST /v1/qurls/batch${statusSuffix}: results[${i}] duplicate index${requestIdSuffix}`, { requestId });
1324
1675
  }
1325
1676
  seenIndices.add(entry.index);
1326
1677
  }
@@ -1346,11 +1697,11 @@ export class QURLClient {
1346
1697
  break;
1347
1698
  }
1348
1699
  if (seenCursors.has(cursor)) {
1349
- throw unexpectedResponseError(`${methodName}: server returned repeated cursor after ${pageCount} auto-pagination pages`, page.request_id);
1700
+ throw unexpectedResponseError(`${methodName}: server returned repeated cursor after ${pageCount} auto-pagination pages`, { requestId: page.request_id });
1350
1701
  }
1351
1702
  seenCursors.add(cursor);
1352
1703
  if (pageCount >= MAX_AUTO_PAGINATION_PAGES) {
1353
- throw unexpectedResponseError(`${methodName}: exceeded ${MAX_AUTO_PAGINATION_PAGES} auto-pagination pages without termination`, page.request_id);
1704
+ throw unexpectedResponseError(`${methodName}: exceeded ${MAX_AUTO_PAGINATION_PAGES} auto-pagination pages without termination`, { requestId: page.request_id });
1354
1705
  }
1355
1706
  } while (cursor);
1356
1707
  }
@@ -1797,7 +2148,7 @@ export class QURLClient {
1797
2148
  `got an ID starting with "${observedPrefix}". ` +
1798
2149
  "To revoke a single access token, use the resource-scoped token endpoint.");
1799
2150
  }
1800
- await this.rawRequest("DELETE", `/v1/qurls/${encodeURIComponent(id)}`);
2151
+ await this.requestNoContent(`/v1/qurls/${encodeURIComponent(id)}`);
1801
2152
  }
1802
2153
  /**
1803
2154
  * Extend a qURL's expiration.
@@ -1949,15 +2300,6 @@ export class QURLClient {
1949
2300
  async getQuota() {
1950
2301
  return this.request("GET", "/v1/quota");
1951
2302
  }
1952
- /** Bootstrap a LayerV qURL Connector agent. */
1953
- async bootstrapAgent(input, options) {
1954
- requireObjectInput(input, "bootstrapAgent");
1955
- requireNoUnknownFields(input, AGENT_BOOTSTRAP_FIELD_KEYS, "bootstrapAgent");
1956
- const normalizedRecord = normalizePatchFields(input, AGENT_BOOTSTRAP_FIELD_KEYS);
1957
- const normalized = normalizedRecord;
1958
- requireNonEmptyStringField(normalizedRecord, "public_key", "bootstrapAgent");
1959
- return this.request("POST", "/v1/agent/bootstrap", normalized, options);
1960
- }
1961
2303
  /** List resources from the `/v1/resources` API. */
1962
2304
  async listResources(input = {}) {
1963
2305
  const { data, meta } = await this.rawRequest("GET", appendQuery("/v1/resources", input, RESOURCE_LIST_PARAM_KEYS, "listResources"));
@@ -2011,7 +2353,7 @@ export class QURLClient {
2011
2353
  /** Revoke a resource and all of its qURLs. */
2012
2354
  async deleteResource(id) {
2013
2355
  requireNonEmptyId(id, "deleteResource");
2014
- await this.rawRequest("DELETE", `/v1/resources/${encodeURIComponent(id)}`);
2356
+ await this.requestNoContent(`/v1/resources/${encodeURIComponent(id)}`);
2015
2357
  }
2016
2358
  /**
2017
2359
  * Mint a qURL against an existing resource.
@@ -2034,7 +2376,7 @@ export class QURLClient {
2034
2376
  async revokeResourceQurl(id, qurlId) {
2035
2377
  requireNonEmptyId(id, "revokeResourceQurl");
2036
2378
  requireNonEmptyId(qurlId, "revokeResourceQurl");
2037
- await this.rawRequest("DELETE", `/v1/resources/${encodeURIComponent(id)}/qurls/${encodeURIComponent(qurlId)}`);
2379
+ await this.requestNoContent(`/v1/resources/${encodeURIComponent(id)}/qurls/${encodeURIComponent(qurlId)}`);
2038
2380
  }
2039
2381
  /** Update a specific qURL token on a resource. */
2040
2382
  async updateResourceQurl(id, qurlId, input, options) {
@@ -2070,13 +2412,7 @@ export class QURLClient {
2070
2412
  page_size: meta?.page_size,
2071
2413
  };
2072
2414
  }
2073
- /**
2074
- * Terminate all active sessions for a resource.
2075
- *
2076
- * The returned count is best-effort under retries: if the first DELETE
2077
- * succeeds server-side but the response is lost, a retried request may
2078
- * return `0` because there are no sessions left to terminate.
2079
- */
2415
+ /** Terminate all active sessions for a resource and return the server count. */
2080
2416
  async terminateAllResourceSessions(id) {
2081
2417
  requireNonEmptyId(id, "terminateAllResourceSessions");
2082
2418
  const path = `/v1/resources/${encodeURIComponent(id)}/sessions`;
@@ -2095,7 +2431,7 @@ export class QURLClient {
2095
2431
  async terminateResourceSession(id, sessionId) {
2096
2432
  requireNonEmptyId(id, "terminateResourceSession");
2097
2433
  requireNonEmptyId(sessionId, "terminateResourceSession");
2098
- await this.rawRequest("DELETE", `/v1/resources/${encodeURIComponent(id)}/sessions/${encodeURIComponent(sessionId)}`);
2434
+ await this.requestNoContent(`/v1/resources/${encodeURIComponent(id)}/sessions/${encodeURIComponent(sessionId)}`);
2099
2435
  }
2100
2436
  /** List connector installations. */
2101
2437
  async listConnectorInstallations(input = {}) {
@@ -2203,7 +2539,7 @@ export class QURLClient {
2203
2539
  /** Remove a custom domain. */
2204
2540
  async deleteDomain(domain) {
2205
2541
  requireNonEmptyId(domain, "deleteDomain", "domain");
2206
- await this.rawRequest("DELETE", `/v1/domains/${encodeURIComponent(domain)}`);
2542
+ await this.requestNoContent(`/v1/domains/${encodeURIComponent(domain)}`);
2207
2543
  }
2208
2544
  /** Trigger DNS verification for a custom domain. */
2209
2545
  async verifyDomain(domain, options) {
@@ -2264,7 +2600,7 @@ export class QURLClient {
2264
2600
  /** Delete a webhook. */
2265
2601
  async deleteWebhook(id) {
2266
2602
  requireNonEmptyId(id, "deleteWebhook");
2267
- await this.rawRequest("DELETE", `/v1/webhooks/${encodeURIComponent(id)}`);
2603
+ await this.requestNoContent(`/v1/webhooks/${encodeURIComponent(id)}`);
2268
2604
  }
2269
2605
  /** Regenerate a webhook signing secret. */
2270
2606
  async regenerateWebhookSecret(id, options) {
@@ -2328,7 +2664,7 @@ export class QURLClient {
2328
2664
  /** Revoke an API key. */
2329
2665
  async revokeApiKey(keyId) {
2330
2666
  requireNonEmptyId(keyId, "revokeApiKey");
2331
- await this.rawRequest("DELETE", `/v1/api-keys/${encodeURIComponent(keyId)}`);
2667
+ await this.requestNoContent(`/v1/api-keys/${encodeURIComponent(keyId)}`);
2332
2668
  }
2333
2669
  /** Redeem an access code. */
2334
2670
  async redeemAccessCode(input, options) {
@@ -2373,7 +2709,7 @@ export class QURLClient {
2373
2709
  /** Revoke an access code. */
2374
2710
  async revokeAccessCode(id) {
2375
2711
  requireNonEmptyId(id, "revokeAccessCode");
2376
- await this.rawRequest("DELETE", `/v1/access-codes/${encodeURIComponent(id)}`);
2712
+ await this.requestNoContent(`/v1/access-codes/${encodeURIComponent(id)}`);
2377
2713
  }
2378
2714
  // --- Internal HTTP plumbing ---
2379
2715
  async request(method, path, body, requestOptions) {
@@ -2387,6 +2723,22 @@ export class QURLClient {
2387
2723
  }
2388
2724
  return data;
2389
2725
  }
2726
+ /**
2727
+ * Require the service's exact 204 response with no response bytes exposed by
2728
+ * Fetch. A standards-compliant Fetch implementation discards any forbidden
2729
+ * wire body on 204, so the SDK cannot detect bytes that Fetch did not expose.
2730
+ */
2731
+ async requestNoContent(path) {
2732
+ const response = await this.rawRequest("DELETE", path, undefined, {
2733
+ allowEmptySuccessBody: true,
2734
+ });
2735
+ if (response.__http_status !== 204 || response.__http_body_empty !== true) {
2736
+ const status = response.__http_status ?? 0;
2737
+ const bodyShape = response.__http_body_empty ? "with an empty body" : "with response bytes";
2738
+ throw unexpectedResponseError(`Unexpected response from DELETE; expected empty HTTP 204, received HTTP ${status} ${bodyShape}. ` +
2739
+ "The delete may already have been applied; reconcile resource state before retrying.", { status });
2740
+ }
2741
+ }
2390
2742
  /**
2391
2743
  * Issue an HTTP request and parse the JSON response.
2392
2744
  *
@@ -2398,7 +2750,7 @@ export class QURLClient {
2398
2750
  */
2399
2751
  async rawRequest(method, path, body, rawOptions = {}) {
2400
2752
  const url = `${this.baseUrl}${path}`;
2401
- const { passthroughStatuses = NO_PASSTHROUGH_STATUSES, requestOptions } = rawOptions;
2753
+ const { passthroughStatuses = NO_PASSTHROUGH_STATUSES, requestOptions, allowEmptySuccessBody = false, } = rawOptions;
2402
2754
  const idempotencyKey = idempotencyKeyForRequest(method, requestOptions);
2403
2755
  const headers = {
2404
2756
  Authorization: `Bearer ${this.apiKey}`,
@@ -2411,12 +2763,20 @@ export class QURLClient {
2411
2763
  if (idempotencyKey !== undefined) {
2412
2764
  headers["Idempotency-Key"] = idempotencyKey;
2413
2765
  }
2414
- // POST/PATCH keep status-code retries limited to rate limits. They
2415
- // still retry fetch-level failures below with the same Idempotency-Key,
2416
- // which fixes the duplicate-creation path from lost responses
2417
- // without broadening mutating 5xx replay behavior.
2418
- const mutatingForRetry = MUTATING_RETRY_METHODS.has(method);
2419
- const retryable = mutatingForRetry ? RETRYABLE_STATUS_MUTATING : RETRYABLE_STATUS;
2766
+ // Reads may retry transient statuses and transport failures. POST/PATCH
2767
+ // keep status-code retries limited to rate limits and reuse the same
2768
+ // Idempotency-Key for fetch-level failures. DELETE is deliberately never
2769
+ // replayed, including after 429: this matches qurl-go's no-hidden-HTTP-
2770
+ // retry rule and avoids SDK pacing on an application request path. The
2771
+ // caller receives retryAfter when supplied and must reconcile resource
2772
+ // state before it chooses to issue another delete.
2773
+ const idempotencyKeyBackedRetry = MUTATING_RETRY_METHODS.has(method);
2774
+ const retryFetchFailure = method === "GET" || idempotencyKeyBackedRetry;
2775
+ const retryable = method === "GET"
2776
+ ? RETRYABLE_STATUS
2777
+ : idempotencyKeyBackedRetry
2778
+ ? RETRYABLE_STATUS_MUTATING
2779
+ : NO_RETRYABLE_STATUSES;
2420
2780
  const serializedBody = body !== undefined ? JSON.stringify(body) : undefined;
2421
2781
  let lastError;
2422
2782
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
@@ -2427,6 +2787,7 @@ export class QURLClient {
2427
2787
  }
2428
2788
  this.log(`${method} ${url}`);
2429
2789
  let response;
2790
+ const requestSignal = AbortSignal.timeout(this.timeout);
2430
2791
  try {
2431
2792
  // `timeout` is intentionally a per-attempt budget, not a total-
2432
2793
  // request budget. With maxRetries=3 and timeout=30s, a slow
@@ -2440,20 +2801,151 @@ export class QURLClient {
2440
2801
  method,
2441
2802
  headers,
2442
2803
  body: serializedBody,
2443
- signal: AbortSignal.timeout(this.timeout),
2804
+ redirect: "manual",
2805
+ signal: requestSignal,
2444
2806
  });
2445
2807
  }
2446
2808
  catch (err) {
2447
- lastError = this.classifyFetchError(err);
2809
+ lastError = this.classifyFetchError(err, requestSignal);
2448
2810
  this.log(`${method} ${url} ${lastError instanceof TimeoutError ? "timed out" : "network error"}`, {
2449
- error: lastError.message,
2811
+ error: boundedErrorSnippet(lastError.message),
2450
2812
  });
2451
- if (attempt < this.maxRetries) {
2813
+ // An injected fetch can abort or impose a deadline for its own reason.
2814
+ // That is not this SDK's timeout. Replaying it can defeat caller-side
2815
+ // cancellation or deadline policy.
2816
+ if (retryFetchFailure &&
2817
+ !isIndependentAbort(err, requestSignal) &&
2818
+ attempt < this.maxRetries) {
2452
2819
  continue;
2453
2820
  }
2454
2821
  throw lastError;
2455
2822
  }
2456
2823
  this.log(`${method} ${url} → ${response.status}`);
2824
+ // Redirects are deterministic protocol violations for SDK API calls.
2825
+ // Refuse them before reading Location or entering retry handling so
2826
+ // Authorization and Idempotency-Key can never reach a follow-up target.
2827
+ const responseUrlStateValue = responseUrlState(response.url, url);
2828
+ if (response.redirected === true ||
2829
+ responseUrlStateValue !== "same" ||
2830
+ REDIRECT_RESPONSE_STATUSES.has(response.status) ||
2831
+ response.type === "opaqueredirect") {
2832
+ await cancelResponseBody(response.body);
2833
+ const redirectKind = response.redirected === true
2834
+ ? "followed"
2835
+ : responseUrlStateValue === "invalid"
2836
+ ? "invalid custom Response.url"
2837
+ : responseUrlStateValue === "changed"
2838
+ ? "changed Response.url"
2839
+ : REDIRECT_RESPONSE_STATUSES.has(response.status)
2840
+ ? `HTTP ${response.status}`
2841
+ : "opaque";
2842
+ throw unexpectedResponseError(`Refused ${redirectKind} redirect response for ${method}`, {
2843
+ status: response.status,
2844
+ });
2845
+ }
2846
+ let responseBody;
2847
+ try {
2848
+ responseBody = await readBoundedResponseBody(response);
2849
+ }
2850
+ catch (err) {
2851
+ if (err instanceof ResponseBodyTooLargeError) {
2852
+ this.log(`rejected oversized response body from ${response.status}`, {
2853
+ status: response.status,
2854
+ });
2855
+ const detail = `Response body exceeds ${MAX_RESPONSE_BODY_BYTES}-byte limit on HTTP ${response.status}; ` +
2856
+ "request a smaller page when listing collections";
2857
+ if (response.ok) {
2858
+ throw unexpectedResponseError(detail, { status: response.status });
2859
+ }
2860
+ const bodyError = createError({
2861
+ status: response.status,
2862
+ // The unread body cannot supply a trustworthy server code. Keep
2863
+ // the real HTTP status class (429/5xx) just like other unreadable
2864
+ // error bodies instead of reclassifying it as client validation.
2865
+ code: ERROR_CODE_UNKNOWN,
2866
+ title: boundedErrorSnippet(response.statusText) || `HTTP ${response.status}`,
2867
+ detail,
2868
+ retry_after: this.parseRetryAfter(response),
2869
+ });
2870
+ // The unread body does not change operation semantics: retry a GET,
2871
+ // or an idempotency-key-backed mutation on an explicitly retryable
2872
+ // status. Successful oversized responses remain deterministic
2873
+ // contract failures, and DELETE has no retryable statuses.
2874
+ if (retryable.has(response.status) && attempt < this.maxRetries) {
2875
+ lastError = bodyError;
2876
+ continue;
2877
+ }
2878
+ throw bodyError;
2879
+ }
2880
+ if (err instanceof InvalidResponseEncodingError) {
2881
+ this.log(`rejected malformed UTF-8 response body from ${response.status}`, {
2882
+ status: response.status,
2883
+ });
2884
+ const detail = `Response body is not valid UTF-8 on HTTP ${response.status}`;
2885
+ if (response.ok) {
2886
+ // A successful status with an invalid wire body is a deterministic
2887
+ // response-contract failure. Do not replay a GET or a mutation.
2888
+ throw unexpectedResponseError(detail, { status: response.status });
2889
+ }
2890
+ const encodingError = createError({
2891
+ status: response.status,
2892
+ code: ERROR_CODE_UNKNOWN,
2893
+ title: boundedErrorSnippet(response.statusText) || `HTTP ${response.status}`,
2894
+ detail,
2895
+ retry_after: this.parseRetryAfter(response),
2896
+ });
2897
+ // For an explicit error status, the HTTP classification remains
2898
+ // authoritative even when its body encoding is invalid.
2899
+ if (retryable.has(response.status) && attempt < this.maxRetries) {
2900
+ lastError = encodingError;
2901
+ continue;
2902
+ }
2903
+ throw encodingError;
2904
+ }
2905
+ await cancelResponseBody(response.body);
2906
+ const transportReadError = this.classifyResponseReadError(err, response, requestSignal);
2907
+ if (transportReadError !== undefined) {
2908
+ this.log(`transport failure while reading response body from ${response.status}`, {
2909
+ status: response.status,
2910
+ error: transportReadError.code,
2911
+ });
2912
+ // A successful GET can be replayed when its success body is lost. A
2913
+ // non-success GET retries only the status set that the normal error
2914
+ // path retries. Mutations are never replayed after a body transport
2915
+ // failure because the operation may have applied.
2916
+ if (method === "GET" &&
2917
+ !isIndependentAbort(err, requestSignal) &&
2918
+ (response.ok || retryable.has(response.status)) &&
2919
+ attempt < this.maxRetries) {
2920
+ lastError = transportReadError;
2921
+ continue;
2922
+ }
2923
+ throw transportReadError;
2924
+ }
2925
+ this.log(`failed to read response body from ${response.status}`, {
2926
+ status: response.status,
2927
+ });
2928
+ // ResponseBodyMaterializationError messages are fixed SDK-authored
2929
+ // contract text. The underlying shim rejection is never interpolated.
2930
+ const detail = err instanceof ResponseBodyMaterializationError
2931
+ ? err.message
2932
+ : `Failed to read response body on HTTP ${response.status}`;
2933
+ const readError = response.ok
2934
+ ? unexpectedResponseError(detail, { status: response.status })
2935
+ : createError({
2936
+ status: response.status,
2937
+ code: ERROR_CODE_UNKNOWN,
2938
+ title: boundedErrorSnippet(response.statusText) || `HTTP ${response.status}`,
2939
+ detail,
2940
+ retry_after: this.parseRetryAfter(response),
2941
+ });
2942
+ // This arm contains deterministic Response-like shim failures (for
2943
+ // example a BigInt returned by json()) and non-Error throws. Do not
2944
+ // replay them: another attempt will see the same local contract bug.
2945
+ throw err instanceof ResponseBodyMaterializationError
2946
+ ? withErrorCause(readError, err)
2947
+ : readError;
2948
+ }
2457
2949
  // `response.ok` is true for the entire 200-299 range, so partial-
2458
2950
  // success responses like 207 flow through this path naturally —
2459
2951
  // `passthroughStatuses` only needs to enumerate non-2xx statuses
@@ -2476,33 +2968,56 @@ export class QURLClient {
2476
2968
  url,
2477
2969
  });
2478
2970
  }
2479
- return { data: undefined, __http_status: response.status };
2971
+ return {
2972
+ data: undefined,
2973
+ __http_status: response.status,
2974
+ __http_body_empty: responseBody.length === 0,
2975
+ };
2976
+ }
2977
+ // Exact no-content helpers must inspect both axes of the success
2978
+ // contract. Let only those callers observe an empty non-204 response;
2979
+ // body-returning methods still reject it as non-JSON below.
2980
+ if (response.ok && allowEmptySuccessBody && responseBody.length === 0) {
2981
+ return {
2982
+ data: undefined,
2983
+ __http_status: response.status,
2984
+ __http_body_empty: true,
2985
+ };
2480
2986
  }
2481
2987
  try {
2482
- const json = (await response.json());
2483
- return { ...json, __http_status: response.status };
2988
+ const json = JSON.parse(responseBody);
2989
+ return {
2990
+ ...json,
2991
+ __http_status: response.status,
2992
+ // JSON.parse("") throws, so parsed JSON is necessarily non-empty.
2993
+ __http_body_empty: false,
2994
+ };
2484
2995
  }
2485
2996
  catch {
2486
2997
  // Non-JSON body on a 2xx response (server contract violation)
2487
2998
  // or on a passthrough status (e.g. proxy HTML on 400). The
2488
- // body stream is already consumed by the failed `.json()`,
2489
- // so we can't delegate to parseError — synthesize a typed
2490
- // QURLError directly so consumers catching by-class don't
2491
- // miss it.
2999
+ // body was read through the cap before JSON decoding.
3000
+ // Synthesize a typed QURLError directly so consumers catching
3001
+ // by-class don't miss the contract failure.
2492
3002
  this.log(`non-JSON body on ${isPassthrough ? "passthrough" : "success"} response ${response.status}`, {
2493
3003
  status: response.status,
2494
- content_type: response.headers.get("content-type") ?? undefined,
3004
+ content_type: boundedErrorSnippet(response.headers.get("content-type")),
2495
3005
  });
2496
3006
  throw createError({
2497
3007
  status: response.status,
2498
3008
  code: ERROR_CODE_UNEXPECTED_RESPONSE,
2499
- title: response.statusText || `HTTP ${response.status}`,
3009
+ title: boundedErrorSnippet(response.statusText) || `HTTP ${response.status}`,
2500
3010
  detail: `Expected JSON response body on HTTP ${response.status} but received non-JSON content`,
2501
3011
  });
2502
3012
  }
2503
3013
  }
2504
- const errorData = await this.parseError(response);
3014
+ const errorData = this.parseError(response, responseBody);
2505
3015
  const err = createError(errorData);
3016
+ // Retryability is determined by status even when an intermediary
3017
+ // returned HTML, an empty body, or another non-envelope error. Those
3018
+ // shapes are common for transient 429/502/503/504 responses and do not
3019
+ // prove that a retry cannot succeed. Redirects and oversized bodies
3020
+ // already throw before reaching this check.
2506
3021
  if (retryable.has(response.status) && attempt < this.maxRetries) {
2507
3022
  lastError = err;
2508
3023
  continue;
@@ -2511,9 +3026,9 @@ export class QURLClient {
2511
3026
  }
2512
3027
  throw lastError ?? new Error("Request failed after retries");
2513
3028
  }
2514
- async parseError(response) {
3029
+ parseError(response, responseBody) {
2515
3030
  try {
2516
- const json = (await response.json());
3031
+ const json = JSON.parse(responseBody);
2517
3032
  if (json.error) {
2518
3033
  const err = json.error;
2519
3034
  // Detail fallback chain:
@@ -2522,18 +3037,27 @@ export class QURLClient {
2522
3037
  // 3. err.title (RFC 7807 required field)
2523
3038
  // 4. HTTP status (final safety net)
2524
3039
  // This prevents `"Title (403): undefined"` when the API omits detail.
2525
- const detail = err.detail ?? err.message ?? err.title ?? `HTTP ${response.status}`;
3040
+ const detail = boundedErrorSnippet(err.detail) ??
3041
+ boundedErrorSnippet(err.message) ??
3042
+ boundedErrorSnippet(err.title) ??
3043
+ `HTTP ${response.status}`;
2526
3044
  // HTTP/2 omits reason-phrases — `statusText` may be "".
2527
- const title = err.title ?? (response.statusText || `HTTP ${response.status}`);
3045
+ const title = boundedErrorSnippet(err.title) ??
3046
+ boundedErrorSnippet(response.statusText) ??
3047
+ `HTTP ${response.status}`;
3048
+ // The transport status is authoritative for error classification. A
3049
+ // conflicting or malformed RFC 7807 body must not turn a real 5xx into
3050
+ // a NotFoundError (or vice versa) in caller reconciliation logic.
3051
+ const status = response.status;
2528
3052
  return {
2529
- status: err.status ?? response.status,
2530
- code: err.code ?? ERROR_CODE_UNKNOWN,
3053
+ status,
3054
+ code: boundedErrorIdentifier(err.code) ?? ERROR_CODE_UNKNOWN,
2531
3055
  title,
2532
3056
  detail,
2533
- type: err.type,
2534
- instance: err.instance,
2535
- invalid_fields: err.invalid_fields,
2536
- request_id: json.meta?.request_id,
3057
+ type: boundedErrorIdentifier(err.type),
3058
+ instance: boundedErrorIdentifier(err.instance),
3059
+ invalid_fields: boundedInvalidFields(err.invalid_fields),
3060
+ request_id: boundedErrorIdentifier(json.meta?.request_id),
2537
3061
  retry_after: this.parseRetryAfter(response),
2538
3062
  };
2539
3063
  }
@@ -2543,31 +3067,37 @@ export class QURLClient {
2543
3067
  // status-only safety net below.
2544
3068
  this.log(`unexpected error response shape from ${response.status}`, {
2545
3069
  status: response.status,
2546
- body_keys: Object.keys(json),
3070
+ body_keys: typeof json === "object" && json !== null ? boundedObjectKeys(json) : undefined,
2547
3071
  });
2548
3072
  }
2549
3073
  catch {
2550
- // Body wasn't valid JSON (or the network stream errored during
2551
- // read). Log so operators can distinguish this from a malformed
2552
- // envelope, and fall through to the status-only safety net.
3074
+ // Body wasn't valid JSON. Log so operators can distinguish this from a
3075
+ // malformed envelope, and fall through to the status-only safety net.
2553
3076
  this.log(`non-JSON error response from ${response.status}`, {
2554
3077
  status: response.status,
2555
- content_type: response.headers.get("content-type") ?? undefined,
3078
+ content_type: boundedErrorSnippet(response.headers.get("content-type")),
2556
3079
  });
2557
3080
  }
3081
+ const statusText = boundedErrorSnippet(response.statusText) || `HTTP ${response.status}`;
2558
3082
  return {
2559
3083
  status: response.status,
2560
3084
  code: ERROR_CODE_UNKNOWN,
2561
- title: response.statusText || `HTTP ${response.status}`,
2562
- detail: response.statusText || `HTTP ${response.status}`,
3085
+ title: statusText,
3086
+ detail: statusText,
3087
+ retry_after: this.parseRetryAfter(response),
2563
3088
  };
2564
3089
  }
2565
3090
  parseRetryAfter(response) {
2566
- // RFC 7231 §7.1.3: Retry-After honored on 429 + 503. (RFC 7231
2567
- // also allows Retry-After on 3xx redirects; the SDK doesn't follow
2568
- // redirects, so 429/503 cover the relevant cases.)
3091
+ // RFC 7231 §7.1.3: Retry-After honored on 429 + 503. Although the RFC
3092
+ // also permits it on 3xx responses, rawRequest now refuses redirects
3093
+ // as deterministic errors before retry parsing, so only 429/503 apply.
2569
3094
  if (response.status !== 429 && response.status !== 503)
2570
3095
  return undefined;
3096
+ // This fallback can run after the body reader rejects a malformed injected
3097
+ // Response-like shim. Preserve the typed, non-retryable SDK error instead
3098
+ // of dereferencing the same missing method and leaking a raw TypeError.
3099
+ if (typeof response.headers?.get !== "function")
3100
+ return undefined;
2571
3101
  const header = response.headers.get("Retry-After");
2572
3102
  if (!header)
2573
3103
  return undefined;
@@ -2629,13 +3159,36 @@ export class QURLClient {
2629
3159
  const jitter = Math.random() * base * 0.5;
2630
3160
  return Math.min(base + jitter, RETRY_MAX_DELAY_MS);
2631
3161
  }
2632
- classifyFetchError(err) {
2633
- if (err instanceof DOMException && err.name === "TimeoutError") {
3162
+ classifyFetchError(err, requestSignal) {
3163
+ // AbortSignal.timeout is the only timeout source owned by this SDK. Keep
3164
+ // this check tied to that signal instead of trusting an injected fetch's
3165
+ // AbortError or TimeoutError name.
3166
+ if (isSdkTimeout(err, requestSignal)) {
2634
3167
  return new TimeoutError("Request timed out", { cause: err });
2635
3168
  }
2636
3169
  const cause = err instanceof Error ? err : undefined;
2637
3170
  return new NetworkError(cause?.message ?? String(err), { cause });
2638
3171
  }
3172
+ classifyResponseReadError(err, response, requestSignal) {
3173
+ if (err instanceof ResponseBodyMaterializationError)
3174
+ return undefined;
3175
+ if (!(err instanceof Error))
3176
+ return undefined;
3177
+ if (!response.ok) {
3178
+ const statusText = boundedErrorSnippet(response.statusText) || `HTTP ${response.status}`;
3179
+ return withErrorCause(createError({
3180
+ status: response.status,
3181
+ code: ERROR_CODE_UNKNOWN,
3182
+ title: statusText,
3183
+ detail: `Failed to read response body after HTTP ${response.status}`,
3184
+ retry_after: this.parseRetryAfter(response),
3185
+ }), err);
3186
+ }
3187
+ if (isSdkTimeout(err, requestSignal)) {
3188
+ return new TimeoutError(`Request timed out while reading response body after HTTP ${response.status}`, { cause: err });
3189
+ }
3190
+ return new NetworkError(`Network failure while reading response body after HTTP ${response.status}`, { cause: err });
3191
+ }
2639
3192
  }
2640
3193
  /**
2641
3194
  * A LayerV-protected resource, bound to the client that produced it.