stock-bot/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts

915 lines
26 KiB
TypeScript

import { compareAscii } from './exchange-pass1';
import type {
ReadOnlySourceSymbolCursor,
ReadOnlySourceSymbolReader,
SourceSymbolFindOptions,
} from './source-symbol-readers';
export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([
'ceoShorts',
'qmSplits',
'qmDividends',
'qmFilings',
'qmEarnings',
'qmPrices',
'eodPrices',
'teMarketData',
] as const);
export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number];
export const FIELD_VALUE_TYPES = Object.freeze([
'string',
'int',
'double',
'bool',
'date',
'null',
'objectId',
'array',
'object',
'other',
] as const);
export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number];
export const STRING_PATTERN_CLASSES = Object.freeze([
'ymd',
'isoDatetime',
'numeric',
'emptyOrWhitespace',
'other',
] as const);
export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number];
export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000;
export const MAX_FIELD_SHAPE_LIMIT = 10_000;
export const DEFAULT_MAX_EXAMPLES = 3;
export const MAX_EXAMPLES_CAP = 10;
export const DEFAULT_MAX_EXAMPLE_LENGTH = 48;
export const MAX_EXAMPLE_LENGTH_CAP = 120;
const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet<string> = new Set<string>(
FIELD_SHAPE_PROBE_COLLECTIONS
);
export class UnknownProbeCollectionError extends Error {
readonly collectionName: string;
readonly allowedCollections: readonly FieldShapeProbeCollection[];
constructor(collectionName: string) {
super(
`Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}`
);
this.name = 'UnknownProbeCollectionError';
this.collectionName = collectionName;
this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS;
Object.setPrototypeOf(this, new.target.prototype);
}
}
export type FieldValueTypeCounts = Record<FieldValueType, number>;
export type StringPatternCounts = Record<StringPatternClass, number>;
export interface FieldStringStats {
minLength: number;
maxLength: number;
patterns: StringPatternCounts;
}
export interface FieldShapeSummary {
field: string;
presentCount: number;
missingCount: number;
typeCounts: FieldValueTypeCounts;
stringStats: FieldStringStats | null;
examples: string[];
}
export interface SummarizeFieldShapesOptions {
readonly maxExamples?: number;
readonly maxExampleLength?: number;
}
export interface CollectionFieldShapesSummary {
docCount: number;
fields: FieldShapeSummary[];
}
export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions {
readonly collections?: readonly string[];
readonly limit?: number;
readonly batchSize?: number;
}
export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary {
collection: FieldShapeProbeCollection;
}
export interface ReadFieldShapesResult {
limit: number;
maxExamples: number;
maxExampleLength: number;
totalDocsSampled: number;
collections: CollectionFieldShapesProbeResult[];
}
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const STRICT_ISO_DATETIME_PATTERN =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/;
const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function isValidCalendarDate(year: number, month: number, day: number): boolean {
if (year < 1 || year > 9999 || month < 1 || month > 12) {
return false;
}
const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0);
return day >= 1 && day <= maxDay;
}
function isValidYmd(value: string): boolean {
if (!EXACT_YMD_PATTERN.test(value)) {
return false;
}
const year =
(value.charCodeAt(0) - 48) * 1000 +
(value.charCodeAt(1) - 48) * 100 +
(value.charCodeAt(2) - 48) * 10 +
(value.charCodeAt(3) - 48);
const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48);
const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48);
return isValidCalendarDate(year, month, day);
}
function isValidIsoDatetime(value: string): boolean {
const match = STRICT_ISO_DATETIME_PATTERN.exec(value);
if (match === null) {
return false;
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hour = Number(match[4]);
const minute = Number(match[5]);
const second = Number(match[6]);
if (!isValidCalendarDate(year, month, day)) {
return false;
}
if (hour > 23 || minute > 59 || second > 59) {
return false;
}
if (match[7] !== undefined) {
const tzHour = Number(match[8]);
const tzMinute = Number(match[9]);
if (tzHour > 23 || tzMinute > 59) {
return false;
}
}
return true;
}
function classifyStringPattern(value: string): StringPatternClass {
if (value.length === 0 || value.trim().length === 0) {
return 'emptyOrWhitespace';
}
if (value.length === 10 && isValidYmd(value)) {
return 'ymd';
}
if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) {
return 'isoDatetime';
}
if (NUMERIC_STRING_PATTERN.test(value)) {
return 'numeric';
}
return 'other';
}
function createEmptyTypeCounts(): FieldValueTypeCounts {
return {
string: 0,
int: 0,
double: 0,
bool: 0,
date: 0,
null: 0,
objectId: 0,
array: 0,
object: 0,
other: 0,
};
}
function createEmptyStringPatternCounts(): StringPatternCounts {
return {
ymd: 0,
isoDatetime: 0,
numeric: 0,
emptyOrWhitespace: 0,
other: 0,
};
}
function isNonPlainBuiltInObject(value: object): boolean {
return (
value instanceof Date ||
Array.isArray(value) ||
ArrayBuffer.isView(value) ||
value instanceof ArrayBuffer ||
value instanceof RegExp ||
value instanceof Map ||
value instanceof Set
);
}
function getBsonTypeTag(value: object): string | null {
const tag = (value as { _bsontype?: unknown })._bsontype;
return typeof tag === 'string' && tag.length > 0 ? tag : null;
}
function isPlainNestedObject(value: unknown): value is Record<string, unknown> {
if (value === null || typeof value !== 'object') {
return false;
}
if (isNonPlainBuiltInObject(value)) {
return false;
}
if (getBsonTypeTag(value) !== null) {
return false;
}
return true;
}
function classifyValueType(value: unknown): FieldValueType {
if (value === null) {
return 'null';
}
const primitiveType = typeof value;
if (primitiveType === 'string') {
return 'string';
}
if (primitiveType === 'boolean') {
return 'bool';
}
if (primitiveType === 'number') {
return Number.isInteger(value) ? 'int' : 'double';
}
if (primitiveType === 'bigint') {
return 'int';
}
if (primitiveType !== 'object') {
return 'other';
}
const obj = value as object;
if (obj instanceof Date) {
return 'date';
}
if (Array.isArray(obj)) {
return 'array';
}
const bsonTag = getBsonTypeTag(obj);
if (bsonTag !== null) {
if (bsonTag === 'Int32' || bsonTag === 'Long') {
return 'int';
}
if (bsonTag === 'Double') {
return 'double';
}
if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') {
return 'objectId';
}
return 'other';
}
if (isNonPlainBuiltInObject(obj)) {
return 'other';
}
return 'object';
}
function escapeFieldSegment(segment: string): string {
if (!segment.includes('.') && !segment.includes('\\')) {
return segment;
}
return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
}
function formatFieldPath(parentKey: string, childKey?: string): string {
const escapedParent = escapeFieldSegment(parentKey);
return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`;
}
function sanitizeAndTruncateExample(raw: string, maxLength: number): string {
let cleaned = '';
for (let i = 0; i < raw.length; i++) {
const code = raw.charCodeAt(i);
if (code === 9 || code === 10 || code === 13) {
cleaned += ' ';
} else if (code >= 32 && code !== 127) {
cleaned += raw[i];
}
}
if (cleaned.length <= maxLength) {
return cleaned;
}
if (maxLength <= 3) {
return cleaned.slice(0, maxLength);
}
return `${cleaned.slice(0, maxLength - 3)}...`;
}
function extractScalarExample(
value: unknown,
valueType: FieldValueType,
maxExampleLength: number
): string | null {
if (valueType === 'null' || valueType === 'array' || valueType === 'object') {
return null;
}
let raw: string | null = null;
if (valueType === 'string') {
raw = value as string;
} else if (valueType === 'bool') {
raw = (value as boolean) ? 'true' : 'false';
} else if (valueType === 'int' || valueType === 'double') {
if (typeof value === 'number' || typeof value === 'bigint') {
raw = String(value);
} else if (value !== null && typeof value === 'object') {
raw = String(value);
}
} else if (valueType === 'date' && value instanceof Date) {
raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
} else if (valueType === 'objectId') {
raw = String(value);
} else if (valueType === 'other' && value !== null && typeof value === 'object') {
const bsonTag = getBsonTypeTag(value);
if (bsonTag === 'Decimal128' || bsonTag === 'UUID') {
raw = String(value);
}
}
if (raw === null) {
return null;
}
return sanitizeAndTruncateExample(raw, maxExampleLength);
}
function validateBoundedInt(value: unknown, name: string, min: number, max: number): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`);
}
return value;
}
function validatePositiveSafeInt(value: unknown, name: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
}
return value;
}
function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): {
maxExamples: number;
maxExampleLength: number;
} {
if (options !== undefined && (options === null || typeof options !== 'object')) {
throw new TypeError('options must be an object');
}
const maxExamples =
options?.maxExamples !== undefined
? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP)
: DEFAULT_MAX_EXAMPLES;
const maxExampleLength =
options?.maxExampleLength !== undefined
? validateBoundedInt(
options.maxExampleLength,
'options.maxExampleLength',
1,
MAX_EXAMPLE_LENGTH_CAP
)
: DEFAULT_MAX_EXAMPLE_LENGTH;
return { maxExamples, maxExampleLength };
}
interface MutableFieldAccumulator {
presentCount: number;
typeCounts: FieldValueTypeCounts;
stringStats: FieldStringStats | null;
examples: string[];
}
/**
* Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes`
* and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field.
*/
class FieldShapeAccumulator {
private readonly maxExamples: number;
private readonly maxExampleLength: number;
private readonly fields = new Map<string, MutableFieldAccumulator>();
private docCount = 0;
constructor(maxExamples: number, maxExampleLength: number) {
this.maxExamples = maxExamples;
this.maxExampleLength = maxExampleLength;
}
addDocument(doc: unknown): void {
this.docCount += 1;
if (!isPlainNestedObject(doc)) {
return;
}
const keys = Object.keys(doc);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === undefined) {
continue;
}
const value = doc[key];
if (value === undefined) {
continue;
}
const suppressExamples = key === '_id';
const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples);
if (valueType === 'object' && isPlainNestedObject(value)) {
const childKeys = Object.keys(value);
for (let j = 0; j < childKeys.length; j++) {
const childKey = childKeys[j];
if (childKey === undefined) {
continue;
}
const childValue = value[childKey];
if (childValue === undefined) {
continue;
}
this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples);
}
}
}
}
finalize(): CollectionFieldShapesSummary {
const sortedNames = Array.from(this.fields.keys()).sort(compareAscii);
const summaries: FieldShapeSummary[] = [];
for (let i = 0; i < sortedNames.length; i++) {
const fieldName = sortedNames[i];
if (fieldName === undefined) {
continue;
}
const acc = this.fields.get(fieldName);
if (acc === undefined) {
continue;
}
summaries.push({
field: fieldName,
presentCount: acc.presentCount,
missingCount: this.docCount - acc.presentCount,
typeCounts: { ...acc.typeCounts },
stringStats:
acc.stringStats === null
? null
: {
minLength: acc.stringStats.minLength,
maxLength: acc.stringStats.maxLength,
patterns: { ...acc.stringStats.patterns },
},
examples: [...acc.examples],
});
}
return {
docCount: this.docCount,
fields: summaries,
};
}
private recordFieldValue(
fieldPath: string,
value: unknown,
suppressExamples: boolean
): FieldValueType {
let acc = this.fields.get(fieldPath);
if (acc === undefined) {
acc = {
presentCount: 0,
typeCounts: createEmptyTypeCounts(),
stringStats: null,
examples: [],
};
this.fields.set(fieldPath, acc);
}
const valueType = classifyValueType(value);
acc.presentCount += 1;
acc.typeCounts[valueType] += 1;
if (valueType === 'string') {
const str = value as string;
const len = str.length;
if (acc.stringStats === null) {
acc.stringStats = {
minLength: len,
maxLength: len,
patterns: createEmptyStringPatternCounts(),
};
} else {
if (len < acc.stringStats.minLength) {
acc.stringStats.minLength = len;
}
if (len > acc.stringStats.maxLength) {
acc.stringStats.maxLength = len;
}
}
acc.stringStats.patterns[classifyStringPattern(str)] += 1;
}
if (this.maxExamples > 0 && !suppressExamples) {
const example = extractScalarExample(value, valueType, this.maxExampleLength);
if (example !== null) {
this.insertExample(acc.examples, example);
}
}
return valueType;
}
private insertExample(examples: string[], candidate: string): void {
const len = examples.length;
const last = len > 0 ? examples[len - 1] : undefined;
if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) {
return;
}
let insertAt = len;
for (let i = 0; i < len; i++) {
const existing = examples[i];
if (existing === undefined) {
continue;
}
const cmp = compareAscii(candidate, existing);
if (cmp === 0) {
return;
}
if (cmp < 0) {
insertAt = i;
break;
}
}
examples.splice(insertAt, 0, candidate);
if (examples.length > this.maxExamples) {
examples.pop();
}
}
}
/**
* Pure, deterministic summarizer for field names, BSON/JS value types, string patterns,
* and bounded sanitized examples across an iterable of documents from one collection.
*/
export function summarizeFieldShapes(
docs: Iterable<Record<string, unknown>>,
options?: SummarizeFieldShapesOptions
): CollectionFieldShapesSummary {
if (
docs === null ||
docs === undefined ||
typeof (docs as unknown as Record<symbol, unknown>)[Symbol.iterator] !== 'function'
) {
throw new TypeError('docs must be an Iterable of document objects');
}
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
for (const doc of docs) {
accumulator.addDocument(doc);
}
return accumulator.finalize();
}
export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection {
return ALLOWED_PROBE_COLLECTION_SET.has(value);
}
export function normalizeProbeCollections(
collections?: readonly string[]
): FieldShapeProbeCollection[] {
const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections;
if (!Array.isArray(source) || source.length === 0) {
throw new RangeError('collections must be a non-empty array of allowed probe collection names');
}
const unique = new Set<FieldShapeProbeCollection>();
for (let i = 0; i < source.length; i++) {
const name = source[i];
if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) {
throw new UnknownProbeCollectionError(String(name));
}
unique.add(name);
}
return Array.from(unique).sort(compareAscii);
}
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
if (
reader === null ||
reader === undefined ||
typeof reader !== 'object' ||
typeof reader.isReadOnly !== 'function' ||
typeof reader.find !== 'function' ||
reader.isReadOnly() !== true
) {
throw new Error(
'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)'
);
}
}
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
);
}
function wrapCollectionReadError(collectionName: string, error: unknown): Error {
const detail = error instanceof Error ? error.message : String(error);
const message = detail.includes(collectionName)
? detail
: `Failed reading collection "${collectionName}": ${detail}`;
return new Error(message, { cause: error });
}
async function streamBoundedCollectionIntoAccumulator(
reader: ReadOnlySourceSymbolReader,
collectionName: FieldShapeProbeCollection,
limit: number,
findOptions: SourceSymbolFindOptions,
accumulator: FieldShapeAccumulator
): Promise<void> {
assertReadOnlyReader(reader);
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
null;
let primaryError: unknown = undefined;
let hasPrimaryError = false;
let isInvalidCursorError = false;
try {
const rawCursor = await reader.find<Record<string, unknown>>(collectionName, {}, findOptions);
if (
rawCursor !== null &&
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
) {
closableHandle = rawCursor as Pick<
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
'close'
>;
}
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(rawCursor)) {
isInvalidCursorError = true;
throw new TypeError(
`Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)`
);
}
let seen = 0;
if (limit > 0) {
for await (const doc of rawCursor) {
accumulator.addDocument(doc);
seen += 1;
if (seen >= limit) {
break;
}
}
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
if (closableHandle !== null && typeof closableHandle.close === 'function') {
try {
await closableHandle.close();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
}
if (hasPrimaryError) {
if (isInvalidCursorError) {
throw primaryError;
}
throw wrapCollectionReadError(collectionName, primaryError);
}
}
/**
* Bounded, read-only MongoDB field-shape probe over allowlisted source collections.
* Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })`
* with zero aggregations, `$sample`, writes, or index operations.
*/
export async function readFieldShapes(
reader: ReadOnlySourceSymbolReader,
options?: ReadFieldShapesOptions
): Promise<ReadFieldShapesResult> {
assertReadOnlyReader(reader);
if (options !== undefined && (options === null || typeof options !== 'object')) {
throw new TypeError('options must be an object');
}
const limit =
options?.limit !== undefined
? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT)
: DEFAULT_FIELD_SHAPE_LIMIT;
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
const batchSize =
options?.batchSize !== undefined
? validatePositiveSafeInt(options.batchSize, 'options.batchSize')
: undefined;
const collections = normalizeProbeCollections(options?.collections);
const findOptions: SourceSymbolFindOptions = {
limit,
promoteValues: false,
promoteLongs: false,
...(batchSize !== undefined ? { batchSize } : {}),
};
const results: CollectionFieldShapesProbeResult[] = [];
let totalDocsSampled = 0;
for (const collection of collections) {
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
await streamBoundedCollectionIntoAccumulator(
reader,
collection,
limit,
findOptions,
accumulator
);
const summary = accumulator.finalize();
totalDocsSampled += summary.docCount;
results.push({
collection,
docCount: summary.docCount,
fields: summary.fields,
});
}
return {
limit,
maxExamples,
maxExampleLength,
totalDocsSampled,
collections: results,
};
}
function formatHtmlCodeElement(value: string): string {
const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => {
switch (ch) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '|':
return '&#124;';
default:
return `&#${ch.charCodeAt(0)};`;
}
});
return `<code>${escaped}</code>`;
}
function formatMarkdownCodeCell(value: string): string {
const normalized = value.replace(/\r\n|\r|\n/g, ' ');
// Empty spans cannot be written with backtick fences; values containing `\|`
// would become `\\|` under pipe escaping, which GFM/micromark parses as an
// escaped backslash followed by a cell-splitting pipe. Use an HTML <code>
// element with entity-encoded pipes and Markdown metacharacters instead.
if (normalized.length === 0 || normalized.includes('\\|')) {
return formatHtmlCodeElement(normalized);
}
const tableSafe = normalized.replace(/\|/g, '\\|');
let maxBacktickRun = 0;
let currentRun = 0;
for (let i = 0; i < tableSafe.length; i++) {
if (tableSafe.charCodeAt(i) === 96) {
currentRun += 1;
if (currentRun > maxBacktickRun) {
maxBacktickRun = currentRun;
}
} else {
currentRun = 0;
}
}
const fence = '`'.repeat(maxBacktickRun + 1);
const startsWithBacktick = tableSafe.charCodeAt(0) === 96;
const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96;
const startsAndEndsWithSpace =
tableSafe.charCodeAt(0) === 32 &&
tableSafe.charCodeAt(tableSafe.length - 1) === 32 &&
tableSafe.trim().length > 0;
const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace;
return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`;
}
function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string {
const parts: string[] = [];
for (const typeName of FIELD_VALUE_TYPES) {
const count = typeCounts[typeName];
if (count > 0) {
parts.push(`${typeName}: ${count}`);
}
}
return parts.length > 0 ? parts.join(', ') : '—';
}
function formatStringStatsCell(stringStats: FieldStringStats | null): string {
if (stringStats === null) {
return '—';
}
const parts: string[] = [];
for (const pattern of STRING_PATTERN_CLASSES) {
const count = stringStats.patterns[pattern];
if (count > 0) {
parts.push(`${pattern}: ${count}`);
}
}
const patternText = parts.length > 0 ? parts.join(', ') : 'none';
return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`;
}
function formatExamplesCell(examples: readonly string[]): string {
if (examples.length === 0) {
return '—';
}
return examples.map(formatMarkdownCodeCell).join(', ');
}
/**
* Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or
* filesystem paths). Identical results always produce byte-identical Markdown.
*/
export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string {
const sortedCollections = [...result.collections].sort((a, b) =>
compareAscii(a.collection, b.collection)
);
const lines: string[] = [
'# Source Field Shapes Report',
'',
'- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)',
`- **Sample limit per collection:** ${result.limit}`,
`- **Collections probed:** ${sortedCollections.length}`,
`- **Total documents sampled:** ${result.totalDocsSampled}`,
];
for (const col of sortedCollections) {
lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, '');
if (col.docCount === 0) {
lines.push('_No documents sampled._');
continue;
}
const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field));
if (sortedFields.length === 0) {
lines.push('_No fields observed._');
continue;
}
lines.push('| Field | Presence | Types | String Patterns | Examples |');
lines.push('| --- | --- | --- | --- | --- |');
for (const field of sortedFields) {
const pct = ((field.presentCount / col.docCount) * 100).toFixed(1);
const fieldCell = formatMarkdownCodeCell(field.field);
const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`;
const typesCell = formatTypeCountsCell(field.typeCounts);
const patternsCell = formatStringStatsCell(field.stringStats);
const examplesCell = formatExamplesCell(field.examples);
lines.push(
`| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |`
);
}
}
return `${lines.join('\n')}\n`;
}