@cliwant/mcp-sam-gov 1.5.0 → 1.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.
Files changed (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.ja.md +240 -231
  3. package/README.ko.md +240 -231
  4. package/README.md +725 -714
  5. package/dist/errors.d.ts +10 -0
  6. package/dist/errors.d.ts.map +1 -1
  7. package/dist/errors.js.map +1 -1
  8. package/dist/feedback.d.ts +64 -0
  9. package/dist/feedback.d.ts.map +1 -0
  10. package/dist/feedback.js +131 -0
  11. package/dist/feedback.js.map +1 -0
  12. package/dist/server.d.ts.map +1 -1
  13. package/dist/server.js +44 -2
  14. package/dist/server.js.map +1 -1
  15. package/package.json +111 -111
  16. package/src/attachments.ts +652 -652
  17. package/src/bea.ts +372 -372
  18. package/src/bls.ts +1943 -1943
  19. package/src/cache.ts +73 -73
  20. package/src/cbp-border.ts +177 -177
  21. package/src/census-economic.ts +431 -431
  22. package/src/census.ts +735 -735
  23. package/src/ckan.ts +495 -495
  24. package/src/clinicaltrials.ts +923 -923
  25. package/src/cms-facility.ts +379 -379
  26. package/src/cms-hospital.ts +344 -344
  27. package/src/cms-supplier.ts +527 -527
  28. package/src/cms-utilization.ts +389 -389
  29. package/src/cms.ts +634 -634
  30. package/src/coerce.ts +47 -47
  31. package/src/courtlistener.ts +465 -465
  32. package/src/cpsc.ts +333 -333
  33. package/src/datagov-catalog.ts +312 -312
  34. package/src/datagov.ts +907 -907
  35. package/src/datagovKey.ts +68 -68
  36. package/src/datasource.ts +721 -721
  37. package/src/disclosure.ts +61 -61
  38. package/src/dol.ts +515 -515
  39. package/src/ecfr.ts +248 -248
  40. package/src/echo.ts +496 -496
  41. package/src/edgar.ts +3046 -3046
  42. package/src/epa-envirofacts.ts +358 -358
  43. package/src/errors.ts +324 -314
  44. package/src/fac.ts +529 -529
  45. package/src/far.ts +1009 -1009
  46. package/src/fdic.ts +2052 -2052
  47. package/src/federal-register.ts +725 -725
  48. package/src/feedback.ts +160 -0
  49. package/src/fema.ts +680 -680
  50. package/src/fpds.ts +620 -620
  51. package/src/fred.ts +464 -464
  52. package/src/gao.ts +744 -744
  53. package/src/gov-domains.ts +237 -237
  54. package/src/govinfo.ts +497 -497
  55. package/src/grants.ts +290 -290
  56. package/src/gsa-csv.ts +992 -992
  57. package/src/gsa-perdiem.ts +361 -361
  58. package/src/integrity.ts +928 -928
  59. package/src/keys.ts +268 -268
  60. package/src/lda.ts +385 -385
  61. package/src/meta.ts +292 -292
  62. package/src/nhtsa.ts +352 -352
  63. package/src/nih.ts +375 -375
  64. package/src/nist-controls.ts +219 -219
  65. package/src/nonprofit.ts +460 -460
  66. package/src/nppes.ts +834 -834
  67. package/src/nsf.ts +706 -706
  68. package/src/nvd.ts +1124 -1124
  69. package/src/nws-weather.ts +167 -167
  70. package/src/ofac.ts +1166 -1166
  71. package/src/openfda-device.ts +356 -356
  72. package/src/openfda-drugsfda.ts +313 -313
  73. package/src/openfda.ts +518 -518
  74. package/src/pricing.ts +1075 -1075
  75. package/src/sam-gov/client.ts +774 -774
  76. package/src/sam-gov/index.ts +32 -32
  77. package/src/sam-gov/types.ts +152 -152
  78. package/src/sba.ts +357 -357
  79. package/src/server.ts +6688 -6639
  80. package/src/snapshot.ts +223 -223
  81. package/src/socrata.ts +532 -532
  82. package/src/treasury.ts +582 -582
  83. package/src/usaspending.ts +2852 -2852
  84. package/src/usitc.ts +420 -420
@@ -1,431 +1,431 @@
1
- /**
2
- * US Census — County Business Patterns (CBP) — the MARKET-SIZING lane
3
- * (ADR-0047, Wave-4 source #1). NAICS × geography establishments / employment /
4
- * annual payroll — the demand-side complement to BLS-QCEW + USAspending in the
5
- * B2G market-sizing set.
6
- *
7
- * ★ THIS IS THE SERVER'S FIRST KEY-REQUIRED SOURCE. The Census Data API removed
8
- * its keyless tier — a request WITHOUT a key is 302-redirected to a "Missing
9
- * Key" HTML page. So, honestly: with NO `CENSUS_API_KEY` this tool THROWS an
10
- * `invalid_input` config error BEFORE any fetch (never a fake-empty, never a
11
- * keyless-pretend). The other tools stay keyless — this key is scoped to
12
- * this one source. (Contrast the OPTIONAL keys of datagov/bls/nvd, which lift a
13
- * tier but are not required.)
14
- *
15
- * DIFFERENT HOST than census.ts (the geocoder, geocoding.geo.census.gov): the
16
- * DATA API is `api.census.gov/data/{year}/cbp`. This module COPIES (does NOT
17
- * import) the census.ts fixed-host SSRF idiom (a single host const + a
18
- * post-construction `new URL().hostname` assertion + `redirect:"error"`) and does
19
- * NOT touch census_geocode.
20
- *
21
- * Coercion/meta code is REUSED (`driftError`, `errorFromResponse`, `num`
22
- * coerce.ts null-never-0, `withMeta`/`buildMeta`). The ONE bespoke bit is the
23
- * fetch: a single `fetch(redirect:"manual")` (NOT the shared getJson) so a
24
- * missing/invalid-key 302 surfaces as an INSPECTABLE opaque-redirect → honest
25
- * invalid_input, instead of undici's redirect:"error" TypeError that
26
- * fetchWithRetry would mask as a retryable outage (see the fetch block). The
27
- * optional-key leak discipline is MIRRORED from datagovKey.ts/bls.ts — but here
28
- * the key is REQUIRED and rides ONLY in the `&key=` query param, NOWHERE else
29
- * (never the label, `_meta.source`, notes, or a log — the K-test).
30
- *
31
- * GET https://api.census.gov/data/{year}/cbp
32
- * ?get=NAME,NAICS2017_LABEL,ESTAB,EMP,PAYANN,GEO_ID
33
- * &for=<geoClause> (us:* | state:* | state:NN | county:*)
34
- * &in=state:NN (county queries only)
35
- * &NAICS2017=<naics> (optional NAICS filter)
36
- * &key=<CENSUS_API_KEY> (REQUIRED)
37
- * → a 2D JSON ARRAY: row 0 = column headers, rows 1..N = data. e.g.
38
- * [["NAME","ESTAB","EMP","PAYANN","NAICS2017","NAICS2017_LABEL","state"],
39
- * ["California","39755","...","...","5415","...","06"], ...]
40
- *
41
- * ★ HONESTY (ADR-0047 P1–P5):
42
- * [KEY] no key ⇒ invalid_input THROW pre-fetch (0 fetch); the message names
43
- * CENSUS_API_KEY + the free-signup URL. A wire 302 (a key that IS set but is
44
- * invalid → the Missing-Key page) is caught via redirect:"manual" as an
45
- * opaque-redirect ⇒ invalid_input "check CENSUS_API_KEY" (never a
46
- * fake-empty, never a masked outage).
47
- * [P1] CBP returns the COMPLETE geography set for the filter (no server
48
- * pagination) ⇒ totalAvailable = the row count, complete:true. NEVER
49
- * fabricated (RED if totalAvailable = header-length or invented).
50
- * [P3] ★the sentinel→null crux: Census suppresses/withholds cells with large
51
- * NEGATIVE sentinels (-999999999 / -888888888 / -666666666 …). `censusNum`
52
- * maps any value ≤ -100000000 to **null** (withheld) — NEVER a negative
53
- * number, NEVER 0. A genuine 0 stays 0. `annualPayrollUsd = PAYANN×1000`
54
- * (PAYANN is in $1,000 units), null-preserving.
55
- * [P2] a 302 ⇒ invalid_input (key); a header-only body ⇒ honest empty
56
- * (returned:0, complete:true); a 5xx ⇒ upstream_unavailable THROW; a 200
57
- * non-JSON ⇒ schema_drift.
58
- * [P4] a body that is not an array, or whose row 0 is not a string[] header
59
- * row ⇒ driftError (never a fabricated empty).
60
- * [SSRF] fixed host; `year` re-guarded ^\d{4}$ (it rides in the PATH); `naics`
61
- * ^\d{2,6}$; `state` ^\d{2}$; geography enum {us,state,county}. All
62
- * predicate VALUES ride in URLSearchParams. The key rides `&key=` ONLY.
63
- */
64
-
65
- import { ToolErrorCarrier, errorFromResponse } from "./errors.js";
66
- import { driftError } from "./datasource.js";
67
- import { num, str } from "./coerce.js";
68
- import { withMeta, type MetaBundle, type ResponseMeta } from "./meta.js";
69
-
70
- // Re-export the shared honesty coercion (single audited copy in ./coerce.js —
71
- // ADR-0005 v2 FIX-C) so a num regression fails together across sources. NO local
72
- // num/str.
73
- export { num };
74
-
75
- // ─── SSRF core: the single fixed host (DIFFERENT from census.ts) ──
76
- const CENSUS_DATA_HOST = "api.census.gov";
77
- const CENSUS_DATA_LABEL = "census:/data/cbp"; // host-only ToolError surface; NO token, NO key
78
-
79
- // ─── Validation charclasses (SSRF + "verify the input" honesty) ───
80
- const YEAR_RE = /^\d{4}$/; // rides in the PATH — strict 4-digit (no path injection)
81
- const NAICS_RE = /^\d{2,6}$/; // 2–6 digit NAICS-2017 sector/code
82
- const STATE_FIPS_RE = /^\d{2}$/; // 2-digit state FIPS
83
- const GEOGRAPHIES = new Set(["us", "state", "county"]);
84
-
85
- // DEFENSIVE large-negative sentinel floor. Some Census products (ACS/SAIPE) encode a
86
- // withheld/unavailable cell as a large NEGATIVE jam value (-999999999 / -888888888 /
87
- // -666666666 …); establishment/employment/payroll counts are non-negative, so any
88
- // value at/below this floor is a sentinel, NOT data → mapped to null.
89
- // ★HONESTY CAVEAT: CBP itself does NOT primarily use these jam values — modern CBP
90
- // uses NOISE INFUSION (EMP_N noise-range columns) + suppression FLAGS (EMP_N_F …),
91
- // which this tool does NOT currently request or interpret (it surfaces values as
92
- // reported). So this floor is a conservative cross-product guard, not CBP's confirmed
93
- // mechanism; a keyed live verification of CBP's exact withheld-cell encoding is pending
94
- // (no CENSUS_API_KEY was available at build time). See SUPPRESSED_NOTE.
95
- const CENSUS_SENTINEL_FLOOR = -100000000;
96
-
97
- const DEFAULT_YEAR = "2022"; // the latest confirmed CBP vintage (ADR-0047)
98
-
99
- // ─── Honesty notes (ADR-0047 required set) ────────────────────────
100
- const KEY_REQUIRED_NOTE =
101
- "This source REQUIRES a free CENSUS_API_KEY (the Census Data API has no keyless tier). The key is sent ONLY as the &key= query parameter to api.census.gov and is NEVER logged, echoed, or placed in this response.";
102
- const PAYROLL_UNITS_NOTE =
103
- "annualPayrollUsd is ANNUAL payroll in US dollars, converted from the Census PAYANN field's $1,000 units (×1000). establishments and employees are integer counts (as-of the reference year).";
104
- const SUPPRESSED_NOTE =
105
- "Disclosure protection: any large-negative jam sentinel (e.g. -999999999) is mapped to null (withheld) — NEVER a negative number and NEVER 0; a genuine 0 is preserved as 0. NOTE: modern CBP applies NOISE INFUSION (perturbed values) plus suppression flag columns (e.g. EMP_N_F) rather than jam sentinels; this tool surfaces values as reported and does not currently interpret suppression flags, so a flagged/noise-infused cell is returned as its reported number — treat exact small counts as approximate.";
106
- const NO_PAGINATION_NOTE =
107
- "CBP returns the COMPLETE set of geographies matching the filter (no server-side pagination); totalAvailable equals the number of rows returned. Narrow with naics / geography to reduce the row count.";
108
-
109
- // ─── The key seam (REQUIRED; value NEVER leaked past the &key= param) ──
110
- /** Read CENSUS_API_KEY from env; trim; return the value or undefined (unset/blank). */
111
- export function censusApiKey(): string | undefined {
112
- const raw = process.env.CENSUS_API_KEY;
113
- const trimmed = typeof raw === "string" ? raw.trim() : "";
114
- return trimmed ? trimmed : undefined;
115
- }
116
-
117
- // ─── Curated row shape ────────────────────────────────────────────
118
- export type CbpRow = {
119
- name: string | null; // the geography NAME (e.g. "California")
120
- geoId: string | null; // GEO_ID (a STRING — leading zeros survive)
121
- naicsCode: string | null; // NAICS2017 (a STRING — sector codes carry structure)
122
- naicsLabel: string | null; // NAICS2017_LABEL
123
- establishments: number | null; // ESTAB — null when suppressed (NEVER negative/0-lie)
124
- employees: number | null; // EMP — null when suppressed
125
- annualPayrollUsd: number | null; // PAYANN×1000 — null when suppressed
126
- state: string | null; // state FIPS (a STRING — leading zeros survive)
127
- };
128
-
129
- /** num(), but map the Census negative suppression sentinel family → null (withheld). */
130
- function censusNum(v: unknown): number | null {
131
- const n = num(v);
132
- if (n === null) return null;
133
- // A large-negative sentinel is a WITHHELD/suppressed cell, never data. A genuine
134
- // 0 (n > floor) passes through as 0.
135
- if (n <= CENSUS_SENTINEL_FLOOR) return null;
136
- return n;
137
- }
138
-
139
- /** Annual payroll: PAYANN is in $1,000 units → ×1000; null-preserving. */
140
- function mul1000(n: number | null): number | null {
141
- return n === null ? null : n * 1000;
142
- }
143
-
144
- export type CensusBusinessPatternsArgs = {
145
- naics?: string;
146
- geography?: string; // us | state | county (default us)
147
- state?: string; // 2-digit FIPS (required for county; optional filter for state)
148
- year?: string; // ^\d{4}$ (default 2022)
149
- limit?: number; // OPTIONAL client-side top-N slice (CBP has no server pagination)
150
- };
151
-
152
- /**
153
- * Fetch County Business Patterns rows for a NAICS × geography filter → normalized
154
- * establishment / employment / annual-payroll rows + honest `_meta`. REQUIRES
155
- * CENSUS_API_KEY (throws invalid_input pre-fetch when unset). The 2D-array body is
156
- * parsed by HEADER NAME (order-independent); suppressed cells map to null.
157
- */
158
- export async function businessPatterns(
159
- args: CensusBusinessPatternsArgs,
160
- ): Promise<MetaBundle> {
161
- // ── [KEY] REQUIRED key — throw an honest config error BEFORE any fetch. ──
162
- const key = censusApiKey();
163
- if (key === undefined) {
164
- throw new ToolErrorCarrier({
165
- kind: "invalid_input",
166
- retryable: false,
167
- message:
168
- "Census Data API requires a free key. Get one at https://api.census.gov/data/key_signup.html and set CENSUS_API_KEY.",
169
- upstreamEndpoint: CENSUS_DATA_LABEL,
170
- });
171
- }
172
-
173
- // ── Validate + default the inputs (belt-and-suspenders behind the server Zod;
174
- // a DIRECT handler call bypasses Zod). ──
175
- const year = args.year ?? DEFAULT_YEAR;
176
- if (!YEAR_RE.test(year)) {
177
- throw new ToolErrorCarrier({
178
- kind: "invalid_input",
179
- retryable: false,
180
- message: `Invalid year ${JSON.stringify(year)} — expected a 4-digit year (^\\d{4}$), e.g. "2022". (year rides in the request PATH; it is strictly validated.)`,
181
- upstreamEndpoint: CENSUS_DATA_LABEL,
182
- });
183
- }
184
-
185
- const geography = args.geography ?? "us";
186
- if (!GEOGRAPHIES.has(geography)) {
187
- throw new ToolErrorCarrier({
188
- kind: "invalid_input",
189
- retryable: false,
190
- message: `Invalid geography ${JSON.stringify(geography)} — expected one of us, state, county.`,
191
- upstreamEndpoint: CENSUS_DATA_LABEL,
192
- });
193
- }
194
-
195
- if (args.state !== undefined && !STATE_FIPS_RE.test(args.state)) {
196
- throw new ToolErrorCarrier({
197
- kind: "invalid_input",
198
- retryable: false,
199
- message: `Invalid state ${JSON.stringify(args.state)} — expected a 2-digit state FIPS code (^\\d{2}$), e.g. "06" (California).`,
200
- upstreamEndpoint: CENSUS_DATA_LABEL,
201
- });
202
- }
203
-
204
- if (args.naics !== undefined && !NAICS_RE.test(args.naics)) {
205
- throw new ToolErrorCarrier({
206
- kind: "invalid_input",
207
- retryable: false,
208
- message: `Invalid naics ${JSON.stringify(args.naics)} — expected a 2–6 digit NAICS-2017 code (^\\d{2,6}$), e.g. "5415" (Computer Systems Design).`,
209
- upstreamEndpoint: CENSUS_DATA_LABEL,
210
- });
211
- }
212
-
213
- // ── Resolve the geography clause (for=… [+ in=state:…]). ──
214
- let forClause: string;
215
- let inClause: string | undefined;
216
- let geoFilter: string;
217
- if (geography === "us") {
218
- forClause = "us:*";
219
- geoFilter = "geography:us";
220
- } else if (geography === "state") {
221
- forClause = args.state !== undefined ? `state:${args.state}` : "state:*";
222
- geoFilter = `geography:state:${args.state ?? "*"}`;
223
- } else {
224
- // county — requires a state (the CBP `in=state:` predicate is mandatory).
225
- if (args.state === undefined) {
226
- throw new ToolErrorCarrier({
227
- kind: "invalid_input",
228
- retryable: false,
229
- message:
230
- "geography 'county' requires `state` (a 2-digit FIPS) — CBP county queries need an `in=state:NN` predicate. Pass state, e.g. state:'06'.",
231
- upstreamEndpoint: CENSUS_DATA_LABEL,
232
- });
233
- }
234
- forClause = "county:*";
235
- inClause = `state:${args.state}`;
236
- geoFilter = `geography:county:* in state:${args.state}`;
237
- }
238
-
239
- // ── Build the query (all VALUES via URLSearchParams — no host/path steer; the
240
- // REQUIRED key rides ONLY here in &key=). ──
241
- const params = new URLSearchParams();
242
- params.set("get", "NAME,NAICS2017_LABEL,ESTAB,EMP,PAYANN,GEO_ID");
243
- params.set("for", forClause);
244
- if (inClause !== undefined) params.set("in", inClause);
245
- if (args.naics !== undefined) params.set("NAICS2017", args.naics);
246
- params.set("key", key);
247
-
248
- const url = `https://${CENSUS_DATA_HOST}/data/${year}/cbp?${params.toString()}`;
249
- // Belt-and-suspenders: the fixed host + strictly-validated path leave nothing to
250
- // steer the authority; assert the built URL cannot have been moved off-host.
251
- const built = new URL(url);
252
- if (built.hostname !== CENSUS_DATA_HOST || built.protocol !== "https:") {
253
- throw new ToolErrorCarrier({
254
- kind: "invalid_input",
255
- retryable: false,
256
- message: `Constructed Census Data URL host ${JSON.stringify(built.hostname)} (${built.protocol}) is not ${CENSUS_DATA_HOST} over https — refusing to fetch (SSRF safety).`,
257
- upstreamEndpoint: CENSUS_DATA_LABEL,
258
- });
259
- }
260
-
261
- // ── Fetch with redirect:"manual" — the KEY-ERROR DETECTION crux. A missing or
262
- // invalid key makes the Census Data API 302-redirect to its "Missing Key" page
263
- // (live-verified: `HTTP 302` + `Location: /data/missing_key.html` +
264
- // `X-DataWebAPI-KeyError: 1`). We must NOT use redirect:"error" via getJson
265
- // here: undici rejects an "error"-mode redirect with a TypeError that the
266
- // shared fetchWithRetry catch reclassifies to a *retryable upstream_unavailable*
267
- // — masking a key-config error as a transient outage. redirect:"manual" instead
268
- // yields an INSPECTABLE opaque-redirect (type "opaqueredirect", status 0), so
269
- // the missing/invalid key surfaces as an honest invalid_input. This is a
270
- // SINGLE classified attempt (no auto-retry): a transient 5xx THROWS
271
- // upstream_unavailable — re-invoke the tool to retry. The 5xx/404/400 taxonomy
272
- // is delegated to the shared errors.ts `errorFromResponse`; a 200 non-JSON body
273
- // ⇒ r.json() SyntaxError ⇒ schema_drift. The redirect is NEVER followed, so no
274
- // off-host hop can occur (a stronger SSRF posture than redirect:"error"). ──
275
- let res: Response;
276
- try {
277
- res = await fetch(built.toString(), {
278
- redirect: "manual",
279
- signal: AbortSignal.timeout(15_000),
280
- });
281
- } catch (e) {
282
- // Timeout/abort ⇒ non-retryable (the same aborted signal would re-reject);
283
- // a genuine network TypeError ⇒ retryable upstream_unavailable. NEVER empty.
284
- if (
285
- e instanceof Error &&
286
- (e.name === "TimeoutError" || e.name === "AbortError")
287
- ) {
288
- throw new ToolErrorCarrier({
289
- kind: "upstream_unavailable",
290
- message: `Request to ${CENSUS_DATA_LABEL} timed out.`,
291
- retryable: false,
292
- upstreamEndpoint: CENSUS_DATA_LABEL,
293
- });
294
- }
295
- throw new ToolErrorCarrier({
296
- kind: "upstream_unavailable",
297
- message: `Network error reaching ${CENSUS_DATA_LABEL}: ${e instanceof Error ? e.message : String(e)}`,
298
- retryable: true,
299
- retryAfterSeconds: 30,
300
- upstreamEndpoint: CENSUS_DATA_LABEL,
301
- });
302
- }
303
-
304
- // [KEY] A redirect (opaque-redirect via redirect:"manual", or a raw 3xx status) ⇒
305
- // the missing/invalid-key "Missing Key" page ⇒ an honest key-config error, NEVER
306
- // a fake-empty (swallowing this as empty ⇒ RED in the fault suite).
307
- if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
308
- throw new ToolErrorCarrier({
309
- kind: "invalid_input",
310
- retryable: false,
311
- message:
312
- "Census Data API redirected the request to its 'Missing Key' page — CENSUS_API_KEY is missing or invalid. Get or check a free key at https://api.census.gov/data/key_signup.html.",
313
- upstreamEndpoint: CENSUS_DATA_LABEL,
314
- });
315
- }
316
-
317
- // [P2] 404/429/5xx/4xx ⇒ the shared errors.ts taxonomy (a DOWN service is NEVER
318
- // an empty result; 400 → invalid_input, 5xx → upstream_unavailable, …).
319
- if (!res.ok) {
320
- throw new ToolErrorCarrier(errorFromResponse(res, CENSUS_DATA_LABEL));
321
- }
322
-
323
- // [P4] 200 ⇒ parse JSON; a non-JSON body (an HTML error page at 200) makes
324
- // r.json() throw a SyntaxError ⇒ schema_drift (never read as an empty result).
325
- let body: unknown;
326
- try {
327
- body = await res.json();
328
- } catch (e) {
329
- if (e instanceof SyntaxError) {
330
- throw driftError(
331
- CENSUS_DATA_LABEL,
332
- "Census CBP returned a non-JSON body at HTTP 200 (likely an HTML 'Missing Key' / error page) — treating as schema drift (never read as an empty result).",
333
- );
334
- }
335
- throw e;
336
- }
337
-
338
- // ── [P4] Parse the 2D array: row 0 = string[] header, rows 1..N = data. ──
339
- if (!Array.isArray(body) || body.length === 0) {
340
- throw driftError(
341
- CENSUS_DATA_LABEL,
342
- "Census CBP returned a body that is not a non-empty 2D array — treating as schema drift (never a fabricated empty).",
343
- );
344
- }
345
- const header = body[0];
346
- if (
347
- !Array.isArray(header) ||
348
- header.length === 0 ||
349
- !header.every((h) => typeof h === "string")
350
- ) {
351
- throw driftError(
352
- CENSUS_DATA_LABEL,
353
- "Census CBP row 0 is not a string[] header row — treating as schema drift (the 2D-array contract changed; never a fabricated empty).",
354
- );
355
- }
356
-
357
- // Header-name → column index (order-independent; a missing column ⇒ index -1 ⇒
358
- // the field maps to null, never a positional mis-read).
359
- const idx = new Map<string, number>();
360
- (header as string[]).forEach((h, i) => idx.set(h, i));
361
- const col = (row: unknown[], name: string): unknown => {
362
- const i = idx.get(name);
363
- return i === undefined || i < 0 ? undefined : row[i];
364
- };
365
-
366
- const allRows: CbpRow[] = [];
367
- for (let i = 1; i < body.length; i++) {
368
- const raw = body[i];
369
- if (!Array.isArray(raw)) {
370
- throw driftError(
371
- CENSUS_DATA_LABEL,
372
- `Census CBP data row ${i} is not an array — treating as schema drift (never a fabricated empty).`,
373
- );
374
- }
375
- const row = raw as unknown[];
376
- allRows.push({
377
- name: str(col(row, "NAME")),
378
- geoId: str(col(row, "GEO_ID")),
379
- naicsCode: str(col(row, "NAICS2017")),
380
- naicsLabel: str(col(row, "NAICS2017_LABEL")),
381
- establishments: censusNum(col(row, "ESTAB")),
382
- employees: censusNum(col(row, "EMP")),
383
- annualPayrollUsd: mul1000(censusNum(col(row, "PAYANN"))),
384
- state: str(col(row, "state")),
385
- });
386
- }
387
-
388
- // ── [P1] The COMPLETE set for the filter (no server pagination). An OPTIONAL
389
- // client-side top-N slice is disclosed (totalAvailable stays the full count,
390
- // so buildMeta derives truncated/complete honestly). ──
391
- const totalAvailable = allRows.length;
392
- const notes: string[] = [
393
- KEY_REQUIRED_NOTE,
394
- PAYROLL_UNITS_NOTE,
395
- SUPPRESSED_NOTE,
396
- NO_PAGINATION_NOTE,
397
- ];
398
-
399
- let rows = allRows;
400
- if (
401
- typeof args.limit === "number" &&
402
- Number.isFinite(args.limit) &&
403
- args.limit >= 0 &&
404
- args.limit < allRows.length
405
- ) {
406
- rows = allRows.slice(0, args.limit);
407
- notes.push(
408
- `Returned the first ${rows.length} of ${totalAvailable} rows (client-side limit=${args.limit}); CBP has NO server-side pagination, so the remaining ${totalAvailable - rows.length} are not fetched separately — raise limit or narrow the filter to see them.`,
409
- );
410
- }
411
-
412
- const filtersApplied = [
413
- args.naics !== undefined ? `naics:${args.naics}` : "naics:(all)",
414
- geoFilter,
415
- `year:${year}`,
416
- ];
417
-
418
- const meta: Partial<ResponseMeta> = {
419
- // MODE only — never the key value (K-test).
420
- source: `api.census.gov /data/${year}/cbp (County Business Patterns; CENSUS_API_KEY)`,
421
- keylessMode: false, // ★KEYED — the first key-required source
422
- returned: rows.length,
423
- totalAvailable,
424
- filtersApplied,
425
- filtersDropped: [],
426
- fieldsUnavailable: [],
427
- notes,
428
- };
429
-
430
- return withMeta({ rows }, meta);
431
- }
1
+ /**
2
+ * US Census — County Business Patterns (CBP) — the MARKET-SIZING lane
3
+ * (ADR-0047, Wave-4 source #1). NAICS × geography establishments / employment /
4
+ * annual payroll — the demand-side complement to BLS-QCEW + USAspending in the
5
+ * B2G market-sizing set.
6
+ *
7
+ * ★ THIS IS THE SERVER'S FIRST KEY-REQUIRED SOURCE. The Census Data API removed
8
+ * its keyless tier — a request WITHOUT a key is 302-redirected to a "Missing
9
+ * Key" HTML page. So, honestly: with NO `CENSUS_API_KEY` this tool THROWS an
10
+ * `invalid_input` config error BEFORE any fetch (never a fake-empty, never a
11
+ * keyless-pretend). The other tools stay keyless — this key is scoped to
12
+ * this one source. (Contrast the OPTIONAL keys of datagov/bls/nvd, which lift a
13
+ * tier but are not required.)
14
+ *
15
+ * DIFFERENT HOST than census.ts (the geocoder, geocoding.geo.census.gov): the
16
+ * DATA API is `api.census.gov/data/{year}/cbp`. This module COPIES (does NOT
17
+ * import) the census.ts fixed-host SSRF idiom (a single host const + a
18
+ * post-construction `new URL().hostname` assertion + `redirect:"error"`) and does
19
+ * NOT touch census_geocode.
20
+ *
21
+ * Coercion/meta code is REUSED (`driftError`, `errorFromResponse`, `num`
22
+ * coerce.ts null-never-0, `withMeta`/`buildMeta`). The ONE bespoke bit is the
23
+ * fetch: a single `fetch(redirect:"manual")` (NOT the shared getJson) so a
24
+ * missing/invalid-key 302 surfaces as an INSPECTABLE opaque-redirect → honest
25
+ * invalid_input, instead of undici's redirect:"error" TypeError that
26
+ * fetchWithRetry would mask as a retryable outage (see the fetch block). The
27
+ * optional-key leak discipline is MIRRORED from datagovKey.ts/bls.ts — but here
28
+ * the key is REQUIRED and rides ONLY in the `&key=` query param, NOWHERE else
29
+ * (never the label, `_meta.source`, notes, or a log — the K-test).
30
+ *
31
+ * GET https://api.census.gov/data/{year}/cbp
32
+ * ?get=NAME,NAICS2017_LABEL,ESTAB,EMP,PAYANN,GEO_ID
33
+ * &for=<geoClause> (us:* | state:* | state:NN | county:*)
34
+ * &in=state:NN (county queries only)
35
+ * &NAICS2017=<naics> (optional NAICS filter)
36
+ * &key=<CENSUS_API_KEY> (REQUIRED)
37
+ * → a 2D JSON ARRAY: row 0 = column headers, rows 1..N = data. e.g.
38
+ * [["NAME","ESTAB","EMP","PAYANN","NAICS2017","NAICS2017_LABEL","state"],
39
+ * ["California","39755","...","...","5415","...","06"], ...]
40
+ *
41
+ * ★ HONESTY (ADR-0047 P1–P5):
42
+ * [KEY] no key ⇒ invalid_input THROW pre-fetch (0 fetch); the message names
43
+ * CENSUS_API_KEY + the free-signup URL. A wire 302 (a key that IS set but is
44
+ * invalid → the Missing-Key page) is caught via redirect:"manual" as an
45
+ * opaque-redirect ⇒ invalid_input "check CENSUS_API_KEY" (never a
46
+ * fake-empty, never a masked outage).
47
+ * [P1] CBP returns the COMPLETE geography set for the filter (no server
48
+ * pagination) ⇒ totalAvailable = the row count, complete:true. NEVER
49
+ * fabricated (RED if totalAvailable = header-length or invented).
50
+ * [P3] ★the sentinel→null crux: Census suppresses/withholds cells with large
51
+ * NEGATIVE sentinels (-999999999 / -888888888 / -666666666 …). `censusNum`
52
+ * maps any value ≤ -100000000 to **null** (withheld) — NEVER a negative
53
+ * number, NEVER 0. A genuine 0 stays 0. `annualPayrollUsd = PAYANN×1000`
54
+ * (PAYANN is in $1,000 units), null-preserving.
55
+ * [P2] a 302 ⇒ invalid_input (key); a header-only body ⇒ honest empty
56
+ * (returned:0, complete:true); a 5xx ⇒ upstream_unavailable THROW; a 200
57
+ * non-JSON ⇒ schema_drift.
58
+ * [P4] a body that is not an array, or whose row 0 is not a string[] header
59
+ * row ⇒ driftError (never a fabricated empty).
60
+ * [SSRF] fixed host; `year` re-guarded ^\d{4}$ (it rides in the PATH); `naics`
61
+ * ^\d{2,6}$; `state` ^\d{2}$; geography enum {us,state,county}. All
62
+ * predicate VALUES ride in URLSearchParams. The key rides `&key=` ONLY.
63
+ */
64
+
65
+ import { ToolErrorCarrier, errorFromResponse } from "./errors.js";
66
+ import { driftError } from "./datasource.js";
67
+ import { num, str } from "./coerce.js";
68
+ import { withMeta, type MetaBundle, type ResponseMeta } from "./meta.js";
69
+
70
+ // Re-export the shared honesty coercion (single audited copy in ./coerce.js —
71
+ // ADR-0005 v2 FIX-C) so a num regression fails together across sources. NO local
72
+ // num/str.
73
+ export { num };
74
+
75
+ // ─── SSRF core: the single fixed host (DIFFERENT from census.ts) ──
76
+ const CENSUS_DATA_HOST = "api.census.gov";
77
+ const CENSUS_DATA_LABEL = "census:/data/cbp"; // host-only ToolError surface; NO token, NO key
78
+
79
+ // ─── Validation charclasses (SSRF + "verify the input" honesty) ───
80
+ const YEAR_RE = /^\d{4}$/; // rides in the PATH — strict 4-digit (no path injection)
81
+ const NAICS_RE = /^\d{2,6}$/; // 2–6 digit NAICS-2017 sector/code
82
+ const STATE_FIPS_RE = /^\d{2}$/; // 2-digit state FIPS
83
+ const GEOGRAPHIES = new Set(["us", "state", "county"]);
84
+
85
+ // DEFENSIVE large-negative sentinel floor. Some Census products (ACS/SAIPE) encode a
86
+ // withheld/unavailable cell as a large NEGATIVE jam value (-999999999 / -888888888 /
87
+ // -666666666 …); establishment/employment/payroll counts are non-negative, so any
88
+ // value at/below this floor is a sentinel, NOT data → mapped to null.
89
+ // ★HONESTY CAVEAT: CBP itself does NOT primarily use these jam values — modern CBP
90
+ // uses NOISE INFUSION (EMP_N noise-range columns) + suppression FLAGS (EMP_N_F …),
91
+ // which this tool does NOT currently request or interpret (it surfaces values as
92
+ // reported). So this floor is a conservative cross-product guard, not CBP's confirmed
93
+ // mechanism; a keyed live verification of CBP's exact withheld-cell encoding is pending
94
+ // (no CENSUS_API_KEY was available at build time). See SUPPRESSED_NOTE.
95
+ const CENSUS_SENTINEL_FLOOR = -100000000;
96
+
97
+ const DEFAULT_YEAR = "2022"; // the latest confirmed CBP vintage (ADR-0047)
98
+
99
+ // ─── Honesty notes (ADR-0047 required set) ────────────────────────
100
+ const KEY_REQUIRED_NOTE =
101
+ "This source REQUIRES a free CENSUS_API_KEY (the Census Data API has no keyless tier). The key is sent ONLY as the &key= query parameter to api.census.gov and is NEVER logged, echoed, or placed in this response.";
102
+ const PAYROLL_UNITS_NOTE =
103
+ "annualPayrollUsd is ANNUAL payroll in US dollars, converted from the Census PAYANN field's $1,000 units (×1000). establishments and employees are integer counts (as-of the reference year).";
104
+ const SUPPRESSED_NOTE =
105
+ "Disclosure protection: any large-negative jam sentinel (e.g. -999999999) is mapped to null (withheld) — NEVER a negative number and NEVER 0; a genuine 0 is preserved as 0. NOTE: modern CBP applies NOISE INFUSION (perturbed values) plus suppression flag columns (e.g. EMP_N_F) rather than jam sentinels; this tool surfaces values as reported and does not currently interpret suppression flags, so a flagged/noise-infused cell is returned as its reported number — treat exact small counts as approximate.";
106
+ const NO_PAGINATION_NOTE =
107
+ "CBP returns the COMPLETE set of geographies matching the filter (no server-side pagination); totalAvailable equals the number of rows returned. Narrow with naics / geography to reduce the row count.";
108
+
109
+ // ─── The key seam (REQUIRED; value NEVER leaked past the &key= param) ──
110
+ /** Read CENSUS_API_KEY from env; trim; return the value or undefined (unset/blank). */
111
+ export function censusApiKey(): string | undefined {
112
+ const raw = process.env.CENSUS_API_KEY;
113
+ const trimmed = typeof raw === "string" ? raw.trim() : "";
114
+ return trimmed ? trimmed : undefined;
115
+ }
116
+
117
+ // ─── Curated row shape ────────────────────────────────────────────
118
+ export type CbpRow = {
119
+ name: string | null; // the geography NAME (e.g. "California")
120
+ geoId: string | null; // GEO_ID (a STRING — leading zeros survive)
121
+ naicsCode: string | null; // NAICS2017 (a STRING — sector codes carry structure)
122
+ naicsLabel: string | null; // NAICS2017_LABEL
123
+ establishments: number | null; // ESTAB — null when suppressed (NEVER negative/0-lie)
124
+ employees: number | null; // EMP — null when suppressed
125
+ annualPayrollUsd: number | null; // PAYANN×1000 — null when suppressed
126
+ state: string | null; // state FIPS (a STRING — leading zeros survive)
127
+ };
128
+
129
+ /** num(), but map the Census negative suppression sentinel family → null (withheld). */
130
+ function censusNum(v: unknown): number | null {
131
+ const n = num(v);
132
+ if (n === null) return null;
133
+ // A large-negative sentinel is a WITHHELD/suppressed cell, never data. A genuine
134
+ // 0 (n > floor) passes through as 0.
135
+ if (n <= CENSUS_SENTINEL_FLOOR) return null;
136
+ return n;
137
+ }
138
+
139
+ /** Annual payroll: PAYANN is in $1,000 units → ×1000; null-preserving. */
140
+ function mul1000(n: number | null): number | null {
141
+ return n === null ? null : n * 1000;
142
+ }
143
+
144
+ export type CensusBusinessPatternsArgs = {
145
+ naics?: string;
146
+ geography?: string; // us | state | county (default us)
147
+ state?: string; // 2-digit FIPS (required for county; optional filter for state)
148
+ year?: string; // ^\d{4}$ (default 2022)
149
+ limit?: number; // OPTIONAL client-side top-N slice (CBP has no server pagination)
150
+ };
151
+
152
+ /**
153
+ * Fetch County Business Patterns rows for a NAICS × geography filter → normalized
154
+ * establishment / employment / annual-payroll rows + honest `_meta`. REQUIRES
155
+ * CENSUS_API_KEY (throws invalid_input pre-fetch when unset). The 2D-array body is
156
+ * parsed by HEADER NAME (order-independent); suppressed cells map to null.
157
+ */
158
+ export async function businessPatterns(
159
+ args: CensusBusinessPatternsArgs,
160
+ ): Promise<MetaBundle> {
161
+ // ── [KEY] REQUIRED key — throw an honest config error BEFORE any fetch. ──
162
+ const key = censusApiKey();
163
+ if (key === undefined) {
164
+ throw new ToolErrorCarrier({
165
+ kind: "invalid_input",
166
+ retryable: false,
167
+ message:
168
+ "Census Data API requires a free key. Get one at https://api.census.gov/data/key_signup.html and set CENSUS_API_KEY.",
169
+ upstreamEndpoint: CENSUS_DATA_LABEL,
170
+ });
171
+ }
172
+
173
+ // ── Validate + default the inputs (belt-and-suspenders behind the server Zod;
174
+ // a DIRECT handler call bypasses Zod). ──
175
+ const year = args.year ?? DEFAULT_YEAR;
176
+ if (!YEAR_RE.test(year)) {
177
+ throw new ToolErrorCarrier({
178
+ kind: "invalid_input",
179
+ retryable: false,
180
+ message: `Invalid year ${JSON.stringify(year)} — expected a 4-digit year (^\\d{4}$), e.g. "2022". (year rides in the request PATH; it is strictly validated.)`,
181
+ upstreamEndpoint: CENSUS_DATA_LABEL,
182
+ });
183
+ }
184
+
185
+ const geography = args.geography ?? "us";
186
+ if (!GEOGRAPHIES.has(geography)) {
187
+ throw new ToolErrorCarrier({
188
+ kind: "invalid_input",
189
+ retryable: false,
190
+ message: `Invalid geography ${JSON.stringify(geography)} — expected one of us, state, county.`,
191
+ upstreamEndpoint: CENSUS_DATA_LABEL,
192
+ });
193
+ }
194
+
195
+ if (args.state !== undefined && !STATE_FIPS_RE.test(args.state)) {
196
+ throw new ToolErrorCarrier({
197
+ kind: "invalid_input",
198
+ retryable: false,
199
+ message: `Invalid state ${JSON.stringify(args.state)} — expected a 2-digit state FIPS code (^\\d{2}$), e.g. "06" (California).`,
200
+ upstreamEndpoint: CENSUS_DATA_LABEL,
201
+ });
202
+ }
203
+
204
+ if (args.naics !== undefined && !NAICS_RE.test(args.naics)) {
205
+ throw new ToolErrorCarrier({
206
+ kind: "invalid_input",
207
+ retryable: false,
208
+ message: `Invalid naics ${JSON.stringify(args.naics)} — expected a 2–6 digit NAICS-2017 code (^\\d{2,6}$), e.g. "5415" (Computer Systems Design).`,
209
+ upstreamEndpoint: CENSUS_DATA_LABEL,
210
+ });
211
+ }
212
+
213
+ // ── Resolve the geography clause (for=… [+ in=state:…]). ──
214
+ let forClause: string;
215
+ let inClause: string | undefined;
216
+ let geoFilter: string;
217
+ if (geography === "us") {
218
+ forClause = "us:*";
219
+ geoFilter = "geography:us";
220
+ } else if (geography === "state") {
221
+ forClause = args.state !== undefined ? `state:${args.state}` : "state:*";
222
+ geoFilter = `geography:state:${args.state ?? "*"}`;
223
+ } else {
224
+ // county — requires a state (the CBP `in=state:` predicate is mandatory).
225
+ if (args.state === undefined) {
226
+ throw new ToolErrorCarrier({
227
+ kind: "invalid_input",
228
+ retryable: false,
229
+ message:
230
+ "geography 'county' requires `state` (a 2-digit FIPS) — CBP county queries need an `in=state:NN` predicate. Pass state, e.g. state:'06'.",
231
+ upstreamEndpoint: CENSUS_DATA_LABEL,
232
+ });
233
+ }
234
+ forClause = "county:*";
235
+ inClause = `state:${args.state}`;
236
+ geoFilter = `geography:county:* in state:${args.state}`;
237
+ }
238
+
239
+ // ── Build the query (all VALUES via URLSearchParams — no host/path steer; the
240
+ // REQUIRED key rides ONLY here in &key=). ──
241
+ const params = new URLSearchParams();
242
+ params.set("get", "NAME,NAICS2017_LABEL,ESTAB,EMP,PAYANN,GEO_ID");
243
+ params.set("for", forClause);
244
+ if (inClause !== undefined) params.set("in", inClause);
245
+ if (args.naics !== undefined) params.set("NAICS2017", args.naics);
246
+ params.set("key", key);
247
+
248
+ const url = `https://${CENSUS_DATA_HOST}/data/${year}/cbp?${params.toString()}`;
249
+ // Belt-and-suspenders: the fixed host + strictly-validated path leave nothing to
250
+ // steer the authority; assert the built URL cannot have been moved off-host.
251
+ const built = new URL(url);
252
+ if (built.hostname !== CENSUS_DATA_HOST || built.protocol !== "https:") {
253
+ throw new ToolErrorCarrier({
254
+ kind: "invalid_input",
255
+ retryable: false,
256
+ message: `Constructed Census Data URL host ${JSON.stringify(built.hostname)} (${built.protocol}) is not ${CENSUS_DATA_HOST} over https — refusing to fetch (SSRF safety).`,
257
+ upstreamEndpoint: CENSUS_DATA_LABEL,
258
+ });
259
+ }
260
+
261
+ // ── Fetch with redirect:"manual" — the KEY-ERROR DETECTION crux. A missing or
262
+ // invalid key makes the Census Data API 302-redirect to its "Missing Key" page
263
+ // (live-verified: `HTTP 302` + `Location: /data/missing_key.html` +
264
+ // `X-DataWebAPI-KeyError: 1`). We must NOT use redirect:"error" via getJson
265
+ // here: undici rejects an "error"-mode redirect with a TypeError that the
266
+ // shared fetchWithRetry catch reclassifies to a *retryable upstream_unavailable*
267
+ // — masking a key-config error as a transient outage. redirect:"manual" instead
268
+ // yields an INSPECTABLE opaque-redirect (type "opaqueredirect", status 0), so
269
+ // the missing/invalid key surfaces as an honest invalid_input. This is a
270
+ // SINGLE classified attempt (no auto-retry): a transient 5xx THROWS
271
+ // upstream_unavailable — re-invoke the tool to retry. The 5xx/404/400 taxonomy
272
+ // is delegated to the shared errors.ts `errorFromResponse`; a 200 non-JSON body
273
+ // ⇒ r.json() SyntaxError ⇒ schema_drift. The redirect is NEVER followed, so no
274
+ // off-host hop can occur (a stronger SSRF posture than redirect:"error"). ──
275
+ let res: Response;
276
+ try {
277
+ res = await fetch(built.toString(), {
278
+ redirect: "manual",
279
+ signal: AbortSignal.timeout(15_000),
280
+ });
281
+ } catch (e) {
282
+ // Timeout/abort ⇒ non-retryable (the same aborted signal would re-reject);
283
+ // a genuine network TypeError ⇒ retryable upstream_unavailable. NEVER empty.
284
+ if (
285
+ e instanceof Error &&
286
+ (e.name === "TimeoutError" || e.name === "AbortError")
287
+ ) {
288
+ throw new ToolErrorCarrier({
289
+ kind: "upstream_unavailable",
290
+ message: `Request to ${CENSUS_DATA_LABEL} timed out.`,
291
+ retryable: false,
292
+ upstreamEndpoint: CENSUS_DATA_LABEL,
293
+ });
294
+ }
295
+ throw new ToolErrorCarrier({
296
+ kind: "upstream_unavailable",
297
+ message: `Network error reaching ${CENSUS_DATA_LABEL}: ${e instanceof Error ? e.message : String(e)}`,
298
+ retryable: true,
299
+ retryAfterSeconds: 30,
300
+ upstreamEndpoint: CENSUS_DATA_LABEL,
301
+ });
302
+ }
303
+
304
+ // [KEY] A redirect (opaque-redirect via redirect:"manual", or a raw 3xx status) ⇒
305
+ // the missing/invalid-key "Missing Key" page ⇒ an honest key-config error, NEVER
306
+ // a fake-empty (swallowing this as empty ⇒ RED in the fault suite).
307
+ if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
308
+ throw new ToolErrorCarrier({
309
+ kind: "invalid_input",
310
+ retryable: false,
311
+ message:
312
+ "Census Data API redirected the request to its 'Missing Key' page — CENSUS_API_KEY is missing or invalid. Get or check a free key at https://api.census.gov/data/key_signup.html.",
313
+ upstreamEndpoint: CENSUS_DATA_LABEL,
314
+ });
315
+ }
316
+
317
+ // [P2] 404/429/5xx/4xx ⇒ the shared errors.ts taxonomy (a DOWN service is NEVER
318
+ // an empty result; 400 → invalid_input, 5xx → upstream_unavailable, …).
319
+ if (!res.ok) {
320
+ throw new ToolErrorCarrier(errorFromResponse(res, CENSUS_DATA_LABEL));
321
+ }
322
+
323
+ // [P4] 200 ⇒ parse JSON; a non-JSON body (an HTML error page at 200) makes
324
+ // r.json() throw a SyntaxError ⇒ schema_drift (never read as an empty result).
325
+ let body: unknown;
326
+ try {
327
+ body = await res.json();
328
+ } catch (e) {
329
+ if (e instanceof SyntaxError) {
330
+ throw driftError(
331
+ CENSUS_DATA_LABEL,
332
+ "Census CBP returned a non-JSON body at HTTP 200 (likely an HTML 'Missing Key' / error page) — treating as schema drift (never read as an empty result).",
333
+ );
334
+ }
335
+ throw e;
336
+ }
337
+
338
+ // ── [P4] Parse the 2D array: row 0 = string[] header, rows 1..N = data. ──
339
+ if (!Array.isArray(body) || body.length === 0) {
340
+ throw driftError(
341
+ CENSUS_DATA_LABEL,
342
+ "Census CBP returned a body that is not a non-empty 2D array — treating as schema drift (never a fabricated empty).",
343
+ );
344
+ }
345
+ const header = body[0];
346
+ if (
347
+ !Array.isArray(header) ||
348
+ header.length === 0 ||
349
+ !header.every((h) => typeof h === "string")
350
+ ) {
351
+ throw driftError(
352
+ CENSUS_DATA_LABEL,
353
+ "Census CBP row 0 is not a string[] header row — treating as schema drift (the 2D-array contract changed; never a fabricated empty).",
354
+ );
355
+ }
356
+
357
+ // Header-name → column index (order-independent; a missing column ⇒ index -1 ⇒
358
+ // the field maps to null, never a positional mis-read).
359
+ const idx = new Map<string, number>();
360
+ (header as string[]).forEach((h, i) => idx.set(h, i));
361
+ const col = (row: unknown[], name: string): unknown => {
362
+ const i = idx.get(name);
363
+ return i === undefined || i < 0 ? undefined : row[i];
364
+ };
365
+
366
+ const allRows: CbpRow[] = [];
367
+ for (let i = 1; i < body.length; i++) {
368
+ const raw = body[i];
369
+ if (!Array.isArray(raw)) {
370
+ throw driftError(
371
+ CENSUS_DATA_LABEL,
372
+ `Census CBP data row ${i} is not an array — treating as schema drift (never a fabricated empty).`,
373
+ );
374
+ }
375
+ const row = raw as unknown[];
376
+ allRows.push({
377
+ name: str(col(row, "NAME")),
378
+ geoId: str(col(row, "GEO_ID")),
379
+ naicsCode: str(col(row, "NAICS2017")),
380
+ naicsLabel: str(col(row, "NAICS2017_LABEL")),
381
+ establishments: censusNum(col(row, "ESTAB")),
382
+ employees: censusNum(col(row, "EMP")),
383
+ annualPayrollUsd: mul1000(censusNum(col(row, "PAYANN"))),
384
+ state: str(col(row, "state")),
385
+ });
386
+ }
387
+
388
+ // ── [P1] The COMPLETE set for the filter (no server pagination). An OPTIONAL
389
+ // client-side top-N slice is disclosed (totalAvailable stays the full count,
390
+ // so buildMeta derives truncated/complete honestly). ──
391
+ const totalAvailable = allRows.length;
392
+ const notes: string[] = [
393
+ KEY_REQUIRED_NOTE,
394
+ PAYROLL_UNITS_NOTE,
395
+ SUPPRESSED_NOTE,
396
+ NO_PAGINATION_NOTE,
397
+ ];
398
+
399
+ let rows = allRows;
400
+ if (
401
+ typeof args.limit === "number" &&
402
+ Number.isFinite(args.limit) &&
403
+ args.limit >= 0 &&
404
+ args.limit < allRows.length
405
+ ) {
406
+ rows = allRows.slice(0, args.limit);
407
+ notes.push(
408
+ `Returned the first ${rows.length} of ${totalAvailable} rows (client-side limit=${args.limit}); CBP has NO server-side pagination, so the remaining ${totalAvailable - rows.length} are not fetched separately — raise limit or narrow the filter to see them.`,
409
+ );
410
+ }
411
+
412
+ const filtersApplied = [
413
+ args.naics !== undefined ? `naics:${args.naics}` : "naics:(all)",
414
+ geoFilter,
415
+ `year:${year}`,
416
+ ];
417
+
418
+ const meta: Partial<ResponseMeta> = {
419
+ // MODE only — never the key value (K-test).
420
+ source: `api.census.gov /data/${year}/cbp (County Business Patterns; CENSUS_API_KEY)`,
421
+ keylessMode: false, // ★KEYED — the first key-required source
422
+ returned: rows.length,
423
+ totalAvailable,
424
+ filtersApplied,
425
+ filtersDropped: [],
426
+ fieldsUnavailable: [],
427
+ notes,
428
+ };
429
+
430
+ return withMeta({ rows }, meta);
431
+ }