import type { SearchIndexSchema } from "./schemas/index.js"; /** * Whitelist-projects a document so only fields explicitly allowed by the * schema reach Meilisearch. Drops every other key — including potentially * sensitive ones the producer forgot to strip. The result always carries * the primary key and `tenantId`; missing values fail loudly. */ export function sanitizeDocument>( schema: SearchIndexSchema, raw: TDocument ): Record & { id: string | number; tenantId: string } { const allowed = new Set(schema.allowedDocumentFields); const out: Record = {}; for (const key of Object.keys(raw)) { if (allowed.has(key)) { out[key] = raw[key]; } } const id = out[schema.primaryKey]; if (id === undefined || id === null) { throw new Error(`Document for index "${schema.name}" is missing primary key "${schema.primaryKey}".`); } if (typeof id !== "string" && typeof id !== "number") { throw new Error(`Document primary key "${schema.primaryKey}" must be string or number.`); } const tenantId = out.tenantId; if (typeof tenantId !== "string" || tenantId.length === 0) { throw new Error(`Document for index "${schema.name}" is missing required tenantId.`); } return { ...out, id: id as string | number, tenantId }; }