@v587d/capital-generation 2.31.4 → 2.31.5
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/CHANGELOG.md +30 -0
- package/README.md +3 -3
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/collector-runtime.js +8 -0
- package/lib/data-collector/catalog-taxonomy.js +11 -0
- package/lib/sources/eastmoney-http.js +274 -0
- package/lib/sources/sec-http.d.ts +9 -0
- package/lib/sources/sec-http.js +643 -0
- package/lib/sources/us-official-http.d.ts +4 -0
- package/lib/sources/us-official-http.js +654 -0
- package/lib/time/tools.js +6 -0
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +1 -1
- package/watchlist/package.json +1 -1
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
/** SEC EDGAR sources: ticker→CIK, submissions, daily index and full-text search.
|
|
2
|
+
*
|
|
3
|
+
* ⛔ Not wired into `createUsOfficialSources()` yet: SEC rate-limited this egress (Akamai 403
|
|
4
|
+
* "Request Rate Threshold Exceeded") while the code was written, so field mappings are still
|
|
5
|
+
* awaiting live-payload verification. Wire it in only after `npm run contract:probe -- --only sec`
|
|
6
|
+
* passes against real responses; a guard that rejects the official sample is a real incident (§10.2).
|
|
7
|
+
*/
|
|
8
|
+
import { buildDataKey } from '../data-collector/hub.js';
|
|
9
|
+
import { getDataTimeContract } from '../time/tools.js';
|
|
10
|
+
import { createRequestThrottle } from '../net/throttle.js';
|
|
11
|
+
const SEC_WWW = 'https://www.sec.gov';
|
|
12
|
+
const SEC_DATA = 'https://data.sec.gov';
|
|
13
|
+
const SEC_EFTS = 'https://efts.sec.gov';
|
|
14
|
+
const DEFAULT_USER_AGENT = 'capital-generation (+https://github.com/v587d/capital-generation)';
|
|
15
|
+
/** SEC allows 10 req/s; 8/s keeps a margin for retries and other SEC consumers on the same IP. */
|
|
16
|
+
const SEC_MIN_INTERVAL_MS = 125;
|
|
17
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
18
|
+
const secThrottle = createRequestThrottle(SEC_MIN_INTERVAL_MS);
|
|
19
|
+
function userAgent() {
|
|
20
|
+
const env = globalThis.process?.env;
|
|
21
|
+
const override = env?.SEC_USER_AGENT?.trim();
|
|
22
|
+
return override !== undefined && override.length > 0 ? override : DEFAULT_USER_AGENT;
|
|
23
|
+
}
|
|
24
|
+
function isRecord(value) {
|
|
25
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
26
|
+
}
|
|
27
|
+
function sourceError(message, code = 'sec_invalid_response') {
|
|
28
|
+
const error = new Error(message);
|
|
29
|
+
error.code = code;
|
|
30
|
+
return error;
|
|
31
|
+
}
|
|
32
|
+
function assertKnown(params, allowed) {
|
|
33
|
+
for (const key of Object.keys(params)) {
|
|
34
|
+
if (!allowed.includes(key))
|
|
35
|
+
throw new Error(`unsupported parameter: ${key} (allowed: ${allowed.join(', ')})`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function calendarDate(value, name) {
|
|
39
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
40
|
+
if (!DATE_PATTERN.test(text))
|
|
41
|
+
throw new Error(`parameter ${name} must be a valid YYYY-MM-DD date`);
|
|
42
|
+
const parsed = new Date(`${text}T00:00:00Z`);
|
|
43
|
+
if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text)
|
|
44
|
+
throw new Error(`parameter ${name} must be a valid YYYY-MM-DD date`);
|
|
45
|
+
return text;
|
|
46
|
+
}
|
|
47
|
+
function numberOrNull(value) {
|
|
48
|
+
if (value === undefined || value === null || value === '')
|
|
49
|
+
return null;
|
|
50
|
+
const parsed = typeof value === 'number' ? value : Number(String(value).replaceAll(',', '').trim());
|
|
51
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
52
|
+
}
|
|
53
|
+
function textOrNull(value) {
|
|
54
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
55
|
+
return text.length === 0 ? null : text;
|
|
56
|
+
}
|
|
57
|
+
function boolOrNull(value) {
|
|
58
|
+
if (value === undefined || value === null || value === '')
|
|
59
|
+
return null;
|
|
60
|
+
if (typeof value === 'boolean')
|
|
61
|
+
return value;
|
|
62
|
+
const text = String(value).trim().toLowerCase();
|
|
63
|
+
if (text === '1' || text === 'true' || text === 'y')
|
|
64
|
+
return true;
|
|
65
|
+
if (text === '0' || text === 'false' || text === 'n')
|
|
66
|
+
return false;
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
/** CIK is printed padded to 10 digits everywhere; the JSON `cik` field is unpadded. */
|
|
70
|
+
function padCik(value) {
|
|
71
|
+
const digits = String(value ?? '').trim().replace(/^0+/, '');
|
|
72
|
+
if (!/^\d{1,10}$/.test(digits))
|
|
73
|
+
throw sourceError(`CIK is not numeric: ${JSON.stringify(String(value ?? ''))}`);
|
|
74
|
+
return digits.padStart(10, '0');
|
|
75
|
+
}
|
|
76
|
+
async function secText(url, signal, label) {
|
|
77
|
+
signal.throwIfAborted();
|
|
78
|
+
return secThrottle(async () => {
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await fetch(url, {
|
|
82
|
+
headers: { 'User-Agent': userAgent(), Accept: 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate' },
|
|
83
|
+
signal,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error instanceof Error && error.name === 'AbortError')
|
|
88
|
+
throw error;
|
|
89
|
+
throw sourceError(`${label} request failed: ${error instanceof Error ? error.message : String(error)}`, 'sec_http_error');
|
|
90
|
+
}
|
|
91
|
+
if (response.status === 403)
|
|
92
|
+
throw sourceError(`${label} returned HTTP 403: SEC requires a declarative User-Agent (set SEC_USER_AGENT) and no more than 10 req/s`, 'sec_forbidden');
|
|
93
|
+
if (response.status === 404)
|
|
94
|
+
throw sourceError(`${label} returned HTTP 404: no such filing day, CIK or endpoint`, 'sec_not_found');
|
|
95
|
+
if (!response.ok)
|
|
96
|
+
throw sourceError(`${label} returned HTTP ${response.status}`, 'sec_http_error');
|
|
97
|
+
return response.text();
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
async function secJson(url, signal, label) {
|
|
101
|
+
const text = await secText(url, signal, label);
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(text);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw sourceError(`${label} returned non-JSON: ${JSON.stringify(text.slice(0, 120))}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** company_tickers.json is ~1MB and changes rarely; one in-process copy per TTL is enough. */
|
|
110
|
+
const TICKER_CACHE_TTL_MS = 3_600_000;
|
|
111
|
+
let tickerCache;
|
|
112
|
+
async function tickerMap(signal) {
|
|
113
|
+
if (tickerCache !== undefined && Date.now() - tickerCache.at < TICKER_CACHE_TTL_MS)
|
|
114
|
+
return tickerCache.map;
|
|
115
|
+
const payload = await secJson(`${SEC_WWW}/files/company_tickers.json`, signal, 'SEC company_tickers');
|
|
116
|
+
if (!isRecord(payload))
|
|
117
|
+
throw sourceError('SEC company_tickers response is not an object');
|
|
118
|
+
const map = new Map();
|
|
119
|
+
for (const value of Object.values(payload)) {
|
|
120
|
+
if (!isRecord(value))
|
|
121
|
+
continue;
|
|
122
|
+
const ticker = textOrNull(value.ticker);
|
|
123
|
+
const title = textOrNull(value.title);
|
|
124
|
+
const cik = value.cik_str;
|
|
125
|
+
if (ticker === null || title === null || cik === undefined || cik === null)
|
|
126
|
+
continue;
|
|
127
|
+
map.set(ticker.toUpperCase(), { cik: padCik(cik), title });
|
|
128
|
+
}
|
|
129
|
+
if (map.size === 0)
|
|
130
|
+
throw sourceError('SEC company_tickers response has no ticker rows');
|
|
131
|
+
tickerCache = { at: Date.now(), map };
|
|
132
|
+
return map;
|
|
133
|
+
}
|
|
134
|
+
const nullableString = { oneOf: [{ type: 'string' }, { type: 'null' }] };
|
|
135
|
+
const nullableNumber = { oneOf: [{ type: 'number' }, { type: 'null' }] };
|
|
136
|
+
const nullableBoolean = { oneOf: [{ type: 'boolean' }, { type: 'null' }] };
|
|
137
|
+
const tickerCikRow = {
|
|
138
|
+
type: 'object',
|
|
139
|
+
properties: {
|
|
140
|
+
ticker: { type: 'string' },
|
|
141
|
+
cik: nullableString,
|
|
142
|
+
company_name: nullableString,
|
|
143
|
+
found: { type: 'boolean' },
|
|
144
|
+
},
|
|
145
|
+
required: ['ticker', 'found'],
|
|
146
|
+
additionalProperties: false,
|
|
147
|
+
};
|
|
148
|
+
function normalizeTickers(params) {
|
|
149
|
+
assertKnown(params, ['tickers']);
|
|
150
|
+
if (!Array.isArray(params.tickers) || params.tickers.length === 0)
|
|
151
|
+
throw new Error('tickers must be a non-empty array');
|
|
152
|
+
if (params.tickers.length > 20)
|
|
153
|
+
throw new Error('tickers exceeds maximum 20');
|
|
154
|
+
const tickers = [...new Set(params.tickers.map((value) => {
|
|
155
|
+
if (typeof value !== 'string')
|
|
156
|
+
throw new Error('tickers[] must be a string');
|
|
157
|
+
const ticker = value.trim().toUpperCase();
|
|
158
|
+
if (!/^[A-Z][A-Z0-9.\-]{0,9}$/.test(ticker))
|
|
159
|
+
throw new Error(`tickers[] must be a US ticker, got ${JSON.stringify(value)}`);
|
|
160
|
+
return ticker;
|
|
161
|
+
}))];
|
|
162
|
+
return { tickers };
|
|
163
|
+
}
|
|
164
|
+
async function executeTickerCik(params, signal) {
|
|
165
|
+
const map = await tickerMap(signal);
|
|
166
|
+
const rows = params.tickers.map((ticker) => {
|
|
167
|
+
const entry = map.get(ticker);
|
|
168
|
+
return entry === undefined
|
|
169
|
+
? { ticker, cik: null, company_name: null, found: false }
|
|
170
|
+
: { ticker, cik: entry.cik, company_name: entry.title, found: true };
|
|
171
|
+
});
|
|
172
|
+
return { data: rows, schema: tickerCikRow };
|
|
173
|
+
}
|
|
174
|
+
// ── submissions (recent filings) ─────────────────────────────────────────────
|
|
175
|
+
const filingRow = {
|
|
176
|
+
type: 'object',
|
|
177
|
+
properties: {
|
|
178
|
+
cik: { type: 'string' },
|
|
179
|
+
company_name: { type: 'string' },
|
|
180
|
+
form: { type: 'string' },
|
|
181
|
+
filing_date: { type: 'string' },
|
|
182
|
+
report_date: nullableString,
|
|
183
|
+
acceptance_datetime: nullableString,
|
|
184
|
+
accession_number: { type: 'string' },
|
|
185
|
+
primary_document: nullableString,
|
|
186
|
+
primary_doc_description: nullableString,
|
|
187
|
+
items: nullableString,
|
|
188
|
+
size: nullableNumber,
|
|
189
|
+
is_xbrl: nullableBoolean,
|
|
190
|
+
is_inline_xbrl: nullableBoolean,
|
|
191
|
+
file_number: nullableString,
|
|
192
|
+
film_number: nullableString,
|
|
193
|
+
url: nullableString,
|
|
194
|
+
},
|
|
195
|
+
required: ['cik', 'company_name', 'form', 'filing_date', 'accession_number'],
|
|
196
|
+
additionalProperties: false,
|
|
197
|
+
};
|
|
198
|
+
function normalizeFilings(params) {
|
|
199
|
+
assertKnown(params, ['ticker', 'cik', 'form', 'limit']);
|
|
200
|
+
const ticker = params.ticker === undefined ? undefined : String(params.ticker).trim().toUpperCase();
|
|
201
|
+
const cik = params.cik === undefined ? undefined : String(params.cik).trim();
|
|
202
|
+
if ((ticker === undefined) === (cik === undefined))
|
|
203
|
+
throw new Error('exactly one of ticker or cik is required');
|
|
204
|
+
if (ticker !== undefined && !/^[A-Z][A-Z0-9.\-]{0,9}$/.test(ticker))
|
|
205
|
+
throw new Error('ticker must be a US ticker');
|
|
206
|
+
if (cik !== undefined && !/^\d{1,10}$/.test(cik))
|
|
207
|
+
throw new Error('cik must be 1 to 10 digits');
|
|
208
|
+
const form = params.form === undefined ? undefined : String(params.form).trim().toUpperCase();
|
|
209
|
+
const limit = params.limit === undefined ? 20 : Number(params.limit);
|
|
210
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
211
|
+
throw new Error('limit must be an integer from 1 to 100');
|
|
212
|
+
return { ...(ticker === undefined ? {} : { ticker }), ...(cik === undefined ? {} : { cik }), ...(form === undefined ? {} : { form }), limit };
|
|
213
|
+
}
|
|
214
|
+
function filingsUrl(cik, accession, primaryDocument) {
|
|
215
|
+
if (primaryDocument === null)
|
|
216
|
+
return null;
|
|
217
|
+
return `${SEC_WWW}/Archives/edgar/data/${Number(cik)}/${accession.replaceAll('-', '')}/${primaryDocument}`;
|
|
218
|
+
}
|
|
219
|
+
async function executeFilings(params, signal) {
|
|
220
|
+
let cik;
|
|
221
|
+
if (params.ticker !== undefined) {
|
|
222
|
+
const entry = (await tickerMap(signal)).get(String(params.ticker));
|
|
223
|
+
if (entry === undefined)
|
|
224
|
+
throw sourceError(`SEC ticker ${String(params.ticker)} is not in company_tickers.json`, 'sec_unknown_ticker');
|
|
225
|
+
cik = entry.cik;
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
cik = padCik(params.cik);
|
|
229
|
+
}
|
|
230
|
+
const payload = await secJson(`${SEC_DATA}/submissions/CIK${cik}.json`, signal, `SEC submissions ${cik}`);
|
|
231
|
+
if (!isRecord(payload))
|
|
232
|
+
throw sourceError('SEC submissions response is not an object');
|
|
233
|
+
const companyName = textOrNull(payload.entityName) ?? textOrNull(payload.name) ?? '';
|
|
234
|
+
const filings = isRecord(payload.filings) && isRecord(payload.filings.recent) ? payload.filings.recent : undefined;
|
|
235
|
+
if (filings === undefined)
|
|
236
|
+
throw sourceError('SEC submissions response has no filings.recent block');
|
|
237
|
+
const column = (name) => {
|
|
238
|
+
const value = filings[name];
|
|
239
|
+
if (!Array.isArray(value))
|
|
240
|
+
throw sourceError(`SEC submissions filings.recent.${name} is not an array`);
|
|
241
|
+
return value;
|
|
242
|
+
};
|
|
243
|
+
const accessions = column('accessionNumber');
|
|
244
|
+
const forms = column('form');
|
|
245
|
+
const filingDates = column('filingDate');
|
|
246
|
+
if (accessions.length !== forms.length || accessions.length !== filingDates.length)
|
|
247
|
+
throw sourceError('SEC submissions recent columns have different lengths');
|
|
248
|
+
const reportDates = column('reportDate');
|
|
249
|
+
const acceptance = column('acceptanceDateTime');
|
|
250
|
+
const primaryDocuments = column('primaryDocument');
|
|
251
|
+
const primaryDescriptions = column('primaryDocDescription');
|
|
252
|
+
const items = column('items');
|
|
253
|
+
const sizes = column('size');
|
|
254
|
+
const xbrl = column('isXBRL');
|
|
255
|
+
const inlineXbrl = column('isInlineXBRL');
|
|
256
|
+
const fileNumbers = column('fileNumber');
|
|
257
|
+
const filmNumbers = column('filmNumber');
|
|
258
|
+
const wantedForm = params.form === undefined ? undefined : String(params.form);
|
|
259
|
+
const rows = [];
|
|
260
|
+
for (let index = 0; index < accessions.length && rows.length < Number(params.limit); index += 1) {
|
|
261
|
+
const form = textOrNull(forms[index]);
|
|
262
|
+
if (form === null)
|
|
263
|
+
throw sourceError(`SEC submissions row ${index} has no form`);
|
|
264
|
+
if (wantedForm !== undefined && form !== wantedForm)
|
|
265
|
+
continue;
|
|
266
|
+
const accession = textOrNull(accessions[index]);
|
|
267
|
+
const filingDate = textOrNull(filingDates[index]);
|
|
268
|
+
if (accession === null || filingDate === null)
|
|
269
|
+
throw sourceError(`SEC submissions row ${index} has no accessionNumber/filingDate`);
|
|
270
|
+
const primaryDocument = textOrNull(primaryDocuments[index]);
|
|
271
|
+
rows.push({
|
|
272
|
+
cik,
|
|
273
|
+
company_name: companyName,
|
|
274
|
+
form,
|
|
275
|
+
filing_date: filingDate,
|
|
276
|
+
report_date: textOrNull(reportDates[index]),
|
|
277
|
+
acceptance_datetime: textOrNull(acceptance[index]),
|
|
278
|
+
accession_number: accession,
|
|
279
|
+
primary_document: primaryDocument,
|
|
280
|
+
primary_doc_description: textOrNull(primaryDescriptions[index]),
|
|
281
|
+
items: textOrNull(items[index]),
|
|
282
|
+
size: numberOrNull(sizes[index]),
|
|
283
|
+
is_xbrl: boolOrNull(xbrl[index]),
|
|
284
|
+
is_inline_xbrl: boolOrNull(inlineXbrl[index]),
|
|
285
|
+
file_number: textOrNull(fileNumbers[index]),
|
|
286
|
+
film_number: textOrNull(filmNumbers[index]),
|
|
287
|
+
url: filingsUrl(cik, accession, primaryDocument),
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return { data: rows, schema: filingRow };
|
|
291
|
+
}
|
|
292
|
+
// ── daily index ──────────────────────────────────────────────────────────────
|
|
293
|
+
const dailyIndexRow = {
|
|
294
|
+
type: 'object',
|
|
295
|
+
properties: {
|
|
296
|
+
form_type: { type: 'string' },
|
|
297
|
+
company_name: { type: 'string' },
|
|
298
|
+
cik: { type: 'string' },
|
|
299
|
+
filing_date: { type: 'string' },
|
|
300
|
+
file_name: { type: 'string' },
|
|
301
|
+
url: { type: 'string' },
|
|
302
|
+
},
|
|
303
|
+
required: ['form_type', 'company_name', 'cik', 'filing_date', 'file_name', 'url'],
|
|
304
|
+
additionalProperties: false,
|
|
305
|
+
};
|
|
306
|
+
function normalizeDailyFilings(params) {
|
|
307
|
+
assertKnown(params, ['filing_date', 'form']);
|
|
308
|
+
const filing_date = calendarDate(params.filing_date, 'filing_date');
|
|
309
|
+
const form = params.form === undefined ? undefined : String(params.form).trim().toUpperCase();
|
|
310
|
+
return { filing_date, ...(form === undefined ? {} : { form }) };
|
|
311
|
+
}
|
|
312
|
+
/** `form.YYYYMMDD.idx` rows: pipe-delimited when the header has `|`, otherwise 2+ spaces. */
|
|
313
|
+
function parseDailyIndex(text, label) {
|
|
314
|
+
const lines = text.split(/\r?\n/);
|
|
315
|
+
const headerIndex = lines.findIndex((line) => /Form Type/i.test(line) && /File Name/i.test(line));
|
|
316
|
+
if (headerIndex < 0)
|
|
317
|
+
throw sourceError(`${label} has no header row`);
|
|
318
|
+
const header = lines[headerIndex];
|
|
319
|
+
const pipe = header.includes('|');
|
|
320
|
+
const cellsOf = (line) => pipe
|
|
321
|
+
? line.split('|').map((cell) => cell.trim())
|
|
322
|
+
: line.trim().split(/\s{2,}/).map((cell) => cell.trim());
|
|
323
|
+
const names = cellsOf(header);
|
|
324
|
+
const indexOf = (pattern) => names.findIndex((name) => pattern.test(name));
|
|
325
|
+
const formIndex = indexOf(/^Form Type$/i);
|
|
326
|
+
const companyIndex = indexOf(/^Company Name$/i);
|
|
327
|
+
const cikIndex = indexOf(/^CIK$/i);
|
|
328
|
+
const dateIndex = indexOf(/^Date Filed$/i);
|
|
329
|
+
const fileIndex = indexOf(/^File Name$/i);
|
|
330
|
+
if ([formIndex, companyIndex, cikIndex, dateIndex, fileIndex].some((index) => index < 0))
|
|
331
|
+
throw sourceError(`${label} header columns changed: ${header}`);
|
|
332
|
+
const rows = [];
|
|
333
|
+
for (const line of lines.slice(headerIndex + 1)) {
|
|
334
|
+
if (line.trim().length === 0 || /^-{5,}/.test(line.trim()))
|
|
335
|
+
continue;
|
|
336
|
+
const cells = cellsOf(line);
|
|
337
|
+
if (cells.length <= Math.max(formIndex, companyIndex, cikIndex, dateIndex, fileIndex))
|
|
338
|
+
throw sourceError(`${label} row has ${cells.length} cells: ${line.slice(0, 120)}`);
|
|
339
|
+
const filingDate = cells[dateIndex];
|
|
340
|
+
if (!DATE_PATTERN.test(filingDate))
|
|
341
|
+
throw sourceError(`${label} row date is not YYYY-MM-DD: ${JSON.stringify(filingDate)}`);
|
|
342
|
+
const fileName = cells[fileIndex];
|
|
343
|
+
rows.push({
|
|
344
|
+
form_type: cells[formIndex],
|
|
345
|
+
company_name: cells[companyIndex],
|
|
346
|
+
cik: padCik(cells[cikIndex]),
|
|
347
|
+
filing_date: filingDate,
|
|
348
|
+
file_name: fileName,
|
|
349
|
+
url: `${SEC_WWW}/Archives/${fileName}`,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
return rows;
|
|
353
|
+
}
|
|
354
|
+
async function executeDailyFilings(params, signal) {
|
|
355
|
+
const filingDate = String(params.filing_date);
|
|
356
|
+
const year = filingDate.slice(0, 4);
|
|
357
|
+
const month = Number(filingDate.slice(5, 7));
|
|
358
|
+
const quarter = Math.floor((month - 1) / 3) + 1;
|
|
359
|
+
const compact = filingDate.replaceAll('-', '');
|
|
360
|
+
const url = `${SEC_WWW}/Archives/edgar/daily-index/${year}/Q${quarter}/form.${compact}.idx`;
|
|
361
|
+
const text = await secText(url, signal, `SEC daily index ${filingDate}`);
|
|
362
|
+
const wantedForm = params.form === undefined ? undefined : String(params.form);
|
|
363
|
+
const rows = parseDailyIndex(text, `SEC daily index ${filingDate}`).filter((row) => wantedForm === undefined || row.form_type === wantedForm);
|
|
364
|
+
return { data: rows, schema: dailyIndexRow };
|
|
365
|
+
}
|
|
366
|
+
// ── full-text search ─────────────────────────────────────────────────────────
|
|
367
|
+
const fulltextRow = {
|
|
368
|
+
type: 'object',
|
|
369
|
+
properties: {
|
|
370
|
+
accession_number: { type: 'string' },
|
|
371
|
+
form: nullableString,
|
|
372
|
+
file_date: nullableString,
|
|
373
|
+
period_ending: nullableString,
|
|
374
|
+
cik: nullableString,
|
|
375
|
+
display_name: nullableString,
|
|
376
|
+
file_type: nullableString,
|
|
377
|
+
file_name: nullableString,
|
|
378
|
+
url: nullableString,
|
|
379
|
+
},
|
|
380
|
+
required: ['accession_number'],
|
|
381
|
+
additionalProperties: false,
|
|
382
|
+
};
|
|
383
|
+
function normalizeFulltext(params) {
|
|
384
|
+
assertKnown(params, ['q', 'forms', 'start_date', 'end_date', 'limit']);
|
|
385
|
+
const q = typeof params.q === 'string' ? params.q.trim() : '';
|
|
386
|
+
if (q.length === 0 || q.length > 200)
|
|
387
|
+
throw new Error('q must be a non-empty string of at most 200 characters');
|
|
388
|
+
let forms;
|
|
389
|
+
if (params.forms !== undefined) {
|
|
390
|
+
if (!Array.isArray(params.forms) || params.forms.length === 0 || params.forms.length > 5)
|
|
391
|
+
throw new Error('forms must be an array of 1 to 5 form types');
|
|
392
|
+
forms = [...new Set(params.forms.map((value) => {
|
|
393
|
+
if (typeof value !== 'string' || value.trim().length === 0)
|
|
394
|
+
throw new Error('forms[] must be a non-empty string');
|
|
395
|
+
return value.trim().toUpperCase();
|
|
396
|
+
}))];
|
|
397
|
+
}
|
|
398
|
+
const hasStart = params.start_date !== undefined;
|
|
399
|
+
const hasEnd = params.end_date !== undefined;
|
|
400
|
+
if (hasStart !== hasEnd)
|
|
401
|
+
throw new Error('start_date and end_date must be given together');
|
|
402
|
+
const start_date = hasStart ? calendarDate(params.start_date, 'start_date') : undefined;
|
|
403
|
+
const end_date = hasEnd ? calendarDate(params.end_date, 'end_date') : undefined;
|
|
404
|
+
if (start_date !== undefined && end_date !== undefined && start_date > end_date)
|
|
405
|
+
throw new Error('start_date must not be later than end_date');
|
|
406
|
+
const limit = params.limit === undefined ? 10 : Number(params.limit);
|
|
407
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
408
|
+
throw new Error('limit must be an integer from 1 to 100');
|
|
409
|
+
return { q, ...(forms === undefined ? {} : { forms }), ...(start_date === undefined ? {} : { start_date }), ...(end_date === undefined ? {} : { end_date }), limit };
|
|
410
|
+
}
|
|
411
|
+
async function executeFulltext(params, signal) {
|
|
412
|
+
const query = new URLSearchParams();
|
|
413
|
+
query.set('q', String(params.q));
|
|
414
|
+
if (params.forms !== undefined)
|
|
415
|
+
query.set('forms', params.forms.join(','));
|
|
416
|
+
if (params.start_date !== undefined && params.end_date !== undefined) {
|
|
417
|
+
query.set('dateRange', 'custom');
|
|
418
|
+
query.set('startdt', String(params.start_date));
|
|
419
|
+
query.set('enddt', String(params.end_date));
|
|
420
|
+
}
|
|
421
|
+
const url = `${SEC_EFTS}/LATEST/search-index?${query.toString()}`;
|
|
422
|
+
const payload = await secJson(url, signal, 'SEC full-text search');
|
|
423
|
+
if (!isRecord(payload) || !isRecord(payload.hits) || !Array.isArray(payload.hits.hits))
|
|
424
|
+
throw sourceError('SEC full-text search response has no hits.hits array');
|
|
425
|
+
const rows = [];
|
|
426
|
+
for (const hit of payload.hits.hits.slice(0, Number(params.limit))) {
|
|
427
|
+
if (!isRecord(hit))
|
|
428
|
+
throw sourceError('SEC full-text search hit is not an object');
|
|
429
|
+
const id = typeof hit._id === 'string' ? hit._id : '';
|
|
430
|
+
const source = isRecord(hit._source) ? hit._source : {};
|
|
431
|
+
const accession = textOrNull(source.adsh) ?? (id.includes(':') ? id.slice(0, id.indexOf(':')) : null);
|
|
432
|
+
if (accession === null)
|
|
433
|
+
throw sourceError('SEC full-text search hit has no accession number');
|
|
434
|
+
const fileName = id.includes(':') ? id.slice(id.indexOf(':') + 1) : null;
|
|
435
|
+
const ciks = Array.isArray(source.ciks) ? source.ciks.map((value) => String(value)) : [];
|
|
436
|
+
const names = Array.isArray(source.display_names) ? source.display_names.map((value) => String(value)) : [];
|
|
437
|
+
const cik = ciks.length > 0 ? padCik(ciks[0]) : null;
|
|
438
|
+
rows.push({
|
|
439
|
+
accession_number: accession,
|
|
440
|
+
form: textOrNull(source.form),
|
|
441
|
+
file_date: textOrNull(source.file_date),
|
|
442
|
+
period_ending: textOrNull(source.period_ending),
|
|
443
|
+
cik,
|
|
444
|
+
display_name: names.length > 0 ? textOrNull(names[0]) : null,
|
|
445
|
+
file_type: textOrNull(source.file_type),
|
|
446
|
+
file_name: fileName,
|
|
447
|
+
url: cik === null || fileName === null ? null : `${SEC_WWW}/Archives/edgar/data/${Number(cik)}/${accession.replaceAll('-', '')}/${fileName}`,
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
return { data: rows, schema: fulltextRow };
|
|
451
|
+
}
|
|
452
|
+
// ── XBRL frames ──────────────────────────────────────────────────────────────
|
|
453
|
+
const FRAME_PERIOD_PATTERN = /^CY\d{4}(?:Q[1-4])?I?$/;
|
|
454
|
+
const marketFrameRow = {
|
|
455
|
+
type: 'object',
|
|
456
|
+
properties: {
|
|
457
|
+
cik: { type: 'string' },
|
|
458
|
+
entity_name: { type: 'string' },
|
|
459
|
+
value: nullableNumber,
|
|
460
|
+
accession_number: { type: 'string' },
|
|
461
|
+
start_date: nullableString,
|
|
462
|
+
end_date: { type: 'string' },
|
|
463
|
+
location: nullableString,
|
|
464
|
+
},
|
|
465
|
+
required: ['cik', 'entity_name', 'accession_number', 'end_date'],
|
|
466
|
+
additionalProperties: false,
|
|
467
|
+
};
|
|
468
|
+
function normalizeMarketFrame(params) {
|
|
469
|
+
assertKnown(params, ['tag', 'unit', 'period']);
|
|
470
|
+
const tag = typeof params.tag === 'string' ? params.tag.trim() : '';
|
|
471
|
+
if (!/^[A-Za-z][A-Za-z0-9]*$/.test(tag))
|
|
472
|
+
throw new Error('tag must be a us-gaap tag such as Assets or Revenues');
|
|
473
|
+
const unit = params.unit === undefined ? 'USD' : String(params.unit).trim();
|
|
474
|
+
if (!/^[A-Za-z]+$/.test(unit))
|
|
475
|
+
throw new Error('unit must be a unit code such as USD or shares');
|
|
476
|
+
const period = typeof params.period === 'string' ? params.period.trim().toUpperCase() : '';
|
|
477
|
+
if (!FRAME_PERIOD_PATTERN.test(period))
|
|
478
|
+
throw new Error('period must look like CY2025Q1I (instant), CY2025Q1 (duration) or CY2025');
|
|
479
|
+
return { tag, unit, period };
|
|
480
|
+
}
|
|
481
|
+
async function executeMarketFrame(params, signal) {
|
|
482
|
+
const tag = String(params.tag);
|
|
483
|
+
const unit = String(params.unit);
|
|
484
|
+
const period = String(params.period);
|
|
485
|
+
const url = `${SEC_DATA}/api/xbrl/frames/us-gaap/${encodeURIComponent(tag)}/${encodeURIComponent(unit)}/${encodeURIComponent(period)}.json`;
|
|
486
|
+
const payload = await secJson(url, signal, `SEC frames ${tag}/${unit}/${period}`);
|
|
487
|
+
if (!isRecord(payload) || !Array.isArray(payload.data))
|
|
488
|
+
throw sourceError(`SEC frames ${tag}/${unit}/${period} response has no data array`);
|
|
489
|
+
const rows = payload.data.map((raw, index) => {
|
|
490
|
+
if (!isRecord(raw))
|
|
491
|
+
throw sourceError(`SEC frames row ${index} is not an object`);
|
|
492
|
+
const endDate = textOrNull(raw.end);
|
|
493
|
+
const accession = textOrNull(raw.accn);
|
|
494
|
+
if (endDate === null || accession === null)
|
|
495
|
+
throw sourceError(`SEC frames row ${index} has no end/accn`);
|
|
496
|
+
return {
|
|
497
|
+
cik: padCik(raw.cik),
|
|
498
|
+
entity_name: textOrNull(raw.entityName) ?? (() => { throw sourceError(`SEC frames row ${index} has no entityName`); })(),
|
|
499
|
+
value: numberOrNull(raw.val),
|
|
500
|
+
accession_number: accession,
|
|
501
|
+
start_date: textOrNull(raw.start),
|
|
502
|
+
end_date: endDate,
|
|
503
|
+
location: textOrNull(raw.loc),
|
|
504
|
+
};
|
|
505
|
+
});
|
|
506
|
+
return { data: rows, schema: marketFrameRow };
|
|
507
|
+
}
|
|
508
|
+
// ── registration ─────────────────────────────────────────────────────────────
|
|
509
|
+
function createSecSource(options) {
|
|
510
|
+
const schema = {
|
|
511
|
+
capability: options.capability,
|
|
512
|
+
time_contract: getDataTimeContract(options.capability),
|
|
513
|
+
name: options.name,
|
|
514
|
+
source: `http:us-official.${options.capability}`,
|
|
515
|
+
data_key: buildDataKey('us_official', 'http', options.capability),
|
|
516
|
+
source_label: 'us_official',
|
|
517
|
+
paginated: false,
|
|
518
|
+
cacheMaxAgeMs: options.cacheMaxAgeMs,
|
|
519
|
+
rowShape: { rootArray: true },
|
|
520
|
+
summary: options.summary,
|
|
521
|
+
description: options.description,
|
|
522
|
+
input_schema: options.inputSchema,
|
|
523
|
+
output_schema: options.outputSchema,
|
|
524
|
+
};
|
|
525
|
+
return {
|
|
526
|
+
schema,
|
|
527
|
+
normalizeParams: (params) => options.normalize(params),
|
|
528
|
+
validateOutput: options.validateOutput,
|
|
529
|
+
execute: async (request, signal) => options.execute(options.normalize(request.params), signal),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
export function createSecSources() {
|
|
533
|
+
return [
|
|
534
|
+
createSecSource({
|
|
535
|
+
capability: 'sec_ticker_cik',
|
|
536
|
+
cacheMaxAgeMs: 86_400_000,
|
|
537
|
+
name: 'get_sec_ticker_cik',
|
|
538
|
+
summary: '美股 ticker → SEC CIK(批量)',
|
|
539
|
+
description: '把美股 ticker 映射到 SEC CIK(company_tickers.json,零 key)。`tickers` 1–20 个、自动大写去重;每个请求的 ticker 都返回一行,**未收录的 ticker 用 `found=false` + `cik=null` 显式标出,不是静默丢行**(该文件只含美股注册人,ADR/ETF 有时不在其中)。`cik` 是 10 位零填充字符串(SEC 全站口径),不是整数。上游文件约 1MB,进程内缓存 1 小时。⛔ 不要用 ticker 猜 CIK;也不要拿别的市场代码当美股 ticker。',
|
|
540
|
+
inputSchema: {
|
|
541
|
+
type: 'object',
|
|
542
|
+
properties: { tickers: { type: 'array', items: { type: 'string' }, description: '美股 ticker 列表(1–20 个,如 AAPL / MSFT)' } },
|
|
543
|
+
required: ['tickers'],
|
|
544
|
+
additionalProperties: false,
|
|
545
|
+
},
|
|
546
|
+
outputSchema: { type: 'array', items: tickerCikRow },
|
|
547
|
+
allowed: ['tickers'],
|
|
548
|
+
normalize: normalizeTickers,
|
|
549
|
+
validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.ticker === 'string' && typeof row.found === 'boolean'),
|
|
550
|
+
execute: executeTickerCik,
|
|
551
|
+
}),
|
|
552
|
+
createSecSource({
|
|
553
|
+
capability: 'sec_filings',
|
|
554
|
+
cacheMaxAgeMs: 1_800_000,
|
|
555
|
+
name: 'get_sec_filings',
|
|
556
|
+
summary: 'SEC 申报列表(submissions,按公司)',
|
|
557
|
+
description: '按公司取 SEC EDGAR 最近申报清单(submissions JSON:`data.sec.gov/submissions/CIK##########.json`,零 key)。`ticker` 与 `cik` 二选一;给 ticker 时先查 company_tickers.json。返回 `filings.recent` 块(上游列式数组转成行),`form` 精确过滤、`limit` 1–100(默认 20)。⛔ `filings.recent` 只覆盖最近约 1000 条,更早的申报在 `filings.files` 分年文件里,本能力不取——需要更早历史时不要假装这里没有就是没申报。`accession_number` 保留连字符;`url` 由 `https://www.sec.gov/Archives/edgar/data/{cik}/{accession 去连字符}/{primaryDocument}` 拼出,`primary_document` 为空时 `url=null`。`filing_date` 是**美东申报日**,`acceptance_datetime` 是 UTC 的 ISO 时刻(上游带 `Z`,不是美东本地时间);`report_date`(报告期)可能为空串。`items` 对 8-K/6-K 有意义(如 2.02),其它 form 常为空。SEC 要求声明式 UA(`SEC_USER_AGENT` 可覆盖)且 ≤10 req/s,本层自设 8 req/s。',
|
|
558
|
+
inputSchema: {
|
|
559
|
+
type: 'object',
|
|
560
|
+
properties: {
|
|
561
|
+
ticker: { type: 'string', description: '美股 ticker(与 cik 二选一)' },
|
|
562
|
+
cik: { type: 'string', description: 'SEC CIK(1–10 位数字,与 ticker 二选一)' },
|
|
563
|
+
form: { type: 'string', description: '精确匹配的 form 类型,如 8-K / 10-Q / 6-K' },
|
|
564
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: '最多返回行数,默认 20' },
|
|
565
|
+
},
|
|
566
|
+
required: [],
|
|
567
|
+
additionalProperties: false,
|
|
568
|
+
},
|
|
569
|
+
outputSchema: { type: 'array', items: filingRow },
|
|
570
|
+
allowed: ['ticker', 'cik', 'form', 'limit'],
|
|
571
|
+
normalize: normalizeFilings,
|
|
572
|
+
validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.accession_number === 'string'),
|
|
573
|
+
execute: executeFilings,
|
|
574
|
+
}),
|
|
575
|
+
createSecSource({
|
|
576
|
+
capability: 'sec_daily_filings',
|
|
577
|
+
cacheMaxAgeMs: 21_600_000,
|
|
578
|
+
name: 'get_sec_daily_filings',
|
|
579
|
+
summary: 'SEC 日索引(某美东申报日的全部申报)',
|
|
580
|
+
description: '取 SEC EDGAR 某一天的**日索引**(`Archives/edgar/daily-index/{年}/Q{季}/form.{YYYYMMDD}.idx`,零 key):当天所有申报的 form、公司名、CIK、申报日与文件路径。`filing_date` 是**美东申报日**,必须是已发布的工作日;`form` 可选、精确过滤(如 8-K)。一行一条申报;全量日(不限 form)实测可达数千行,按 form 过滤后再用。`url` 指向 `https://www.sec.gov/Archives/{file_name}`(索引条目,不是正文)。⛔ 该日索引不存在(周末/假日/尚未发布)时上游 404,本层响亮失败并提示换工作日,不返回空数组冒充「没有申报」。idx 行格式按表头自适应(有 `|` 按竖线切,否则按 2+ 空格切),表头列缺失、行宽不足、日期非 YYYY-MM-DD 都响亮失败。`filing_date` 是申报日,不是报告期。SEC 限速与 UA 同其它 sec_* 能力。',
|
|
581
|
+
inputSchema: {
|
|
582
|
+
type: 'object',
|
|
583
|
+
properties: {
|
|
584
|
+
filing_date: { type: 'string', description: '美东申报日 YYYY-MM-DD(必须是已发布的工作日)' },
|
|
585
|
+
form: { type: 'string', description: '精确匹配的 form 类型,如 8-K' },
|
|
586
|
+
},
|
|
587
|
+
required: ['filing_date'],
|
|
588
|
+
additionalProperties: false,
|
|
589
|
+
},
|
|
590
|
+
outputSchema: { type: 'array', items: dailyIndexRow },
|
|
591
|
+
allowed: ['filing_date', 'form'],
|
|
592
|
+
normalize: normalizeDailyFilings,
|
|
593
|
+
validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.file_name === 'string'),
|
|
594
|
+
execute: executeDailyFilings,
|
|
595
|
+
}),
|
|
596
|
+
createSecSource({
|
|
597
|
+
capability: 'sec_fulltext_search',
|
|
598
|
+
cacheMaxAgeMs: 1_800_000,
|
|
599
|
+
name: 'get_sec_fulltext_search',
|
|
600
|
+
summary: 'SEC 全文检索(EDGAR FTS)',
|
|
601
|
+
description: 'SEC EDGAR 全文检索(`efts.sec.gov/LATEST/search-index`,零 key):按关键词找申报文件。`q` 必填(≤200 字符,短语可用引号);`forms` 可选 1–5 个 form 类型;`start_date`/`end_date` 可选但必须成对给(美东申报日);`limit` 1–100(默认 10)。返回 `hits.hits` 的申报级行:`accession_number`、`form`、`file_date`、`period_ending`、`cik`(10 位)、`display_name`、`file_type`、`file_name`(来自 `_id` 冒号后半段)与拼出的 `url`。⛔ `_id` 是 `{accession}:{filename}`,**不是 URL**,必须按 cik+accession 重新拼;cik 缺失时 `url=null`。⛔ 全文检索只覆盖 2001 年以来的电子申报正文,且是关键词匹配不是语义检索;命中排序由上游给,本层不改。空命中返回成功空数组。SEC 限速与 UA 同其它 sec_* 能力。',
|
|
602
|
+
inputSchema: {
|
|
603
|
+
type: 'object',
|
|
604
|
+
properties: {
|
|
605
|
+
q: { type: 'string', description: '检索词(≤200 字符;短语加引号)' },
|
|
606
|
+
forms: { type: 'array', items: { type: 'string' }, description: 'form 类型列表(1–5 个)' },
|
|
607
|
+
start_date: { type: 'string', description: '起始申报日 YYYY-MM-DD(与 end_date 成对)' },
|
|
608
|
+
end_date: { type: 'string', description: '截止申报日 YYYY-MM-DD(与 start_date 成对)' },
|
|
609
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: '最多返回行数,默认 10' },
|
|
610
|
+
},
|
|
611
|
+
required: ['q'],
|
|
612
|
+
additionalProperties: false,
|
|
613
|
+
},
|
|
614
|
+
outputSchema: { type: 'array', items: fulltextRow },
|
|
615
|
+
allowed: ['q', 'forms', 'start_date', 'end_date', 'limit'],
|
|
616
|
+
normalize: normalizeFulltext,
|
|
617
|
+
validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.accession_number === 'string'),
|
|
618
|
+
execute: executeFulltext,
|
|
619
|
+
}),
|
|
620
|
+
createSecSource({
|
|
621
|
+
capability: 'sec_market_frame',
|
|
622
|
+
cacheMaxAgeMs: 86_400_000,
|
|
623
|
+
name: 'get_sec_market_frame',
|
|
624
|
+
summary: 'SEC XBRL frames(同 tag 全市场横截面)',
|
|
625
|
+
description: '获取 SEC XBRL frames:某个 us-gaap 概念在**同一报告期**的全市场横截面(`data.sec.gov/api/xbrl/frames/us-gaap/{tag}/{unit}/{period}.json`,零 key)。`tag` 如 Assets / Revenues / NetIncomeLoss;`unit` 默认 USD;`period` 形如 `CY2025Q1I`(instant,时点)、`CY2025Q1`(duration,区间)、`CY2025`(年度)。真报文实测(2026-11-27):`Assets/USD/CY2025Q1I` 有 `pts:5655` 行,单次响应约 1MB——本能力**不分页、一次返回全部行**,按 `limit` 截断不做(会静默丢公司);要收窄就在本地用 tag/period 选。行字段:`cik`(10 位补零)、`entity_name`、`value`(报告币种原值;instant 是时点值、duration 是区间值,⛔ 不可跨期直接比较)、`accession_number`、`start_date`(instant 行为 null)、`end_date`、`location`(如 US-CA,可能为空串或 `-`)。⛔ 同一 tag 不同公司的会计口径/期间端点不同(如 52/53 周财年),`end_date` 会分散在几天内,不是数据错误;不要把 frames 当「同一时刻快照」。空 data 是合法空(该期没有申报该 tag)。SEC 限速与 UA 同其它 sec_* 能力。',
|
|
626
|
+
inputSchema: {
|
|
627
|
+
type: 'object',
|
|
628
|
+
properties: {
|
|
629
|
+
tag: { type: 'string', description: 'us-gaap 概念名,如 Assets / Revenues / NetIncomeLoss' },
|
|
630
|
+
unit: { type: 'string', description: '单位代码,默认 USD' },
|
|
631
|
+
period: { type: 'string', description: '报告期:CY2025Q1I(时点)/ CY2025Q1(区间)/ CY2025' },
|
|
632
|
+
},
|
|
633
|
+
required: ['tag', 'period'],
|
|
634
|
+
additionalProperties: false,
|
|
635
|
+
},
|
|
636
|
+
outputSchema: { type: 'array', items: marketFrameRow },
|
|
637
|
+
allowed: ['tag', 'unit', 'period'],
|
|
638
|
+
normalize: normalizeMarketFrame,
|
|
639
|
+
validateOutput: (data) => Array.isArray(data) && data.every((row) => isRecord(row) && typeof row.cik === 'string' && typeof row.end_date === 'string'),
|
|
640
|
+
execute: executeMarketFrame,
|
|
641
|
+
}),
|
|
642
|
+
];
|
|
643
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** US official data sources (Treasury, NY Fed): zero-key public endpoints, one throttle per host,
|
|
2
|
+
* rows are plain arrays (no upstream pagination). SEC (same file family) is added separately. */
|
|
3
|
+
import type { DataSource } from '../data-collector/hub.js';
|
|
4
|
+
export declare function createUsOfficialSources(): DataSource[];
|