@cliwant/mcp-sam-gov 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +11 -9
- package/README.ko.md +11 -9
- package/README.md +51 -12
- package/dist/census-economic.d.ts +93 -0
- package/dist/census-economic.d.ts.map +1 -0
- package/dist/census-economic.js +355 -0
- package/dist/census-economic.js.map +1 -0
- package/dist/fred.d.ts +108 -0
- package/dist/fred.d.ts.map +1 -0
- package/dist/fred.js +373 -0
- package/dist/fred.js.map +1 -0
- package/dist/gsa-perdiem.d.ts +74 -0
- package/dist/gsa-perdiem.d.ts.map +1 -0
- package/dist/gsa-perdiem.js +296 -0
- package/dist/gsa-perdiem.js.map +1 -0
- package/dist/keys.d.ts +83 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +173 -0
- package/dist/keys.js.map +1 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +185 -1
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +33 -16
- package/dist/snapshot.d.ts.map +1 -1
- package/dist/snapshot.js +46 -17
- package/dist/snapshot.js.map +1 -1
- package/package.json +1 -1
- package/src/census-economic.ts +425 -0
- package/src/fred.ts +464 -0
- package/src/gsa-perdiem.ts +361 -0
- package/src/keys.ts +216 -0
- package/src/server.ts +221 -1
- package/src/snapshot.ts +51 -20
|
@@ -0,0 +1,355 @@
|
|
|
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 111 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
|
+
import { ToolErrorCarrier, errorFromResponse } from "./errors.js";
|
|
65
|
+
import { driftError } from "./datasource.js";
|
|
66
|
+
import { num, str } from "./coerce.js";
|
|
67
|
+
import { withMeta } from "./meta.js";
|
|
68
|
+
// Re-export the shared honesty coercion (single audited copy in ./coerce.js —
|
|
69
|
+
// ADR-0005 v2 FIX-C) so a num regression fails together across sources. NO local
|
|
70
|
+
// num/str.
|
|
71
|
+
export { num };
|
|
72
|
+
// ─── SSRF core: the single fixed host (DIFFERENT from census.ts) ──
|
|
73
|
+
const CENSUS_DATA_HOST = "api.census.gov";
|
|
74
|
+
const CENSUS_DATA_LABEL = "census:/data/cbp"; // host-only ToolError surface; NO token, NO key
|
|
75
|
+
// ─── Validation charclasses (SSRF + "verify the input" honesty) ───
|
|
76
|
+
const YEAR_RE = /^\d{4}$/; // rides in the PATH — strict 4-digit (no path injection)
|
|
77
|
+
const NAICS_RE = /^\d{2,6}$/; // 2–6 digit NAICS-2017 sector/code
|
|
78
|
+
const STATE_FIPS_RE = /^\d{2}$/; // 2-digit state FIPS
|
|
79
|
+
const GEOGRAPHIES = new Set(["us", "state", "county"]);
|
|
80
|
+
// The Census suppression/withhold sentinel floor. Census encodes a suppressed or
|
|
81
|
+
// unavailable cell as a large NEGATIVE value (-999999999 / -888888888 /
|
|
82
|
+
// -666666666 …). Establishment/employment/payroll counts are non-negative, so any
|
|
83
|
+
// value at/below this floor is a sentinel, NOT data.
|
|
84
|
+
const CENSUS_SENTINEL_FLOOR = -100000000;
|
|
85
|
+
const DEFAULT_YEAR = "2022"; // the latest confirmed CBP vintage (ADR-0047)
|
|
86
|
+
// ─── Honesty notes (ADR-0047 required set) ────────────────────────
|
|
87
|
+
const KEY_REQUIRED_NOTE = "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.";
|
|
88
|
+
const PAYROLL_UNITS_NOTE = "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).";
|
|
89
|
+
const SUPPRESSED_NOTE = "Census suppresses cells for confidentiality/reliability using large negative sentinels (e.g. -999999999); such values are mapped to null (withheld) — NEVER a negative number and NEVER 0. A genuine 0 is preserved as 0.";
|
|
90
|
+
const NO_PAGINATION_NOTE = "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.";
|
|
91
|
+
// ─── The key seam (REQUIRED; value NEVER leaked past the &key= param) ──
|
|
92
|
+
/** Read CENSUS_API_KEY from env; trim; return the value or undefined (unset/blank). */
|
|
93
|
+
export function censusApiKey() {
|
|
94
|
+
const raw = process.env.CENSUS_API_KEY;
|
|
95
|
+
const trimmed = typeof raw === "string" ? raw.trim() : "";
|
|
96
|
+
return trimmed ? trimmed : undefined;
|
|
97
|
+
}
|
|
98
|
+
/** num(), but map the Census negative suppression sentinel family → null (withheld). */
|
|
99
|
+
function censusNum(v) {
|
|
100
|
+
const n = num(v);
|
|
101
|
+
if (n === null)
|
|
102
|
+
return null;
|
|
103
|
+
// A large-negative sentinel is a WITHHELD/suppressed cell, never data. A genuine
|
|
104
|
+
// 0 (n > floor) passes through as 0.
|
|
105
|
+
if (n <= CENSUS_SENTINEL_FLOOR)
|
|
106
|
+
return null;
|
|
107
|
+
return n;
|
|
108
|
+
}
|
|
109
|
+
/** Annual payroll: PAYANN is in $1,000 units → ×1000; null-preserving. */
|
|
110
|
+
function mul1000(n) {
|
|
111
|
+
return n === null ? null : n * 1000;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Fetch County Business Patterns rows for a NAICS × geography filter → normalized
|
|
115
|
+
* establishment / employment / annual-payroll rows + honest `_meta`. REQUIRES
|
|
116
|
+
* CENSUS_API_KEY (throws invalid_input pre-fetch when unset). The 2D-array body is
|
|
117
|
+
* parsed by HEADER NAME (order-independent); suppressed cells map to null.
|
|
118
|
+
*/
|
|
119
|
+
export async function businessPatterns(args) {
|
|
120
|
+
// ── [KEY] REQUIRED key — throw an honest config error BEFORE any fetch. ──
|
|
121
|
+
const key = censusApiKey();
|
|
122
|
+
if (key === undefined) {
|
|
123
|
+
throw new ToolErrorCarrier({
|
|
124
|
+
kind: "invalid_input",
|
|
125
|
+
retryable: false,
|
|
126
|
+
message: "Census Data API requires a free key. Get one at https://api.census.gov/data/key_signup.html and set CENSUS_API_KEY.",
|
|
127
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
// ── Validate + default the inputs (belt-and-suspenders behind the server Zod;
|
|
131
|
+
// a DIRECT handler call bypasses Zod). ──
|
|
132
|
+
const year = args.year ?? DEFAULT_YEAR;
|
|
133
|
+
if (!YEAR_RE.test(year)) {
|
|
134
|
+
throw new ToolErrorCarrier({
|
|
135
|
+
kind: "invalid_input",
|
|
136
|
+
retryable: false,
|
|
137
|
+
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.)`,
|
|
138
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const geography = args.geography ?? "us";
|
|
142
|
+
if (!GEOGRAPHIES.has(geography)) {
|
|
143
|
+
throw new ToolErrorCarrier({
|
|
144
|
+
kind: "invalid_input",
|
|
145
|
+
retryable: false,
|
|
146
|
+
message: `Invalid geography ${JSON.stringify(geography)} — expected one of us, state, county.`,
|
|
147
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (args.state !== undefined && !STATE_FIPS_RE.test(args.state)) {
|
|
151
|
+
throw new ToolErrorCarrier({
|
|
152
|
+
kind: "invalid_input",
|
|
153
|
+
retryable: false,
|
|
154
|
+
message: `Invalid state ${JSON.stringify(args.state)} — expected a 2-digit state FIPS code (^\\d{2}$), e.g. "06" (California).`,
|
|
155
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (args.naics !== undefined && !NAICS_RE.test(args.naics)) {
|
|
159
|
+
throw new ToolErrorCarrier({
|
|
160
|
+
kind: "invalid_input",
|
|
161
|
+
retryable: false,
|
|
162
|
+
message: `Invalid naics ${JSON.stringify(args.naics)} — expected a 2–6 digit NAICS-2017 code (^\\d{2,6}$), e.g. "5415" (Computer Systems Design).`,
|
|
163
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
// ── Resolve the geography clause (for=… [+ in=state:…]). ──
|
|
167
|
+
let forClause;
|
|
168
|
+
let inClause;
|
|
169
|
+
let geoFilter;
|
|
170
|
+
if (geography === "us") {
|
|
171
|
+
forClause = "us:*";
|
|
172
|
+
geoFilter = "geography:us";
|
|
173
|
+
}
|
|
174
|
+
else if (geography === "state") {
|
|
175
|
+
forClause = args.state !== undefined ? `state:${args.state}` : "state:*";
|
|
176
|
+
geoFilter = `geography:state:${args.state ?? "*"}`;
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
// county — requires a state (the CBP `in=state:` predicate is mandatory).
|
|
180
|
+
if (args.state === undefined) {
|
|
181
|
+
throw new ToolErrorCarrier({
|
|
182
|
+
kind: "invalid_input",
|
|
183
|
+
retryable: false,
|
|
184
|
+
message: "geography 'county' requires `state` (a 2-digit FIPS) — CBP county queries need an `in=state:NN` predicate. Pass state, e.g. state:'06'.",
|
|
185
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
forClause = "county:*";
|
|
189
|
+
inClause = `state:${args.state}`;
|
|
190
|
+
geoFilter = `geography:county:* in state:${args.state}`;
|
|
191
|
+
}
|
|
192
|
+
// ── Build the query (all VALUES via URLSearchParams — no host/path steer; the
|
|
193
|
+
// REQUIRED key rides ONLY here in &key=). ──
|
|
194
|
+
const params = new URLSearchParams();
|
|
195
|
+
params.set("get", "NAME,NAICS2017_LABEL,ESTAB,EMP,PAYANN,GEO_ID");
|
|
196
|
+
params.set("for", forClause);
|
|
197
|
+
if (inClause !== undefined)
|
|
198
|
+
params.set("in", inClause);
|
|
199
|
+
if (args.naics !== undefined)
|
|
200
|
+
params.set("NAICS2017", args.naics);
|
|
201
|
+
params.set("key", key);
|
|
202
|
+
const url = `https://${CENSUS_DATA_HOST}/data/${year}/cbp?${params.toString()}`;
|
|
203
|
+
// Belt-and-suspenders: the fixed host + strictly-validated path leave nothing to
|
|
204
|
+
// steer the authority; assert the built URL cannot have been moved off-host.
|
|
205
|
+
const built = new URL(url);
|
|
206
|
+
if (built.hostname !== CENSUS_DATA_HOST || built.protocol !== "https:") {
|
|
207
|
+
throw new ToolErrorCarrier({
|
|
208
|
+
kind: "invalid_input",
|
|
209
|
+
retryable: false,
|
|
210
|
+
message: `Constructed Census Data URL host ${JSON.stringify(built.hostname)} (${built.protocol}) is not ${CENSUS_DATA_HOST} over https — refusing to fetch (SSRF safety).`,
|
|
211
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
// ── Fetch with redirect:"manual" — the KEY-ERROR DETECTION crux. A missing or
|
|
215
|
+
// invalid key makes the Census Data API 302-redirect to its "Missing Key" page
|
|
216
|
+
// (live-verified: `HTTP 302` + `Location: /data/missing_key.html` +
|
|
217
|
+
// `X-DataWebAPI-KeyError: 1`). We must NOT use redirect:"error" via getJson
|
|
218
|
+
// here: undici rejects an "error"-mode redirect with a TypeError that the
|
|
219
|
+
// shared fetchWithRetry catch reclassifies to a *retryable upstream_unavailable*
|
|
220
|
+
// — masking a key-config error as a transient outage. redirect:"manual" instead
|
|
221
|
+
// yields an INSPECTABLE opaque-redirect (type "opaqueredirect", status 0), so
|
|
222
|
+
// the missing/invalid key surfaces as an honest invalid_input. This is a
|
|
223
|
+
// SINGLE classified attempt (no auto-retry): a transient 5xx THROWS
|
|
224
|
+
// upstream_unavailable — re-invoke the tool to retry. The 5xx/404/400 taxonomy
|
|
225
|
+
// is delegated to the shared errors.ts `errorFromResponse`; a 200 non-JSON body
|
|
226
|
+
// ⇒ r.json() SyntaxError ⇒ schema_drift. The redirect is NEVER followed, so no
|
|
227
|
+
// off-host hop can occur (a stronger SSRF posture than redirect:"error"). ──
|
|
228
|
+
let res;
|
|
229
|
+
try {
|
|
230
|
+
res = await fetch(built.toString(), {
|
|
231
|
+
redirect: "manual",
|
|
232
|
+
signal: AbortSignal.timeout(15_000),
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
catch (e) {
|
|
236
|
+
// Timeout/abort ⇒ non-retryable (the same aborted signal would re-reject);
|
|
237
|
+
// a genuine network TypeError ⇒ retryable upstream_unavailable. NEVER empty.
|
|
238
|
+
if (e instanceof Error &&
|
|
239
|
+
(e.name === "TimeoutError" || e.name === "AbortError")) {
|
|
240
|
+
throw new ToolErrorCarrier({
|
|
241
|
+
kind: "upstream_unavailable",
|
|
242
|
+
message: `Request to ${CENSUS_DATA_LABEL} timed out.`,
|
|
243
|
+
retryable: false,
|
|
244
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
throw new ToolErrorCarrier({
|
|
248
|
+
kind: "upstream_unavailable",
|
|
249
|
+
message: `Network error reaching ${CENSUS_DATA_LABEL}: ${e instanceof Error ? e.message : String(e)}`,
|
|
250
|
+
retryable: true,
|
|
251
|
+
retryAfterSeconds: 30,
|
|
252
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
// [KEY] A redirect (opaque-redirect via redirect:"manual", or a raw 3xx status) ⇒
|
|
256
|
+
// the missing/invalid-key "Missing Key" page ⇒ an honest key-config error, NEVER
|
|
257
|
+
// a fake-empty (swallowing this as empty ⇒ RED in the fault suite).
|
|
258
|
+
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
|
|
259
|
+
throw new ToolErrorCarrier({
|
|
260
|
+
kind: "invalid_input",
|
|
261
|
+
retryable: false,
|
|
262
|
+
message: "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.",
|
|
263
|
+
upstreamEndpoint: CENSUS_DATA_LABEL,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
// [P2] 404/429/5xx/4xx ⇒ the shared errors.ts taxonomy (a DOWN service is NEVER
|
|
267
|
+
// an empty result; 400 → invalid_input, 5xx → upstream_unavailable, …).
|
|
268
|
+
if (!res.ok) {
|
|
269
|
+
throw new ToolErrorCarrier(errorFromResponse(res, CENSUS_DATA_LABEL));
|
|
270
|
+
}
|
|
271
|
+
// [P4] 200 ⇒ parse JSON; a non-JSON body (an HTML error page at 200) makes
|
|
272
|
+
// r.json() throw a SyntaxError ⇒ schema_drift (never read as an empty result).
|
|
273
|
+
let body;
|
|
274
|
+
try {
|
|
275
|
+
body = await res.json();
|
|
276
|
+
}
|
|
277
|
+
catch (e) {
|
|
278
|
+
if (e instanceof SyntaxError) {
|
|
279
|
+
throw driftError(CENSUS_DATA_LABEL, "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).");
|
|
280
|
+
}
|
|
281
|
+
throw e;
|
|
282
|
+
}
|
|
283
|
+
// ── [P4] Parse the 2D array: row 0 = string[] header, rows 1..N = data. ──
|
|
284
|
+
if (!Array.isArray(body) || body.length === 0) {
|
|
285
|
+
throw driftError(CENSUS_DATA_LABEL, "Census CBP returned a body that is not a non-empty 2D array — treating as schema drift (never a fabricated empty).");
|
|
286
|
+
}
|
|
287
|
+
const header = body[0];
|
|
288
|
+
if (!Array.isArray(header) ||
|
|
289
|
+
header.length === 0 ||
|
|
290
|
+
!header.every((h) => typeof h === "string")) {
|
|
291
|
+
throw driftError(CENSUS_DATA_LABEL, "Census CBP row 0 is not a string[] header row — treating as schema drift (the 2D-array contract changed; never a fabricated empty).");
|
|
292
|
+
}
|
|
293
|
+
// Header-name → column index (order-independent; a missing column ⇒ index -1 ⇒
|
|
294
|
+
// the field maps to null, never a positional mis-read).
|
|
295
|
+
const idx = new Map();
|
|
296
|
+
header.forEach((h, i) => idx.set(h, i));
|
|
297
|
+
const col = (row, name) => {
|
|
298
|
+
const i = idx.get(name);
|
|
299
|
+
return i === undefined || i < 0 ? undefined : row[i];
|
|
300
|
+
};
|
|
301
|
+
const allRows = [];
|
|
302
|
+
for (let i = 1; i < body.length; i++) {
|
|
303
|
+
const raw = body[i];
|
|
304
|
+
if (!Array.isArray(raw)) {
|
|
305
|
+
throw driftError(CENSUS_DATA_LABEL, `Census CBP data row ${i} is not an array — treating as schema drift (never a fabricated empty).`);
|
|
306
|
+
}
|
|
307
|
+
const row = raw;
|
|
308
|
+
allRows.push({
|
|
309
|
+
name: str(col(row, "NAME")),
|
|
310
|
+
geoId: str(col(row, "GEO_ID")),
|
|
311
|
+
naicsCode: str(col(row, "NAICS2017")),
|
|
312
|
+
naicsLabel: str(col(row, "NAICS2017_LABEL")),
|
|
313
|
+
establishments: censusNum(col(row, "ESTAB")),
|
|
314
|
+
employees: censusNum(col(row, "EMP")),
|
|
315
|
+
annualPayrollUsd: mul1000(censusNum(col(row, "PAYANN"))),
|
|
316
|
+
state: str(col(row, "state")),
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
// ── [P1] The COMPLETE set for the filter (no server pagination). An OPTIONAL
|
|
320
|
+
// client-side top-N slice is disclosed (totalAvailable stays the full count,
|
|
321
|
+
// so buildMeta derives truncated/complete honestly). ──
|
|
322
|
+
const totalAvailable = allRows.length;
|
|
323
|
+
const notes = [
|
|
324
|
+
KEY_REQUIRED_NOTE,
|
|
325
|
+
PAYROLL_UNITS_NOTE,
|
|
326
|
+
SUPPRESSED_NOTE,
|
|
327
|
+
NO_PAGINATION_NOTE,
|
|
328
|
+
];
|
|
329
|
+
let rows = allRows;
|
|
330
|
+
if (typeof args.limit === "number" &&
|
|
331
|
+
Number.isFinite(args.limit) &&
|
|
332
|
+
args.limit >= 0 &&
|
|
333
|
+
args.limit < allRows.length) {
|
|
334
|
+
rows = allRows.slice(0, args.limit);
|
|
335
|
+
notes.push(`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.`);
|
|
336
|
+
}
|
|
337
|
+
const filtersApplied = [
|
|
338
|
+
args.naics !== undefined ? `naics:${args.naics}` : "naics:(all)",
|
|
339
|
+
geoFilter,
|
|
340
|
+
`year:${year}`,
|
|
341
|
+
];
|
|
342
|
+
const meta = {
|
|
343
|
+
// MODE only — never the key value (K-test).
|
|
344
|
+
source: `api.census.gov /data/${year}/cbp (County Business Patterns; CENSUS_API_KEY)`,
|
|
345
|
+
keylessMode: false, // ★KEYED — the first key-required source
|
|
346
|
+
returned: rows.length,
|
|
347
|
+
totalAvailable,
|
|
348
|
+
filtersApplied,
|
|
349
|
+
filtersDropped: [],
|
|
350
|
+
fieldsUnavailable: [],
|
|
351
|
+
notes,
|
|
352
|
+
};
|
|
353
|
+
return withMeta({ rows }, meta);
|
|
354
|
+
}
|
|
355
|
+
//# sourceMappingURL=census-economic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"census-economic.js","sourceRoot":"","sources":["../src/census-economic.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AAEH,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CA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AAM,6EAA6E,CAChQ,CAAC;IACJ,CAAC;IAED,MAAM,cAAc,GAAG;QACrB,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,aAAa;QAChE,SAAS;QACT,QAAQ,IAAI,EAAE;KACf,CAAC;IAEF,MAAM,IAAI,GAA0B;QAClC,4CAA4C;QAC5C,MAAM,EAAE,wBAAwB,IAAI,iDAAiD;QACrF,WAAW,EAAE,KAAK,EAAE,yCAAyC;QAC7D,QAAQ,EAAE,IAAI,CAAC,MAAM;QACrB,cAAc;QACd,cAAc;QACd,cAAc,EAAE,EAAE;QAClB,iBAAiB,EAAE,EAAE;QACrB,KAAK;KACN,CAAC;IAEF,OAAO,QAAQ,CAAC,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC;AAClC,CAAC"}
|
package/dist/fred.d.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* fred.ts — FRED (Federal Reserve Economic Data, St. Louis Fed) — the MACRO
|
|
3
|
+
* CONTEXT lane (ADR-0048, Wave-4 source #2). GDP · CPI · interest rates ·
|
|
4
|
+
* unemployment · PPI … — the economy-wide backdrop for B2G bid escalation and
|
|
5
|
+
* market-timing that no contract/spending source carries.
|
|
6
|
+
*
|
|
7
|
+
* ★ THIS IS THE SERVER'S SECOND KEY-REQUIRED SOURCE (Census CBP was the first).
|
|
8
|
+
* FRED has NO keyless tier: every request needs `&api_key=`, and a missing/bad
|
|
9
|
+
* key returns HTTP 400 `{error_code, error_message}`. So, honestly: with NO
|
|
10
|
+
* `FRED_API_KEY` these two tools THROW an `invalid_input` config error BEFORE any
|
|
11
|
+
* fetch (never a fake-empty, never a keyless-pretend). The other 112 tools stay
|
|
12
|
+
* keyless — this key is scoped to this one source. (Contrast the OPTIONAL keys of
|
|
13
|
+
* datagov/bls/nvd, which lift a tier but are not required.)
|
|
14
|
+
*
|
|
15
|
+
* This module MIRRORS the census-economic.ts optional-key precedent: a `fredApiKey()`
|
|
16
|
+
* env seam, a pre-fetch `invalid_input` THROW when unset, the fixed-host SSRF assert
|
|
17
|
+
* + `redirect:"error"`, and the missing-sentinel→null idiom (Census's negative
|
|
18
|
+
* suppression sentinel there; FRED's `value === "."` here — the BLS `"-"` lineage).
|
|
19
|
+
* It writes ZERO coercion/meta code of its own: it REUSES `getJson` (the shared
|
|
20
|
+
* fetch envelope) / `driftError` / `num`·`str` (coerce.ts, null-never-0/empty) /
|
|
21
|
+
* `withMeta`·`buildMeta` (offset pagination via count-exact totals).
|
|
22
|
+
*
|
|
23
|
+
* GET https://api.stlouisfed.org/fred/series/search
|
|
24
|
+
* ?search_text=<q>&limit=&offset=&api_key=<KEY>&file_type=json
|
|
25
|
+
* → { seriess:[{ id,title,frequency,frequency_short,units,seasonal_adjustment,
|
|
26
|
+
* observation_start,observation_end,last_updated,popularity,notes }],
|
|
27
|
+
* count, limit, offset }
|
|
28
|
+
*
|
|
29
|
+
* GET https://api.stlouisfed.org/fred/series/observations
|
|
30
|
+
* ?series_id=<id>&observation_start=&observation_end=&limit=&offset=
|
|
31
|
+
* &sort_order=&api_key=<KEY>&file_type=json
|
|
32
|
+
* → { observations:[{ date, value }], count, … } ★value === "." ⇒ missing (null)
|
|
33
|
+
*
|
|
34
|
+
* ★ HONESTY (ADR-0048 P1–P5):
|
|
35
|
+
* [KEY] no key ⇒ invalid_input THROW pre-fetch (0 fetch); the message names
|
|
36
|
+
* FRED_API_KEY + the free-signup URL. A 400 carrying `{error_message}` (a
|
|
37
|
+
* bad series_id / expired key) ⇒ reclassified to invalid_input CARRYING the
|
|
38
|
+
* FRED error_message — honestly reported, never a fake empty.
|
|
39
|
+
* [P1] both endpoints report `count` (the total) ⇒ totalAvailable = num(count)
|
|
40
|
+
* EXACT; offset pagination (hasMore = offset+returned < count, nextOffset).
|
|
41
|
+
* NEVER fabricated (RED if totalAvailable = returned).
|
|
42
|
+
* [P3] ★the missing crux: an observation `value === "."` ⇒ **null** (FRED's
|
|
43
|
+
* missing sentinel — the BLS `"-"` lineage), NEVER 0. A genuine "0" ⇒ 0.
|
|
44
|
+
* [P2] a 400 ⇒ invalid_input (carrying error_message); a genuine no-match
|
|
45
|
+
* (seriess:[] / observations:[]) ⇒ honest empty; a 5xx ⇒ upstream_unavailable
|
|
46
|
+
* THROW; a 200 non-JSON ⇒ schema_drift.
|
|
47
|
+
* [P4] a body whose `seriess` / `observations` is absent or non-array ⇒ driftError
|
|
48
|
+
* (never a fabricated empty).
|
|
49
|
+
* [SSRF] fixed host `api.stlouisfed.org`; `series_id` charclass `^[A-Za-z0-9._-]+$`;
|
|
50
|
+
* dates `^\d{4}-\d{2}-\d{2}$`; sort_order enum {asc,desc}. All VALUES ride
|
|
51
|
+
* URLSearchParams; the key rides `&api_key=` ONLY — never a label/_meta/note
|
|
52
|
+
* (the K-test).
|
|
53
|
+
*/
|
|
54
|
+
import { num } from "./coerce.js";
|
|
55
|
+
import { type MetaBundle } from "./meta.js";
|
|
56
|
+
export { num };
|
|
57
|
+
export declare const FRED_HOST = "api.stlouisfed.org";
|
|
58
|
+
/** Read FRED_API_KEY from env; trim; return the value or undefined (unset/blank). */
|
|
59
|
+
export declare function fredApiKey(): string | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* num(), but map FRED's missing-observation sentinel `"."` → null (missing). A
|
|
62
|
+
* genuine "0" stays 0 (num("0") === 0); a real numeric string parses. This is the
|
|
63
|
+
* BLS `"-"` lineage — a data-absence marker, never a fabricated 0.
|
|
64
|
+
*/
|
|
65
|
+
export declare function fredValue(v: unknown): number | null;
|
|
66
|
+
export type FredSearchSeriesArgs = {
|
|
67
|
+
query?: string;
|
|
68
|
+
limit?: number;
|
|
69
|
+
offset?: number;
|
|
70
|
+
};
|
|
71
|
+
export type FredSeries = {
|
|
72
|
+
id: string | null;
|
|
73
|
+
title: string | null;
|
|
74
|
+
frequency: string | null;
|
|
75
|
+
frequencyShort: string | null;
|
|
76
|
+
units: string | null;
|
|
77
|
+
seasonalAdjustment: string | null;
|
|
78
|
+
observationStart: string | null;
|
|
79
|
+
observationEnd: string | null;
|
|
80
|
+
lastUpdated: string | null;
|
|
81
|
+
popularity: number | null;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Search FRED series (`/fred/series/search`) by `search_text` → curated series
|
|
85
|
+
* rows + honest `_meta`. REQUIRES FRED_API_KEY (throws invalid_input pre-fetch when
|
|
86
|
+
* unset). totalAvailable = FRED's exact `count`; offset pagination.
|
|
87
|
+
*/
|
|
88
|
+
export declare function searchSeries(args: FredSearchSeriesArgs): Promise<MetaBundle>;
|
|
89
|
+
export type FredSeriesObservationsArgs = {
|
|
90
|
+
seriesId?: string;
|
|
91
|
+
startDate?: string;
|
|
92
|
+
endDate?: string;
|
|
93
|
+
limit?: number;
|
|
94
|
+
offset?: number;
|
|
95
|
+
sortOrder?: string;
|
|
96
|
+
};
|
|
97
|
+
export type FredObservation = {
|
|
98
|
+
date: string | null;
|
|
99
|
+
value: number | null;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Fetch a FRED series' time series (`/fred/series/observations`) → date/value rows
|
|
103
|
+
* + honest `_meta`. REQUIRES FRED_API_KEY (throws invalid_input pre-fetch when
|
|
104
|
+
* unset). ★A missing observation (`value === "."`) maps to null, never 0.
|
|
105
|
+
* totalAvailable = FRED's exact `count`; offset pagination.
|
|
106
|
+
*/
|
|
107
|
+
export declare function seriesObservations(args: FredSeriesObservationsArgs): Promise<MetaBundle>;
|
|
108
|
+
//# sourceMappingURL=fred.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fred.d.ts","sourceRoot":"","sources":["../src/fred.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAIH,OAAO,EAAE,GAAG,EAAO,MAAM,aAAa,CAAC;AACvC,OAAO,EAA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