@cyanheads/secedgar-mcp-server 0.20.1 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/AGENTS.md +33 -26
  2. package/CLAUDE.md +33 -26
  3. package/README.md +23 -12
  4. package/changelog/0.21.x/0.21.0.md +35 -0
  5. package/changelog/0.21.x/0.21.1.md +29 -0
  6. package/dist/mcp-server/prompts/definitions/company-analysis.prompt.js +3 -3
  7. package/dist/mcp-server/prompts/definitions/company-analysis.prompt.js.map +1 -1
  8. package/dist/mcp-server/tools/annual-report-reads.d.ts +53 -0
  9. package/dist/mcp-server/tools/annual-report-reads.d.ts.map +1 -0
  10. package/dist/mcp-server/tools/annual-report-reads.js +145 -0
  11. package/dist/mcp-server/tools/annual-report-reads.js.map +1 -0
  12. package/dist/mcp-server/tools/blockquote.d.ts +13 -0
  13. package/dist/mcp-server/tools/blockquote.d.ts.map +1 -0
  14. package/dist/mcp-server/tools/blockquote.js +18 -0
  15. package/dist/mcp-server/tools/blockquote.js.map +1 -0
  16. package/dist/mcp-server/tools/calendar-quarter.d.ts +22 -0
  17. package/dist/mcp-server/tools/calendar-quarter.d.ts.map +1 -0
  18. package/dist/mcp-server/tools/calendar-quarter.js +34 -0
  19. package/dist/mcp-server/tools/calendar-quarter.js.map +1 -0
  20. package/dist/mcp-server/tools/definitions/company-search.tool.d.ts.map +1 -1
  21. package/dist/mcp-server/tools/definitions/company-search.tool.js +10 -21
  22. package/dist/mcp-server/tools/definitions/company-search.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts +12 -2
  24. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/compare-companies.tool.js +120 -29
  26. package/dist/mcp-server/tools/definitions/compare-companies.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/find-holders.tool.d.ts.map +1 -1
  28. package/dist/mcp-server/tools/definitions/find-holders.tool.js +9 -16
  29. package/dist/mcp-server/tools/definitions/find-holders.tool.js.map +1 -1
  30. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts +31 -9
  31. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts.map +1 -1
  32. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js +268 -88
  33. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js.map +1 -1
  34. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts +10 -0
  35. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts.map +1 -1
  36. package/dist/mcp-server/tools/definitions/get-filing.tool.js +164 -10
  37. package/dist/mcp-server/tools/definitions/get-filing.tool.js.map +1 -1
  38. package/dist/mcp-server/tools/definitions/get-financials.tool.d.ts +1 -0
  39. package/dist/mcp-server/tools/definitions/get-financials.tool.d.ts.map +1 -1
  40. package/dist/mcp-server/tools/definitions/get-financials.tool.js +219 -128
  41. package/dist/mcp-server/tools/definitions/get-financials.tool.js.map +1 -1
  42. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.d.ts.map +1 -1
  43. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js +2 -3
  44. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js.map +1 -1
  45. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts +44 -0
  46. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts.map +1 -1
  47. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js +336 -75
  48. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js.map +1 -1
  49. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.d.ts +12 -0
  50. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.d.ts.map +1 -1
  51. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js +16 -31
  52. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js.map +1 -1
  53. package/dist/mcp-server/tools/definitions/get-material-events.tool.d.ts +15 -0
  54. package/dist/mcp-server/tools/definitions/get-material-events.tool.d.ts.map +1 -1
  55. package/dist/mcp-server/tools/definitions/get-material-events.tool.js +107 -54
  56. package/dist/mcp-server/tools/definitions/get-material-events.tool.js.map +1 -1
  57. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts +5 -0
  58. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts.map +1 -1
  59. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js +48 -17
  60. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js.map +1 -1
  61. package/dist/mcp-server/tools/definitions/index.d.ts +526 -464
  62. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  63. package/dist/mcp-server/tools/definitions/search-concepts.tool.js +1 -1
  64. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts +16 -0
  65. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts.map +1 -1
  66. package/dist/mcp-server/tools/definitions/search-filings.tool.js +194 -70
  67. package/dist/mcp-server/tools/definitions/search-filings.tool.js.map +1 -1
  68. package/dist/mcp-server/tools/filing-dates.d.ts +48 -0
  69. package/dist/mcp-server/tools/filing-dates.d.ts.map +1 -0
  70. package/dist/mcp-server/tools/filing-dates.js +99 -0
  71. package/dist/mcp-server/tools/filing-dates.js.map +1 -0
  72. package/dist/mcp-server/tools/limit-clamp.d.ts.map +1 -1
  73. package/dist/mcp-server/tools/limit-clamp.js +6 -2
  74. package/dist/mcp-server/tools/limit-clamp.js.map +1 -1
  75. package/dist/services/edgar/body-text-decoder.d.ts +33 -0
  76. package/dist/services/edgar/body-text-decoder.d.ts.map +1 -0
  77. package/dist/services/edgar/body-text-decoder.js +103 -0
  78. package/dist/services/edgar/body-text-decoder.js.map +1 -0
  79. package/dist/services/edgar/call-scope.d.ts +9 -0
  80. package/dist/services/edgar/call-scope.d.ts.map +1 -1
  81. package/dist/services/edgar/call-scope.js +3 -0
  82. package/dist/services/edgar/call-scope.js.map +1 -1
  83. package/dist/services/edgar/concept-map.d.ts.map +1 -1
  84. package/dist/services/edgar/concept-map.js +70 -12
  85. package/dist/services/edgar/concept-map.js.map +1 -1
  86. package/dist/services/edgar/concept-series.d.ts +126 -9
  87. package/dist/services/edgar/concept-series.d.ts.map +1 -1
  88. package/dist/services/edgar/concept-series.js +217 -21
  89. package/dist/services/edgar/concept-series.js.map +1 -1
  90. package/dist/services/edgar/edgar-api-service.d.ts +31 -15
  91. package/dist/services/edgar/edgar-api-service.d.ts.map +1 -1
  92. package/dist/services/edgar/edgar-api-service.js +182 -36
  93. package/dist/services/edgar/edgar-api-service.js.map +1 -1
  94. package/dist/services/edgar/eight-k-items.d.ts +19 -1
  95. package/dist/services/edgar/eight-k-items.d.ts.map +1 -1
  96. package/dist/services/edgar/eight-k-items.js +24 -1
  97. package/dist/services/edgar/eight-k-items.js.map +1 -1
  98. package/dist/services/edgar/filing-headers.d.ts +22 -10
  99. package/dist/services/edgar/filing-headers.d.ts.map +1 -1
  100. package/dist/services/edgar/filing-headers.js +98 -15
  101. package/dist/services/edgar/filing-headers.js.map +1 -1
  102. package/dist/services/edgar/filing-to-text.d.ts +13 -6
  103. package/dist/services/edgar/filing-to-text.d.ts.map +1 -1
  104. package/dist/services/edgar/filing-to-text.js +23 -3
  105. package/dist/services/edgar/filing-to-text.js.map +1 -1
  106. package/dist/services/edgar/fiscal-periods.d.ts +14 -1
  107. package/dist/services/edgar/fiscal-periods.d.ts.map +1 -1
  108. package/dist/services/edgar/fiscal-periods.js +47 -18
  109. package/dist/services/edgar/fiscal-periods.js.map +1 -1
  110. package/dist/services/edgar/form4-amendments.d.ts +63 -0
  111. package/dist/services/edgar/form4-amendments.d.ts.map +1 -0
  112. package/dist/services/edgar/form4-amendments.js +99 -0
  113. package/dist/services/edgar/form4-amendments.js.map +1 -0
  114. package/dist/services/edgar/mirror/companyfacts-sync.d.ts +6 -1
  115. package/dist/services/edgar/mirror/companyfacts-sync.d.ts.map +1 -1
  116. package/dist/services/edgar/mirror/companyfacts-sync.js +29 -6
  117. package/dist/services/edgar/mirror/companyfacts-sync.js.map +1 -1
  118. package/dist/services/edgar/ownership-parser.d.ts +24 -0
  119. package/dist/services/edgar/ownership-parser.d.ts.map +1 -1
  120. package/dist/services/edgar/ownership-parser.js +82 -0
  121. package/dist/services/edgar/ownership-parser.js.map +1 -1
  122. package/dist/services/edgar/types.d.ts +5 -1
  123. package/dist/services/edgar/types.d.ts.map +1 -1
  124. package/package.json +3 -3
  125. package/server.json +3 -3
  126. package/skills/secedgar-guide/SKILL.md +11 -7
@@ -4,11 +4,12 @@
4
4
  * with backoff, CIK resolution, and ticker/entity caching.
5
5
  * @module services/edgar/edgar-api-service
6
6
  */
7
- import { JsonRpcErrorCode, McpError, notFound, rateLimited, serviceUnavailable, } from '@cyanheads/mcp-ts-core/errors';
7
+ import { JsonRpcErrorCode, McpError, notFound, rateLimited, requestCancelled, serviceUnavailable, timeout, } from '@cyanheads/mcp-ts-core/errors';
8
8
  import { createPacer, httpErrorFromResponse, httpStatusToErrorCode, isRecord, logger, requestContextService, withExtra, } from '@cyanheads/mcp-ts-core/utils';
9
9
  import { parseDocument } from 'htmlparser2';
10
10
  import { getServerConfig } from '../../config/server-config.js';
11
11
  import { getEdgarMirror } from './mirror/index.js';
12
+ import { BodyTextDecoder } from './body-text-decoder.js';
12
13
  import { CALL_FAILURE_BUDGET_MS, CallScope } from './call-scope.js';
13
14
  import formerNamesData from './data/former-names.json' with { type: 'json' };
14
15
  import formerTickersData from './data/former-tickers.json' with { type: 'json' };
@@ -488,9 +489,124 @@ export function suggestCompanies(query, allEntries) {
488
489
  }
489
490
  return suggestions;
490
491
  }
492
+ // ---------------------------------------------------------------------------
493
+ // Side reads (#283)
494
+ // ---------------------------------------------------------------------------
495
+ /** The pacer's name, which its `RequestCancelled` message on disposal carries. */
496
+ const PACER_NAME = 'sec-edgar';
497
+ /**
498
+ * How many pacer start gaps a side read may wait for its turn before it leaves unsent
499
+ * (#283). Every waiter settles by it whatever its own signal, so sustained primary load
500
+ * cannot pile side reads up, and it scales with `EDGAR_RATE_LIMIT_RPS`.
501
+ */
502
+ const SIDE_READ_MAX_WAIT_GAPS = 100;
503
+ /**
504
+ * The tier in front of the FIFO pacer that lets best-effort side reads yield to primary
505
+ * reads (#283). A side read is handed to the pacer only while no primary read is queued
506
+ * there, and one at a time, so a primary read arriving behind waiting side reads starts
507
+ * ahead of all of them, behind at most the one already handed over. A side read that leaves
508
+ * while it waits — its signal fires, a 429 closes the block gate, the service is disposed,
509
+ * or {@link SIDE_READ_MAX_WAIT_GAPS} gaps pass — sends nothing and costs no slot.
510
+ */
511
+ class SideReadTier {
512
+ /** Primary reads handed to the pacer and not yet dispatched or withdrawn. */
513
+ #primariesQueued = 0;
514
+ /** Set while a side read holds the turn: handed to the pacer, not yet dispatched or withdrawn. */
515
+ #turnTaken = false;
516
+ #waiting = [];
517
+ #maxWaitMs;
518
+ constructor(maxWaitMs) {
519
+ this.#maxWaitMs = maxWaitMs;
520
+ }
521
+ /** Counts a primary read as queued in the pacer until the returned release, idempotent, runs. */
522
+ queuePrimary() {
523
+ this.#primariesQueued++;
524
+ return this.#release(() => {
525
+ this.#primariesQueued--;
526
+ });
527
+ }
528
+ /**
529
+ * The turn's release when the turn is free and no primary read is queued, else
530
+ * `undefined`. Synchronous, as a primary read joins the pacer, so a side read asking
531
+ * while the pacer holds no primary read is never overtaken by one asking just after it.
532
+ */
533
+ tryTurn() {
534
+ return this.#open() ? this.#take() : undefined;
535
+ }
536
+ /**
537
+ * Waits, in arrival order, for the turn. Rejects with `signal`'s reason when it fires,
538
+ * and with a `Timeout` once {@link SIDE_READ_MAX_WAIT_GAPS} gaps pass, never having sent.
539
+ */
540
+ waitTurn(signal) {
541
+ if (signal.aborted)
542
+ return Promise.reject(signal.reason);
543
+ const { promise, resolve, reject } = Promise.withResolvers();
544
+ const onAbort = () => this.#drop(waiter, signal.reason);
545
+ const timer = setTimeout(() => this.#drop(waiter, timeout(`SEC EDGAR request not sent: this best-effort read waited ${seconds(this.#maxWaitMs)} s for a pacer slot while other requests held it.`)), this.#maxWaitMs);
546
+ timer.unref?.();
547
+ const waiter = { resolve, reject, signal, onAbort, timer };
548
+ signal.addEventListener('abort', onAbort, { once: true });
549
+ this.#waiting.push(waiter);
550
+ return promise;
551
+ }
552
+ /** Rejects every waiting side read with `error()` — none of them sent. */
553
+ refuseWaiting(error) {
554
+ for (const waiter of this.#waiting.splice(0)) {
555
+ this.#detach(waiter);
556
+ waiter.reject(error());
557
+ }
558
+ }
559
+ #open() {
560
+ return !this.#turnTaken && this.#primariesQueued === 0;
561
+ }
562
+ #take() {
563
+ this.#turnTaken = true;
564
+ return this.#release(() => {
565
+ this.#turnTaken = false;
566
+ });
567
+ }
568
+ /** A once-only release: `undo`, then the turn to the next waiter if that opened it. */
569
+ #release(undo) {
570
+ let released = false;
571
+ return () => {
572
+ if (released)
573
+ return;
574
+ released = true;
575
+ undo();
576
+ this.#pass();
577
+ };
578
+ }
579
+ /** Hands the turn to the longest waiter once it is open. */
580
+ #pass() {
581
+ if (!this.#open())
582
+ return;
583
+ const next = this.#waiting.shift();
584
+ if (!next)
585
+ return;
586
+ this.#detach(next);
587
+ next.resolve(this.#take());
588
+ }
589
+ #drop(waiter, reason) {
590
+ const index = this.#waiting.indexOf(waiter);
591
+ if (index === -1)
592
+ return;
593
+ this.#waiting.splice(index, 1);
594
+ this.#detach(waiter);
595
+ waiter.reject(reason);
596
+ }
597
+ #detach(waiter) {
598
+ clearTimeout(waiter.timer);
599
+ waiter.signal.removeEventListener('abort', waiter.onAbort);
600
+ }
601
+ }
491
602
  class EdgarApiService {
492
- /** One queue for every SEC request in the process, spacing starts at the configured rate. */
603
+ /**
604
+ * One queue for every SEC request in the process, spacing starts at the configured rate.
605
+ * Side reads reach it through {@link sideReads}.
606
+ */
493
607
  pacer;
608
+ /** Holds best-effort side reads back while primary reads are queued in the pacer (#283). */
609
+ sideReads;
494
610
  cooldownMs;
495
611
  gate = OPEN_GATE;
496
612
  tickerCache;
@@ -533,17 +649,18 @@ class EdgarApiService {
533
649
  * gate would hold queued calls until it reopened and then release them all,
534
650
  * where SEC's block needs local refusals and a single probe (the block gate).
535
651
  */
536
- this.pacer = createPacer({
537
- name: 'sec-edgar',
538
- minStartGapMs: Math.ceil(1000 / config.rateLimitRps),
539
- });
652
+ const minStartGapMs = Math.ceil(1000 / config.rateLimitRps);
653
+ this.pacer = createPacer({ name: PACER_NAME, minStartGapMs });
654
+ this.sideReads = new SideReadTier(SIDE_READ_MAX_WAIT_GAPS * minStartGapMs);
540
655
  }
541
656
  /**
542
- * Stop the pacer: queued requests reject with `RequestCancelled`, and so does
543
- * any request made afterwards. Requests already sent are left to finish.
657
+ * Stop the pacer: queued requests and waiting side reads reject with
658
+ * `RequestCancelled`, and so does any request made afterwards. Requests already
659
+ * sent are left to finish.
544
660
  */
545
661
  dispose() {
546
662
  this.pacer.dispose();
663
+ this.sideReads.refuseWaiting(() => requestCancelled(`The ${PACER_NAME} pacer has been disposed.`));
547
664
  }
548
665
  /**
549
666
  * Fetch and parse JSON, throwing on non-OK responses and on a body that is not JSON.
@@ -1037,9 +1154,9 @@ class EdgarApiService {
1037
1154
  }
1038
1155
  /**
1039
1156
  * Fetch the bare SGML submission header (`<accession>.hdr.sgml`, under 1 KB) and read
1040
- * its form, filing date, and period. Returns `null` if the file is absent. The
1041
- * fallback for filings whose index-headers page is missing — common among filings
1042
- * made before 2014; it lists no documents.
1157
+ * its form, filing date, period, and each party's file number. Returns `null` if the
1158
+ * file is absent. The fallback for filings whose index-headers page is missing —
1159
+ * common among filings made before 2014; it lists no documents.
1043
1160
  */
1044
1161
  async tryGetSubmissionHeader(cik, accessionNumber, scope) {
1045
1162
  const text = await this.tryFetchText(filingArchiveUrl(cik, accessionNumber, `${accessionNumber}.hdr.sgml`), scope);
@@ -1303,8 +1420,9 @@ class EdgarApiService {
1303
1420
  * the last attempt decides — a 5xx throws `sec_unavailable` (#233), a backend
1304
1421
  * failure `efts_degraded_response`, the other two `sec_unreachable`. Other
1305
1422
  * non-OK statuses throw at once, as does the local refusal while SEC's
1306
- * rate-limit block is active, and the pacer's `RequestCancelled` — those are
1307
- * `McpError`s from `send()`, never retried.
1423
+ * rate-limit block is active, the pacer's `RequestCancelled`, and a side read's
1424
+ * refusal while it waits for its turn (#283) — those are `McpError`s from
1425
+ * `send()`, never retried.
1308
1426
  *
1309
1427
  * Every failed attempt and every backoff is charged to the call's failure budget,
1310
1428
  * and the ladder ends early once the budget cannot cover another backoff and
@@ -1345,7 +1463,8 @@ class EdgarApiService {
1345
1463
  }
1346
1464
  if (response.ok) {
1347
1465
  const readFrom = Date.now();
1348
- const body = await readBody(response, scope, options.cutoff);
1466
+ const charset = acceptJson ? 'utf-8' : 'declared';
1467
+ const body = await readBody(response, scope, charset, options.cutoff);
1349
1468
  if (body.kind === 'read') {
1350
1469
  const error = options.backendFailure?.(body.text, url);
1351
1470
  if (error === undefined)
@@ -1445,13 +1564,16 @@ class EdgarApiService {
1445
1564
  return serviceUnavailable(`SEC EDGAR (${host}) answered HTTP ${status} on ${onAttempt}${close}`, error.data, { cause: error });
1446
1565
  }
1447
1566
  /**
1448
- * One attempt through the block gate and the pacer, under the caller's signal. A
1449
- * 429 closes the gate before the response is handed back, so no call admitted
1450
- * after it sends. A `fetch` rejection comes back as an unanswered attempt, and so
1451
- * does a probe this call waited on that got no HTTP response; an attempt the spent
1452
- * failure budget kept from going out comes back as `budget_spent`. The gate's
1453
- * refusal and the pacer's `RequestCancelled` throw, and so does the caller's
1454
- * cancel, with its own reason — then a probe settles as having got no answer.
1567
+ * One attempt through the block gate, the side-read tier, and the pacer, under the
1568
+ * caller's signal. A primary read joins the pacer at once; a side read (#283) waits
1569
+ * in the tier for its turn, leaving unsent when its signal fires, a 429 closes the
1570
+ * gate, the service is disposed, or the tier's wait bound passes. A 429 closes the
1571
+ * gate before the response is handed back, so no call admitted after it sends. A
1572
+ * `fetch` rejection comes back as an unanswered attempt, and so does a probe this
1573
+ * call waited on that got no HTTP response; an attempt the spent failure budget kept
1574
+ * from going out comes back as `budget_spent`. The gate's refusal, the pacer's
1575
+ * `RequestCancelled`, and the tier's refusals throw, and so does the caller's cancel,
1576
+ * with its own reason — then a probe settles as having got no answer.
1455
1577
  */
1456
1578
  async send(url, headers, scope) {
1457
1579
  const admission = await this.admit(scope);
@@ -1459,16 +1581,29 @@ class EdgarApiService {
1459
1581
  return admission;
1460
1582
  let outcome;
1461
1583
  try {
1462
- outcome = await this.pacer.run(() => {
1463
- // Re-read at dispatch: a 429 may have landed while this call waited for its
1464
- // slot, and a call queued before the block must not go out inside it.
1465
- if (this.gate !== admission.gate)
1584
+ // Released at dispatch, or on leaving the pacer unsent.
1585
+ const release = scope.sideRead
1586
+ ? (this.sideReads.tryTurn() ?? (await this.sideReads.waitTurn(scope.signal)))
1587
+ : this.sideReads.queuePrimary();
1588
+ try {
1589
+ // A 429 may have closed the gate while this side read waited for its turn, after
1590
+ // the refusal of the side reads still waiting had passed it by.
1591
+ if (scope.sideRead && this.gate !== admission.gate)
1466
1592
  throw this.cooldownRefusal();
1467
- return fetchUntilHeaders(url, headers, scope);
1468
- }, { signal: scope.signal });
1469
- if (outcome.kind === 'answered' && outcome.response.status === 429) {
1470
- this.gate = { state: 'closed', reopensAt: Date.now() + this.cooldownMs };
1593
+ outcome = await this.pacer.run(() => {
1594
+ release();
1595
+ // Re-read at dispatch: a 429 may have landed while this call waited for its
1596
+ // slot, and a call queued before the block must not go out inside it.
1597
+ if (this.gate !== admission.gate)
1598
+ throw this.cooldownRefusal();
1599
+ return fetchUntilHeaders(url, headers, scope);
1600
+ }, { signal: scope.signal });
1471
1601
  }
1602
+ finally {
1603
+ release();
1604
+ }
1605
+ if (outcome.kind === 'answered' && outcome.response.status === 429)
1606
+ this.closeGate();
1472
1607
  return outcome;
1473
1608
  }
1474
1609
  finally {
@@ -1524,6 +1659,15 @@ class EdgarApiService {
1524
1659
  };
1525
1660
  }
1526
1661
  }
1662
+ /**
1663
+ * Close the gate for the full cool-down on SEC's 429, refusing at once every side
1664
+ * read still waiting for its turn (#283); a call already queued in the pacer is
1665
+ * refused at its slot.
1666
+ */
1667
+ closeGate() {
1668
+ this.gate = { state: 'closed', reopensAt: Date.now() + this.cooldownMs };
1669
+ this.sideReads.refuseWaiting(() => this.cooldownRefusal());
1670
+ }
1527
1671
  /** The error for a call made while the cool-down runs — nothing was sent. */
1528
1672
  cooldownRefusal() {
1529
1673
  const retryAfter = this.cooldownSecondsRemaining();
@@ -2164,14 +2308,16 @@ async function fetchUntilHeaders(url, headers, scope) {
2164
2308
  * way. Both cutoff checks run between reads, so neither can cut below one read
2165
2309
  * chunk. Once the caller's signal has fired, the read's rejection is rethrown as
2166
2310
  * it came, never a body failure. A failed read carries the text that arrived
2167
- * before it failed.
2311
+ * before it failed. `charset` picks the decoding ({@link BodyTextDecoder}): UTF-8, or
2312
+ * the charset the response declares in its `Content-Type` or a `<meta>` (#273); a head
2313
+ * read settles the declared charset on its first chunk, so it stops where it always did.
2168
2314
  */
2169
- async function readBody(response, scope, cutoff) {
2315
+ async function readBody(response, scope, charset, cutoff) {
2170
2316
  if (!response.body)
2171
2317
  return { kind: 'read', text: '' };
2172
2318
  const stalled = new DOMException("No body bytes within the read's idle limit.", 'TimeoutError');
2173
2319
  const reader = response.body.getReader();
2174
- const decoder = new TextDecoder();
2320
+ const decoder = new BodyTextDecoder(charset, response.headers.get('content-type'), cutoff !== undefined);
2175
2321
  let text = '';
2176
2322
  let bytes = 0;
2177
2323
  let capMs = 0;
@@ -2182,11 +2328,11 @@ async function readBody(response, scope, cutoff) {
2182
2328
  readFrom = Date.now();
2183
2329
  const { done, value } = await nextChunk(reader, stalled, capMs, scope.signal);
2184
2330
  if (done) {
2185
- text += decoder.decode();
2331
+ text += decoder.end();
2186
2332
  break;
2187
2333
  }
2188
2334
  bytes += value.byteLength;
2189
- text += decoder.decode(value, { stream: true });
2335
+ text += decoder.push(value);
2190
2336
  if (cutoff?.stopAt !== undefined && text.includes(cutoff.stopAt))
2191
2337
  break;
2192
2338
  }
@@ -2201,7 +2347,7 @@ async function readBody(response, scope, cutoff) {
2201
2347
  capMs,
2202
2348
  rejection,
2203
2349
  stalled: rejection === stalled,
2204
- text,
2350
+ text: text + decoder.settle(),
2205
2351
  waitedMs: Date.now() - readFrom,
2206
2352
  };
2207
2353
  }
@@ -2227,7 +2373,7 @@ async function errorBodyHead(response, scope) {
2227
2373
  // Up to 3 bytes of a split code point stay in the decoder, so a read stopped at
2228
2374
  // this cutoff still holds more than the limit as text: a body cut short is never
2229
2375
  // mistaken for a whole one.
2230
- const read = await readBody(response, scope, { maxBytes: ERROR_BODY_LIMIT_BYTES + 4 });
2376
+ const read = await readBody(response, scope, 'utf-8', { maxBytes: ERROR_BODY_LIMIT_BYTES + 4 });
2231
2377
  if (read.kind === 'body_failed')
2232
2378
  scope.charge(read.waitedMs);
2233
2379
  const cut = cutToErrorLimit(read.text);