1import { XMLParser } from 'fast-xml-parser';
2import { FormDFilingSchema, type FormDFiling, type RelatedPerson } from '../schema.js';
3import type { SecHttpClient } from './rate-limiter.js';
4import { buildFormDXmlUrl, buildSecIndexUrl } from './submissions.js';
5import { normalizeCik, type TickerResolver } from './tickers.js';
6
7export const EFTS_SEARCH_URL = 'https://efts.sec.gov/LATEST/search-index';
8
9interface EftsHitSource {
10 ciks?: string[];
11 display_names?: string[];
12 file_date?: string;
13 form?: string;
14 adsh?: string;
15 biz_states?: string[];
16 inc_states?: string[];
17}
18
19interface EftsHit {
20 _id: string;
21 _source: EftsHitSource;
22}
23
24interface EftsSearchResponse {
25 hits?: {
26 total?: { value: number };
27 hits?: EftsHit[];
28 };
29}
30
31const xmlParser = new XMLParser({
32 ignoreAttributes: true,
33 parseTagValue: false,
34 trimValues: true,
35 isArray: (tagName) =>
36 tagName === 'relatedPersonInfo' ||
37 tagName === 'relationship' ||
38 tagName === 'item',
39});
40
41function asNonEmptyString(value: unknown): string | null {
42 if (value === null || value === undefined) return null;
43 const str = String(value).trim();
44 if (!str || str.toLowerCase() === 'none') return null;
45 return str;
46}
47
48function asBoolean(value: unknown): boolean {
49 if (typeof value === 'boolean') return value;
50 if (typeof value === 'string') {
51 const lower = value.trim().toLowerCase();
52 return lower === 'true' || lower === '1' || lower === 'yes';
53 }
54 return false;
55}
56
57function asNullableBoolean(value: unknown): boolean | null {
58 if (value === null || value === undefined || value === '') return null;
59 return asBoolean(value);
60}
61
62function asNullableNumber(value: unknown): number | null {
63 if (value === null || value === undefined) return null;
64 const str = String(value).trim().replace(/,/g, '');
65 if (!str) return null;
66 const num = Number(str);
67 return Number.isFinite(num) ? num : null;
68}
69
70function parseOfferingAmount(value: unknown): number | 'Indefinite' | null {
71 if (value === null || value === undefined) return null;
72 const str = String(value).trim();
73 if (!str) return null;
74 if (str.toLowerCase() === 'indefinite') return 'Indefinite';
75 return asNullableNumber(str);
76}
77
78function parseYearOfIncorporation(yearOfInc: Record<string, unknown> | undefined): string | null {
79 if (!yearOfInc || typeof yearOfInc !== 'object') return null;
80 const explicit = asNonEmptyString(yearOfInc.value);
81 if (explicit) return explicit;
82 if (asBoolean(yearOfInc.overFiveYears)) return 'Over Five Years';
83 if (asBoolean(yearOfInc.yetToBeFormed)) return 'Yet to Be Formed';
84 return null;
85}
86
87
88
89
90
91function parseRelatedPersonsNonPii(rawList: unknown): RelatedPerson[] {
92 if (!rawList || typeof rawList !== 'object') return [];
93 const container = rawList as { relatedPersonInfo?: unknown };
94 const entries = Array.isArray(container.relatedPersonInfo)
95 ? container.relatedPersonInfo
96 : container.relatedPersonInfo
97 ? [container.relatedPersonInfo]
98 : [];
99
100 const results: RelatedPerson[] = [];
101 for (const entry of entries) {
102 if (!entry || typeof entry !== 'object') continue;
103 const person = entry as Record<string, unknown>;
104 const nameObj = (person.relatedPersonName ?? {}) as Record<string, unknown>;
105 const nameParts = [
106 asNonEmptyString(nameObj.firstName),
107 asNonEmptyString(nameObj.middleName),
108 asNonEmptyString(nameObj.lastName),
109 ].filter((p): p is string => Boolean(p));
110
111 const fullName = nameParts.join(' ').trim();
112 if (!fullName) continue;
113
114 const relList = (person.relatedPersonRelationshipList ?? {}) as Record<string, unknown>;
115 const rawRels = Array.isArray(relList.relationship)
116 ? relList.relationship
117 : relList.relationship
118 ? [relList.relationship]
119 : [];
120 const roles = rawRels
121 .map((r) => asNonEmptyString(r))
122 .filter((r): r is string => Boolean(r));
123
124 results.push({
125 name: fullName,
126 roles,
127 clarification: asNonEmptyString(person.relationshipClarification),
128 });
129 }
130
131 return results;
132}
133
134export interface FormDXmlContext {
135 filingDate: string;
136 accessionNumber: string;
137 fallbackCik?: string;
138 fallbackFormType?: string;
139 ticker?: string | null;
140 xmlFilename?: string;
141}
142
143
144
145
146
147export function parseFormDXml(xmlContent: string, ctx: FormDXmlContext): FormDFiling {
148 const parsed = xmlParser.parse(xmlContent) as { edgarSubmission?: Record<string, unknown> };
149 const root = parsed.edgarSubmission;
150 if (!root || typeof root !== 'object') {
151 throw new Error(`Invalid Form D XML for accession ${ctx.accessionNumber}: missing <edgarSubmission>`);
152 }
153
154 const primaryIssuer = (root.primaryIssuer ?? {}) as Record<string, unknown>;
155 const issuerAddress = (primaryIssuer.issuerAddress ?? {}) as Record<string, unknown>;
156 const offeringData = (root.offeringData ?? {}) as Record<string, unknown>;
157 const industryGroup = (offeringData.industryGroup ?? {}) as Record<string, unknown>;
158 const issuerSize = (offeringData.issuerSize ?? {}) as Record<string, unknown>;
159 const exemptionsObj = (offeringData.federalExemptionsExclusions ?? {}) as Record<string, unknown>;
160 const typeOfFiling = (offeringData.typeOfFiling ?? {}) as Record<string, unknown>;
161 const dateOfFirstSale = (typeOfFiling.dateOfFirstSale ?? {}) as Record<string, unknown>;
162 const securities = (offeringData.typesOfSecuritiesOffered ?? {}) as Record<string, unknown>;
163 const salesAmounts = (offeringData.offeringSalesAmounts ?? {}) as Record<string, unknown>;
164 const investors = (offeringData.investors ?? {}) as Record<string, unknown>;
165
166 const rawCik = asNonEmptyString(primaryIssuer.cik) ?? ctx.fallbackCik;
167 if (!rawCik) {
168 throw new Error(`Missing CIK in Form D XML for accession ${ctx.accessionNumber}`);
169 }
170 const cik = normalizeCik(rawCik);
171
172 const issuerName = asNonEmptyString(primaryIssuer.entityName);
173 if (!issuerName) {
174 throw new Error(`Missing entityName in Form D XML for accession ${ctx.accessionNumber}`);
175 }
176
177 const rawExemptions = Array.isArray(exemptionsObj.item)
178 ? exemptionsObj.item
179 : exemptionsObj.item
180 ? [exemptionsObj.item]
181 : [];
182 const federalExemptions = rawExemptions
183 .map((e) => asNonEmptyString(e))
184 .filter((e): e is string => Boolean(e));
185
186 const formType = asNonEmptyString(root.submissionType) ?? ctx.fallbackFormType ?? 'D';
187 const xmlFilename = ctx.xmlFilename ?? 'primary_doc.xml';
188
189
190
191 const record: FormDFiling = {
192 mode: 'form_d',
193 formType,
194 issuerName,
195 cik,
196 ticker: ctx.ticker ?? null,
197 entityType: asNonEmptyString(primaryIssuer.entityType),
198 yearOfIncorporation: parseYearOfIncorporation(
199 primaryIssuer.yearOfInc as Record<string, unknown> | undefined,
200 ),
201 jurisdictionOfInc: asNonEmptyString(primaryIssuer.jurisdictionOfInc),
202 issuerCity: asNonEmptyString(issuerAddress.city),
203 issuerState: asNonEmptyString(issuerAddress.stateOrCountry),
204 industryGroupType: asNonEmptyString(industryGroup.industryGroupType),
205 revenueRange:
206 asNonEmptyString(issuerSize.revenueRange) ??
207 asNonEmptyString(issuerSize.aggregateNetAssetValueRange),
208 totalOfferingAmount: parseOfferingAmount(salesAmounts.totalOfferingAmount),
209 totalAmountSold: asNullableNumber(salesAmounts.totalAmountSold),
210 totalRemaining: asNullableNumber(salesAmounts.totalRemaining),
211 minimumInvestmentAccepted: asNullableNumber(offeringData.minimumInvestmentAccepted),
212 isEquity: asBoolean(securities.isEquityType),
213 isDebt: asBoolean(securities.isDebtType),
214 isPooledInvestmentFund: asBoolean(securities.isPooledInvestmentFundType),
215 federalExemptions,
216 dateOfFirstSale: asNonEmptyString(dateOfFirstSale.value),
217 hasNonAccreditedInvestors: asNullableBoolean(investors.hasNonAccreditedInvestors),
218 totalNumberAlreadyInvested: asNullableNumber(investors.totalNumberAlreadyInvested),
219 relatedPersons: parseRelatedPersonsNonPii(root.relatedPersonsList),
220 filingDate: ctx.filingDate,
221 accessionNumber: ctx.accessionNumber,
222 secFilingUrl: buildSecIndexUrl(cik, ctx.accessionNumber),
223 xmlUrl: buildFormDXmlUrl(cik, ctx.accessionNumber, xmlFilename),
224 extractedAt: new Date().toISOString(),
225 };
226
227 return FormDFilingSchema.parse(record);
228}
229
230export interface FetchFormDOptions {
231 startDate: string;
232 endDate: string;
233 keyword?: string;
234 states: string[];
235 maxResults: number;
236}
237
238export async function fetchFormDFundings(
239 client: SecHttpClient,
240 tickerResolver: TickerResolver,
241 options: FetchFormDOptions,
242): Promise<FormDFiling[]> {
243 const stateSet = new Set(options.states.map((s) => s.toUpperCase()));
244 const fetchSize = Math.min(Math.max(options.maxResults * (stateSet.size > 0 ? 3 : 2), 25), 100);
245
246 const params = new URLSearchParams({
247 forms: 'D,D/A',
248 dateRange: 'custom',
249 startdt: options.startDate,
250 enddt: options.endDate,
251 from: '0',
252 size: String(fetchSize),
253 });
254
255 if (options.keyword) {
256 params.set('q', options.keyword);
257 }
258
259 const searchUrl = `${EFTS_SEARCH_URL}?${params.toString()}`;
260 const response = await client.fetchJson<EftsSearchResponse>(searchUrl);
261 const hits = response.hits?.hits ?? [];
262
263 const results: FormDFiling[] = [];
264 const seenAccessions = new Set<string>();
265
266 for (const hit of hits) {
267 if (results.length >= options.maxResults) {
268 break;
269 }
270 const src = hit._source;
271 const accessionNumber = src.adsh?.trim();
272 const rawCik = src.ciks?.[0];
273 if (!accessionNumber || !rawCik || seenAccessions.has(accessionNumber)) {
274 continue;
275 }
276
277 if (stateSet.size > 0) {
278 const hitStates = [...(src.biz_states ?? []), ...(src.inc_states ?? [])].map((s) =>
279 s.toUpperCase(),
280 );
281 if (hitStates.length > 0 && !hitStates.some((s) => stateSet.has(s))) {
282 continue;
283 }
284 }
285
286 seenAccessions.add(accessionNumber);
287
288 const cik = normalizeCik(rawCik);
289 const xmlFilename = hit._id.includes(':') ? hit._id.split(':')[1] : 'primary_doc.xml';
290 const xmlUrl = buildFormDXmlUrl(cik, accessionNumber, xmlFilename || 'primary_doc.xml');
291
292 try {
293 const xmlText = await client.fetchText(xmlUrl, 'application/xml, text/xml');
294 const ticker = await tickerResolver.lookupTickerByCik(cik);
295 const record = parseFormDXml(xmlText, {
296 filingDate: src.file_date ?? options.endDate,
297 accessionNumber,
298 fallbackCik: cik,
299 fallbackFormType: src.form ?? 'D',
300 ticker,
301 xmlFilename: xmlFilename || 'primary_doc.xml',
302 });
303
304 if (stateSet.size > 0) {
305 const stateMatch =
306 (record.issuerState && stateSet.has(record.issuerState.toUpperCase())) ||
307 (src.biz_states ?? []).some((s) => stateSet.has(s.toUpperCase()));
308 if (!stateMatch) {
309 continue;
310 }
311 }
312
313 results.push(record);
314 } catch {
315
316 }
317 }
318
319 return results;
320}