import type { DescribeFieldInfo, DetailedField, FlatIndexSchema, IndexDescription, Language, QueryOptions, QueryResult, } from "./types"; import { FIELD_TYPES, type FieldType, type NestedIndexSchema } from "./types"; import { setOwnProperty } from "../../util"; type FlattenedField = { path: string; type: FieldType; fast?: boolean; noTokenize?: boolean; noStem?: boolean; from?: string; }; function isFieldType(value: any): value is FieldType { return typeof value === "string" && (FIELD_TYPES as readonly string[]).includes(value); } function isDetailedField(value: any): value is DetailedField { return typeof value === "object" && value !== null && "type" in value && isFieldType(value.type); } function isNestedSchema(value: any): value is NestedIndexSchema { return typeof value === "object" && value !== null && !isDetailedField(value); } export function flattenSchema( schema: NestedIndexSchema | FlatIndexSchema, pathPrefix: string[] = [] ): FlattenedField[] { const fields: FlattenedField[] = []; for (const [key, value] of Object.entries(schema)) { const currentPath = [...pathPrefix, key]; const pathString = currentPath.join("."); if (isFieldType(value)) { fields.push({ path: pathString, type: value, }); } else if (isDetailedField(value)) { fields.push({ path: pathString, type: value.type as FieldType, fast: "fast" in value ? value.fast : undefined, noTokenize: "noTokenize" in value ? value.noTokenize : undefined, noStem: "noStem" in value ? value.noStem : undefined, from: "from" in value ? value.from : undefined, }); } else if (isNestedSchema(value)) { const nestedFields = flattenSchema(value, currentPath); fields.push(...nestedFields); } } return fields; } function hasFieldAbove(pathParts: string[], names: Set): boolean { for (let length = 1; length < pathParts.length; length++) { if (names.has(pathParts.slice(0, length).join("."))) { return true; } } return false; } function isDocument(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } export function deserializeQueryResponse< TSchema extends NestedIndexSchema | FlatIndexSchema = any, TOptions extends QueryOptions | undefined = any, >(rawResponse: unknown[]): QueryResult[] { return rawResponse.map((itemRaw) => { const raw = itemRaw as [string, string, unknown[]?]; const key = raw[0]; const score = Number(raw[1]); const rawFields = raw[2]; if (rawFields === undefined) { return { key, score } as QueryResult; } if (!Array.isArray(rawFields) || rawFields.length === 0) { return { key, score, data: {} } as QueryResult; } const fields = rawFields as [string, unknown][]; // The whole document of a string or JSON key arrives as a single "$" field. // A field which is only named "$", or starts with "$.", is a regular field. if (fields.length === 1 && fields[0][0] === "$" && isDocument(fields[0][1])) { return { key, score, data: fields[0][1] } as QueryResult; } // Merge all field objects into a single object const data: Record = {}; const names = new Set(fields.map((field) => field[0])); for (const fieldRaw of fields) { const key = fieldRaw[0]; const value = fieldRaw[1]; const pathParts = key.split("."); // A name like "a.b" is the path to a nested field, unless "a" is a // field of its own. Then it is kept as it is, so that it can't replace // "a" or change what is inside it. if (hasFieldAbove(pathParts, names)) { setOwnProperty(data, key, value); continue; } let currentObj = data; for (const pathPart of pathParts.slice(0, -1)) { const existing = Object.prototype.hasOwnProperty.call(currentObj, pathPart) ? currentObj[pathPart] : undefined; if (typeof existing === "object" && existing !== null) { currentObj = existing as Record; } else { const nested: Record = {}; setOwnProperty(currentObj, pathPart, nested); currentObj = nested; } } setOwnProperty(currentObj, pathParts.at(-1)!, value); } return { key, score, data } as QueryResult; }); } export function deserializeDescribeResponse( rawResponse: unknown[] ): IndexDescription { const description = {} as IndexDescription; for (let i = 0; i < rawResponse.length; i += 2) { const descriptor = rawResponse[i] as string; switch (descriptor) { case "name": { description["name"] = rawResponse[i + 1] as string; break; } case "type": { description["dataType"] = ( rawResponse[i + 1] as string ).toLowerCase() as IndexDescription["dataType"]; break; } case "prefixes": { description["prefixes"] = rawResponse[i + 1] as string[]; break; } case "language": { description["language"] = rawResponse[i + 1] as Language; break; } case "schema": { const schema: Record = {}; for (const fieldDescription of rawResponse[i + 1] as string[][]) { const fieldName = fieldDescription[0]; const fieldInfo: DescribeFieldInfo = { type: fieldDescription[1] as FieldType }; if (fieldDescription.length > 2) { for (let j = 2; j < fieldDescription.length; j++) { const fieldOption = fieldDescription[j]; switch (fieldOption) { case "NOSTEM": { fieldInfo.noStem = true; break; } case "NOTOKENIZE": { fieldInfo.noTokenize = true; break; } case "FAST": { fieldInfo.fast = true; break; } case "FROM": { fieldInfo.from = fieldDescription[++j]; break; } } } } setOwnProperty(schema, fieldName, fieldInfo); } description["schema"] = schema; break; } } } return description; } export function parseCountResponse(rawResponse: any): number { return typeof rawResponse === "number" ? rawResponse : Number.parseInt(rawResponse, 10); } export function deserializeAggregateResponse(rawResponse: any[]): any { // Response is a flat key-value array: [key, val, key, val, ...] return parseAggregationArray(rawResponse); } function parseAggregationArray(arr: any[]): any { const result: any = {}; for (let i = 0; i < arr.length; i += 2) { const key = arr[i]; const value = arr[i + 1]; if (Array.isArray(value)) { // Check if it's a stats-like array or buckets array if (value.length > 0 && typeof value[0] === "string") { // Stats or buckets format setOwnProperty( result, key, value[0] === "buckets" ? parseBucketsValue(value) : parseStatsValue(value) ); } else { // Nested aggregation setOwnProperty(result, key, parseAggregationArray(value)); } } else { setOwnProperty(result, key, value); } } return result; } function coerceNumericString(value: any): any { if (typeof value === "string" && value !== "" && !Number.isNaN(Number(value))) { return Number(value); } return value; } function parseStatsValue(arr: any[]): any { const result: any = {}; for (let i = 0; i < arr.length; i += 2) { const key = arr[i]; const value = arr[i + 1]; if (Array.isArray(value) && value.length > 0) { // Check if it's a single array following key-value format if (typeof value[0] === "string") { setOwnProperty(result, key, parseStatsValue(value)); } // Check if it's an array of arrays (like percentiles unkeyed format) else if (Array.isArray(value[0]) && typeof value[0][0] === "string") { setOwnProperty( result, key, value.map((item: any[]) => parseStatsValue(item)) ); } // Otherwise keep as-is else { setOwnProperty(result, key, value); } } else { setOwnProperty(result, key, coerceNumericString(value)); } } return result; } function parseBucketsValue(arr: any[]): any { // Format: ["buckets", [bucket1_array, bucket2_array, ...], extraKey, extraVal, ...] if (arr[0] === "buckets" && Array.isArray(arr[1])) { const result: any = { buckets: arr[1].map((bucket: any[]) => { const bucketObj: any = {}; for (let i = 0; i < bucket.length; i += 2) { const key = bucket[i]; const value = bucket[i + 1]; setOwnProperty( bucketObj, key, Array.isArray(value) && value.length > 0 && typeof value[0] === "string" ? parseStatsValue(value) : value ); } return bucketObj; }), }; // Parse remaining key-value pairs (e.g. sumOtherDocCount, docCountErrorUpperBound) for (let i = 2; i < arr.length; i += 2) { setOwnProperty(result, arr[i], arr[i + 1]); } return result; } return arr; }