@lpdjs/firestore-repo-service 3.0.8 → 3.0.9
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/dist/index.cjs +45 -45
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +45 -45
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/servers/index.cjs +17 -17
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.js +17 -17
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/index.cjs +28 -28
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +28 -28
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.cjs +2 -2
- package/dist/sync/meilisearch.cjs.map +1 -1
- package/dist/sync/meilisearch.d.cts +70 -2
- package/dist/sync/meilisearch.d.ts +70 -2
- package/dist/sync/meilisearch.js +2 -2
- package/dist/sync/meilisearch.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var g=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function d(r){let e={};for(let[t,n]of Object.entries(r)){let i=n;if(typeof i=="string"){let a=i.trim();if(a.startsWith("[")&&a.endsWith("]")||a.startsWith("{")&&a.endsWith("}"))try{i=JSON.parse(a);}catch{}}if(t.startsWith("__")||!t.includes("__")){e[t]=i;continue}let s=t.split("__").filter(Boolean),o=e;for(let a=0;a<s.length-1;a++){let c=s[a];(!o[c]||typeof o[c]!="object"||Array.isArray(o[c]))&&(o[c]={}),o=o[c];}o[s[s.length-1]]=i;}return e}function h(r){if(r.client)return r.client;if(!r.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=g("meilisearch");return new e({host:r.host,apiKey:r.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
|
|
2
2
|
bun add meilisearch # or npm install meilisearch
|
|
3
|
-
Original error: ${
|
|
3
|
+
Original error: ${e?.message??String(e)}`)}}function p(r,e){if(!r||!e)return false;for(let[t,n]of Object.entries(e)){if(n===void 0)continue;let i=r[t];if(Array.isArray(n)){if(!Array.isArray(i)||n.length!==i.length)return false;for(let s=0;s<n.length;s++)if(n[s]!==i[s])return false}else if(typeof n=="object"&&n!==null){if(JSON.stringify(n)!==JSON.stringify(i))return false}else if(n!==i)return false}return true}var f=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=h(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,n){if(t.length===0)return;let i=this.options.unflatten!==false,s=t.map(a=>{let c=i?d(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(e).addDocuments(s,{primaryKey:n});}async delete(e,t,n){if(n.length===0)return;await this.client.index(e).deleteDocuments(n);}async ensureTarget(e){let{targetName:t,primaryKey:n}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:n});let s=this.options.indexesSettings?.[t];if(s){let{retrievableAttributes:o,attributesToRetrieve:a,...c}=s,l={...c,displayedAttributes:c.displayedAttributes??o??a};l.displayedAttributes===void 0&&delete l.displayedAttributes;let u=this.client.index(t);if(typeof u.getSettings=="function")try{let y=await u.getSettings();if(p(y,l))return}catch{}await u.updateSettings(l);}}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let i=this.client.index(t),s=await i.getStats(),o=typeof i.getRawInfo=="function"?await i.getRawInfo():{};return {healthy:!0,targetName:t,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:o?.primaryKey??e.primaryKey}}}catch(n){return {healthy:false,targetName:t,targetExists:false,error:n?.message??String(n)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let n=await this.client.isHealthy();e=n?.status==="available"||n===!0;}else if(typeof this.client.health=="function"){let n=await this.client.health();e=n?.status==="available"||n===!0;}let t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};function w(r){return ()=>new f(r)}exports.MeilisearchAdapter=f;exports.defineMeilisearchAdapter=w;//# sourceMappingURL=meilisearch.cjs.map
|
|
4
4
|
//# sourceMappingURL=meilisearch.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sync/serializer.ts","../../src/sync/adapters/meilisearch.ts"],"names":["unflattenDocument","doc","result","key","rawValue","value","trimmed","parts","current","i","part","loadMeilisearchClient","options","MeiliSearch","err","MeilisearchAdapter","targetName","items","primaryKey","shouldUnflatten","docs","item","_primaryKey","ids","settings","index","stats","rawInfo","isHealthy","res","version","e","defineMeilisearchAdapter"],"mappings":"aAyMO,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,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GAAS,UAAA,EAAcf,CAAAA,CAAQ,UAC7C,CACF,CACF,CAAA,MAASE,EAAU,CACjB,OAAO,CACL,OAAA,CAAS,KAAA,CACT,UAAA,CAAAE,EACA,YAAA,CAAc,KAAA,CACd,MAAOF,CAAAA,EAAK,OAAA,EAAW,OAAOA,CAAG,CACnC,CACF,CACF,CAGA,MAAM,iBAIH,CACD,GAAI,CACF,IAAIc,CAAAA,CAAY,CAAA,CAAA,CAChB,GAAI,OAAO,IAAA,CAAK,MAAA,CAAO,SAAA,EAAc,UAAA,CAAY,CAC/C,IAAMC,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,EAAU,CACxCD,EAAYC,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,MAAA,CAAO,MAAA,EAAW,UAAA,CAAY,CACnD,IAAMA,EAAM,MAAM,IAAA,CAAK,MAAA,CAAO,MAAA,EAAO,CACrCD,CAAAA,CAAYC,GAAK,MAAA,GAAW,WAAA,EAAeA,IAAQ,CAAA,EACrD,CACA,IAAIC,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,EAAe,aAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW,GAC1B,YAER,CAAE,OAAA,CAASF,CAAAA,CAAW,OAAA,CAAAE,CAAQ,CACvC,OAASC,CAAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,KAAA,CAAO,MAAOA,CAAAA,EAAG,OAAA,EAAW,MAAA,CAAOA,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAASC,CAAAA,CAEdpB,CAAAA,CAAoE,CACpE,OAAO,IAAM,IAAIG,CAAAA,CAAsBH,CAAO,CAChD","file":"meilisearch.cjs","sourcesContent":["import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(doc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n filterableAttributes?: Fields[];\n sortableAttributes?: Fields[];\n searchableAttributes?: Fields[];\n rankingRules?: string[];\n stopWords?: string[];\n synonyms?: Record<string, string[]>;\n distinctAttribute?: Fields;\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Configured index settings */\n get indexesSettings(): MeilisearchAdapterOptions<M>[\"indexesSettings\"] {\n return this.options.indexesSettings;\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const settings = this.options.indexesSettings?.[targetName];\n if (settings) {\n const index = this.client.index(targetName);\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n\n/**\n * Type-safe factory helper for creating a Meilisearch adapter bound to a repository mapping `M`.\n * Provides full autocompletion and strict type checking on repository names and nested field paths.\n *\n * @example\n * ```ts\n * const adapter = defineMeilisearchAdapter<typeof repos>({\n * client: createMeilisearchClient(),\n * indexesSettings: {\n * adminUsers: {\n * searchableAttributes: [\"docId\", \"baseUser.email\"],\n * },\n * },\n * });\n * ```\n */\nexport function defineMeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n>(options: MeilisearchAdapterOptions<M>): () => MeilisearchAdapter<M> {\n return () => new MeilisearchAdapter<M>(options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sync/serializer.ts","../../src/sync/adapters/meilisearch.ts"],"names":["unflattenDocument","doc","result","key","rawValue","value","trimmed","parts","current","i","part","loadMeilisearchClient","options","MeiliSearch","err","areMeiliSettingsEqual","desired","curVal","MeilisearchAdapter","targetName","items","primaryKey","shouldUnflatten","docs","item","_primaryKey","ids","rawSettings","retrievableAttributes","attributesToRetrieve","rest","settings","index","stats","rawInfo","isHealthy","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KAAA,GAAW,OAAO,IAAA,CAAK,OAAO,MAAA,EAAW,UAAA,CAAY,CACnD,IAAMA,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAAO,CACrCD,CAAAA,CAAYC,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CACA,IAAIC,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,EAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW,GAC1B,UAAA,CAAA,CAER,CAAE,OAAA,CAASF,CAAAA,CAAW,QAAAE,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,MAAO,KAAA,CAAO,CAAA,EAAG,OAAA,EAAW,MAAA,CAAO,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAASC,CAAAA,CAEd1B,CAAAA,CAAoE,CACpE,OAAO,IAAM,IAAIM,CAAAA,CAAsBN,CAAO,CAChD","file":"meilisearch.cjs","sourcesContent":["import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(doc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n /**\n * Fields displayed in the returned documents. Defaults to `[\"*\"]`.\n */\n displayedAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes` (Algolia-style naming).\n */\n retrievableAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes`.\n */\n attributesToRetrieve?: (Fields | \"*\")[];\n /**\n * Fields that are searched for query words. Defaults to `[\"*\"]`.\n */\n searchableAttributes?: (Fields | \"*\")[];\n /**\n * Fields that can be filtered using the `filter` search parameter.\n */\n filterableAttributes?: Fields[];\n /**\n * Fields that can be sorted using the `sort` search parameter.\n */\n sortableAttributes?: Fields[];\n /**\n * Custom ranking rules for search result scoring.\n */\n rankingRules?: string[];\n /**\n * List of words ignored during search queries.\n */\n stopWords?: string[];\n /**\n * Custom synonyms map.\n */\n synonyms?: Record<string, string[]>;\n /**\n * Field used to deduplicate search results.\n */\n distinctAttribute?: Fields | null;\n /**\n * Typo tolerance settings.\n */\n typoTolerance?: Record<string, any>;\n /**\n * Faceting settings.\n */\n faceting?: Record<string, any>;\n /**\n * Pagination limits (e.g. `maxTotalHits`).\n */\n pagination?: { maxTotalHits?: number; [key: string]: any };\n /**\n * Custom separator tokens.\n */\n separatorTokens?: string[];\n /**\n * Custom non-separator tokens.\n */\n nonSeparatorTokens?: string[];\n /**\n * Custom dictionary words.\n */\n dictionary?: string[];\n /**\n * Proximity precision mode (\"byWord\" or \"byAttribute\").\n */\n proximityPrecision?: \"byWord\" | \"byAttribute\";\n /**\n * Maximum search duration before timeout in ms.\n */\n searchCutoffMs?: number;\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\nfunction areMeiliSettingsEqual(current: any, desired: any): boolean {\n if (!current || !desired) return false;\n for (const [key, value] of Object.entries(desired)) {\n if (value === undefined) continue;\n const curVal = current[key];\n if (Array.isArray(value)) {\n if (!Array.isArray(curVal)) return false;\n if (value.length !== curVal.length) return false;\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== curVal[i]) return false;\n }\n } else if (typeof value === \"object\" && value !== null) {\n if (JSON.stringify(value) !== JSON.stringify(curVal)) return false;\n } else {\n if (value !== curVal) return false;\n }\n }\n return true;\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Configured index settings */\n get indexesSettings(): MeilisearchAdapterOptions<M>[\"indexesSettings\"] {\n return this.options.indexesSettings;\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const rawSettings = this.options.indexesSettings?.[targetName];\n if (rawSettings) {\n const { retrievableAttributes, attributesToRetrieve, ...rest } = rawSettings;\n const settings = {\n ...rest,\n displayedAttributes:\n rest.displayedAttributes ?? retrievableAttributes ?? attributesToRetrieve,\n };\n if (settings.displayedAttributes === undefined) {\n delete (settings as any).displayedAttributes;\n }\n\n const index = this.client.index(targetName);\n if (typeof index.getSettings === \"function\") {\n try {\n const current = await index.getSettings();\n if (areMeiliSettingsEqual(current, settings)) {\n return;\n }\n } catch {\n // If reading current settings fails, fallback to updating\n }\n }\n\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n\n/**\n * Type-safe factory helper for creating a Meilisearch adapter bound to a repository mapping `M`.\n * Provides full autocompletion and strict type checking on repository names and nested field paths.\n *\n * @example\n * ```ts\n * const adapter = defineMeilisearchAdapter<typeof repos>({\n * client: createMeilisearchClient(),\n * indexesSettings: {\n * adminUsers: {\n * searchableAttributes: [\"docId\", \"baseUser.email\"],\n * },\n * },\n * });\n * ```\n */\nexport function defineMeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n>(options: MeilisearchAdapterOptions<M>): () => MeilisearchAdapter<M> {\n return () => new MeilisearchAdapter<M>(options);\n}\n"]}
|
|
@@ -52,13 +52,81 @@ interface MeilisearchLike {
|
|
|
52
52
|
getVersion?(): Promise<any>;
|
|
53
53
|
}
|
|
54
54
|
interface MeilisearchIndexSettings<Fields extends string = string> {
|
|
55
|
+
/**
|
|
56
|
+
* Fields displayed in the returned documents. Defaults to `["*"]`.
|
|
57
|
+
*/
|
|
58
|
+
displayedAttributes?: (Fields | "*")[];
|
|
59
|
+
/**
|
|
60
|
+
* Alias for `displayedAttributes` (Algolia-style naming).
|
|
61
|
+
*/
|
|
62
|
+
retrievableAttributes?: (Fields | "*")[];
|
|
63
|
+
/**
|
|
64
|
+
* Alias for `displayedAttributes`.
|
|
65
|
+
*/
|
|
66
|
+
attributesToRetrieve?: (Fields | "*")[];
|
|
67
|
+
/**
|
|
68
|
+
* Fields that are searched for query words. Defaults to `["*"]`.
|
|
69
|
+
*/
|
|
70
|
+
searchableAttributes?: (Fields | "*")[];
|
|
71
|
+
/**
|
|
72
|
+
* Fields that can be filtered using the `filter` search parameter.
|
|
73
|
+
*/
|
|
55
74
|
filterableAttributes?: Fields[];
|
|
75
|
+
/**
|
|
76
|
+
* Fields that can be sorted using the `sort` search parameter.
|
|
77
|
+
*/
|
|
56
78
|
sortableAttributes?: Fields[];
|
|
57
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Custom ranking rules for search result scoring.
|
|
81
|
+
*/
|
|
58
82
|
rankingRules?: string[];
|
|
83
|
+
/**
|
|
84
|
+
* List of words ignored during search queries.
|
|
85
|
+
*/
|
|
59
86
|
stopWords?: string[];
|
|
87
|
+
/**
|
|
88
|
+
* Custom synonyms map.
|
|
89
|
+
*/
|
|
60
90
|
synonyms?: Record<string, string[]>;
|
|
61
|
-
|
|
91
|
+
/**
|
|
92
|
+
* Field used to deduplicate search results.
|
|
93
|
+
*/
|
|
94
|
+
distinctAttribute?: Fields | null;
|
|
95
|
+
/**
|
|
96
|
+
* Typo tolerance settings.
|
|
97
|
+
*/
|
|
98
|
+
typoTolerance?: Record<string, any>;
|
|
99
|
+
/**
|
|
100
|
+
* Faceting settings.
|
|
101
|
+
*/
|
|
102
|
+
faceting?: Record<string, any>;
|
|
103
|
+
/**
|
|
104
|
+
* Pagination limits (e.g. `maxTotalHits`).
|
|
105
|
+
*/
|
|
106
|
+
pagination?: {
|
|
107
|
+
maxTotalHits?: number;
|
|
108
|
+
[key: string]: any;
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Custom separator tokens.
|
|
112
|
+
*/
|
|
113
|
+
separatorTokens?: string[];
|
|
114
|
+
/**
|
|
115
|
+
* Custom non-separator tokens.
|
|
116
|
+
*/
|
|
117
|
+
nonSeparatorTokens?: string[];
|
|
118
|
+
/**
|
|
119
|
+
* Custom dictionary words.
|
|
120
|
+
*/
|
|
121
|
+
dictionary?: string[];
|
|
122
|
+
/**
|
|
123
|
+
* Proximity precision mode ("byWord" or "byAttribute").
|
|
124
|
+
*/
|
|
125
|
+
proximityPrecision?: "byWord" | "byAttribute";
|
|
126
|
+
/**
|
|
127
|
+
* Maximum search duration before timeout in ms.
|
|
128
|
+
*/
|
|
129
|
+
searchCutoffMs?: number;
|
|
62
130
|
[key: string]: any;
|
|
63
131
|
}
|
|
64
132
|
/**
|
|
@@ -52,13 +52,81 @@ interface MeilisearchLike {
|
|
|
52
52
|
getVersion?(): Promise<any>;
|
|
53
53
|
}
|
|
54
54
|
interface MeilisearchIndexSettings<Fields extends string = string> {
|
|
55
|
+
/**
|
|
56
|
+
* Fields displayed in the returned documents. Defaults to `["*"]`.
|
|
57
|
+
*/
|
|
58
|
+
displayedAttributes?: (Fields | "*")[];
|
|
59
|
+
/**
|
|
60
|
+
* Alias for `displayedAttributes` (Algolia-style naming).
|
|
61
|
+
*/
|
|
62
|
+
retrievableAttributes?: (Fields | "*")[];
|
|
63
|
+
/**
|
|
64
|
+
* Alias for `displayedAttributes`.
|
|
65
|
+
*/
|
|
66
|
+
attributesToRetrieve?: (Fields | "*")[];
|
|
67
|
+
/**
|
|
68
|
+
* Fields that are searched for query words. Defaults to `["*"]`.
|
|
69
|
+
*/
|
|
70
|
+
searchableAttributes?: (Fields | "*")[];
|
|
71
|
+
/**
|
|
72
|
+
* Fields that can be filtered using the `filter` search parameter.
|
|
73
|
+
*/
|
|
55
74
|
filterableAttributes?: Fields[];
|
|
75
|
+
/**
|
|
76
|
+
* Fields that can be sorted using the `sort` search parameter.
|
|
77
|
+
*/
|
|
56
78
|
sortableAttributes?: Fields[];
|
|
57
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Custom ranking rules for search result scoring.
|
|
81
|
+
*/
|
|
58
82
|
rankingRules?: string[];
|
|
83
|
+
/**
|
|
84
|
+
* List of words ignored during search queries.
|
|
85
|
+
*/
|
|
59
86
|
stopWords?: string[];
|
|
87
|
+
/**
|
|
88
|
+
* Custom synonyms map.
|
|
89
|
+
*/
|
|
60
90
|
synonyms?: Record<string, string[]>;
|
|
61
|
-
|
|
91
|
+
/**
|
|
92
|
+
* Field used to deduplicate search results.
|
|
93
|
+
*/
|
|
94
|
+
distinctAttribute?: Fields | null;
|
|
95
|
+
/**
|
|
96
|
+
* Typo tolerance settings.
|
|
97
|
+
*/
|
|
98
|
+
typoTolerance?: Record<string, any>;
|
|
99
|
+
/**
|
|
100
|
+
* Faceting settings.
|
|
101
|
+
*/
|
|
102
|
+
faceting?: Record<string, any>;
|
|
103
|
+
/**
|
|
104
|
+
* Pagination limits (e.g. `maxTotalHits`).
|
|
105
|
+
*/
|
|
106
|
+
pagination?: {
|
|
107
|
+
maxTotalHits?: number;
|
|
108
|
+
[key: string]: any;
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Custom separator tokens.
|
|
112
|
+
*/
|
|
113
|
+
separatorTokens?: string[];
|
|
114
|
+
/**
|
|
115
|
+
* Custom non-separator tokens.
|
|
116
|
+
*/
|
|
117
|
+
nonSeparatorTokens?: string[];
|
|
118
|
+
/**
|
|
119
|
+
* Custom dictionary words.
|
|
120
|
+
*/
|
|
121
|
+
dictionary?: string[];
|
|
122
|
+
/**
|
|
123
|
+
* Proximity precision mode ("byWord" or "byAttribute").
|
|
124
|
+
*/
|
|
125
|
+
proximityPrecision?: "byWord" | "byAttribute";
|
|
126
|
+
/**
|
|
127
|
+
* Maximum search duration before timeout in ms.
|
|
128
|
+
*/
|
|
129
|
+
searchCutoffMs?: number;
|
|
62
130
|
[key: string]: any;
|
|
63
131
|
}
|
|
64
132
|
/**
|
package/dist/sync/meilisearch.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function d(r){let e={};for(let[t,n]of Object.entries(r)){let i=n;if(typeof i=="string"){let a=i.trim();if(a.startsWith("[")&&a.endsWith("]")||a.startsWith("{")&&a.endsWith("}"))try{i=JSON.parse(a);}catch{}}if(t.startsWith("__")||!t.includes("__")){e[t]=i;continue}let s=t.split("__").filter(Boolean),o=e;for(let a=0;a<s.length-1;a++){let c=s[a];(!o[c]||typeof o[c]!="object"||Array.isArray(o[c]))&&(o[c]={}),o=o[c];}o[s[s.length-1]]=i;}return e}function h(r){if(r.client)return r.client;if(!r.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=g("meilisearch");return new e({host:r.host,apiKey:r.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
|
|
2
2
|
bun add meilisearch # or npm install meilisearch
|
|
3
|
-
Original error: ${
|
|
3
|
+
Original error: ${e?.message??String(e)}`)}}function p(r,e){if(!r||!e)return false;for(let[t,n]of Object.entries(e)){if(n===void 0)continue;let i=r[t];if(Array.isArray(n)){if(!Array.isArray(i)||n.length!==i.length)return false;for(let s=0;s<n.length;s++)if(n[s]!==i[s])return false}else if(typeof n=="object"&&n!==null){if(JSON.stringify(n)!==JSON.stringify(i))return false}else if(n!==i)return false}return true}var f=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=h(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,n){if(t.length===0)return;let i=this.options.unflatten!==false,s=t.map(a=>{let c=i?d(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(e).addDocuments(s,{primaryKey:n});}async delete(e,t,n){if(n.length===0)return;await this.client.index(e).deleteDocuments(n);}async ensureTarget(e){let{targetName:t,primaryKey:n}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:n});let s=this.options.indexesSettings?.[t];if(s){let{retrievableAttributes:o,attributesToRetrieve:a,...c}=s,l={...c,displayedAttributes:c.displayedAttributes??o??a};l.displayedAttributes===void 0&&delete l.displayedAttributes;let u=this.client.index(t);if(typeof u.getSettings=="function")try{let y=await u.getSettings();if(p(y,l))return}catch{}await u.updateSettings(l);}}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let i=this.client.index(t),s=await i.getStats(),o=typeof i.getRawInfo=="function"?await i.getRawInfo():{};return {healthy:!0,targetName:t,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:o?.primaryKey??e.primaryKey}}}catch(n){return {healthy:false,targetName:t,targetExists:false,error:n?.message??String(n)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let n=await this.client.isHealthy();e=n?.status==="available"||n===!0;}else if(typeof this.client.health=="function"){let n=await this.client.health();e=n?.status==="available"||n===!0;}let t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};function w(r){return ()=>new f(r)}export{f as MeilisearchAdapter,w as defineMeilisearchAdapter};//# sourceMappingURL=meilisearch.js.map
|
|
4
4
|
//# sourceMappingURL=meilisearch.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sync/serializer.ts","../../src/sync/adapters/meilisearch.ts"],"names":["unflattenDocument","doc","result","key","rawValue","value","trimmed","parts","current","i","part","loadMeilisearchClient","options","MeiliSearch","err","MeilisearchAdapter","targetName","items","primaryKey","shouldUnflatten","docs","item","_primaryKey","ids","settings","index","stats","rawInfo","isHealthy","res","version","e","defineMeilisearchAdapter"],"mappings":"AAy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CAAAE,CAAQ,CACvC,OAASC,CAAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,KAAA,CAAO,MAAOA,CAAAA,EAAG,OAAA,EAAW,MAAA,CAAOA,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAASC,CAAAA,CAEdpB,CAAAA,CAAoE,CACpE,OAAO,IAAM,IAAIG,CAAAA,CAAsBH,CAAO,CAChD","file":"meilisearch.js","sourcesContent":["import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(doc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n filterableAttributes?: Fields[];\n sortableAttributes?: Fields[];\n searchableAttributes?: Fields[];\n rankingRules?: string[];\n stopWords?: string[];\n synonyms?: Record<string, string[]>;\n distinctAttribute?: Fields;\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Configured index settings */\n get indexesSettings(): MeilisearchAdapterOptions<M>[\"indexesSettings\"] {\n return this.options.indexesSettings;\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const settings = this.options.indexesSettings?.[targetName];\n if (settings) {\n const index = this.client.index(targetName);\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n\n/**\n * Type-safe factory helper for creating a Meilisearch adapter bound to a repository mapping `M`.\n * Provides full autocompletion and strict type checking on repository names and nested field paths.\n *\n * @example\n * ```ts\n * const adapter = defineMeilisearchAdapter<typeof repos>({\n * client: createMeilisearchClient(),\n * indexesSettings: {\n * adminUsers: {\n * searchableAttributes: [\"docId\", \"baseUser.email\"],\n * },\n * },\n * });\n * ```\n */\nexport function defineMeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n>(options: MeilisearchAdapterOptions<M>): () => MeilisearchAdapter<M> {\n return () => new MeilisearchAdapter<M>(options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sync/serializer.ts","../../src/sync/adapters/meilisearch.ts"],"names":["unflattenDocument","doc","result","key","rawValue","value","trimmed","parts","current","i","part","loadMeilisearchClient","options","MeiliSearch","err","areMeiliSettingsEqual","desired","curVal","MeilisearchAdapter","targetName","items","primaryKey","shouldUnflatten","docs","item","_primaryKey","ids","rawSettings","retrievableAttributes","attributesToRetrieve","rest","settings","index","stats","rawInfo","isHealthy","res","version","defineMeilisearchAdapter"],"mappings":"AAyMO,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CAAA,oBAAA,CAAA,CAAA,CAAA,CAAA,SAASA,EACdC,CAAAA,CACyB,CACzB,IAAMC,CAAAA,CAAkC,GAExC,IAAA,GAAW,CAACC,EAAKC,CAAQ,CAAA,GAAK,OAAO,OAAA,CAAQH,CAAG,EAAG,CACjD,IAAII,EAAQD,CAAAA,CAGZ,GAAI,OAAOC,CAAAA,EAAU,SAAU,CAC7B,IAAMC,EAAUD,CAAAA,CAAM,IAAA,GACtB,GACGC,CAAAA,CAAQ,WAAW,GAAG,CAAA,EAAKA,EAAQ,QAAA,CAAS,GAAG,GAC/CA,CAAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,EAAKA,C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A,EAAK,OAAA,EAAW,OAAOA,CAAG,CACnC,CACF,CACF,CAGA,MAAM,eAAA,EAIH,CACD,GAAI,CACF,IAAIqB,CAAAA,CAAY,CAAA,CAAA,CAChB,GAAI,OAAO,IAAA,CAAK,MAAA,CAAO,WAAc,UAAA,CAAY,CAC/C,IAAMC,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,EAAU,CACxCD,EAAYC,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,OAAO,MAAA,EAAW,UAAA,CAAY,CACnD,IAAMA,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAAO,CACrCD,CAAAA,CAAYC,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CACA,IAAIC,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,EAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW,GAC1B,UAAA,CAAA,CAER,CAAE,OAAA,CAASF,CAAAA,CAAW,QAAAE,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,MAAO,KAAA,CAAO,CAAA,EAAG,OAAA,EAAW,MAAA,CAAO,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAASC,CAAAA,CAEd1B,CAAAA,CAAoE,CACpE,OAAO,IAAM,IAAIM,CAAAA,CAAsBN,CAAO,CAChD","file":"meilisearch.js","sourcesContent":["import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(doc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n /**\n * Fields displayed in the returned documents. Defaults to `[\"*\"]`.\n */\n displayedAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes` (Algolia-style naming).\n */\n retrievableAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes`.\n */\n attributesToRetrieve?: (Fields | \"*\")[];\n /**\n * Fields that are searched for query words. Defaults to `[\"*\"]`.\n */\n searchableAttributes?: (Fields | \"*\")[];\n /**\n * Fields that can be filtered using the `filter` search parameter.\n */\n filterableAttributes?: Fields[];\n /**\n * Fields that can be sorted using the `sort` search parameter.\n */\n sortableAttributes?: Fields[];\n /**\n * Custom ranking rules for search result scoring.\n */\n rankingRules?: string[];\n /**\n * List of words ignored during search queries.\n */\n stopWords?: string[];\n /**\n * Custom synonyms map.\n */\n synonyms?: Record<string, string[]>;\n /**\n * Field used to deduplicate search results.\n */\n distinctAttribute?: Fields | null;\n /**\n * Typo tolerance settings.\n */\n typoTolerance?: Record<string, any>;\n /**\n * Faceting settings.\n */\n faceting?: Record<string, any>;\n /**\n * Pagination limits (e.g. `maxTotalHits`).\n */\n pagination?: { maxTotalHits?: number; [key: string]: any };\n /**\n * Custom separator tokens.\n */\n separatorTokens?: string[];\n /**\n * Custom non-separator tokens.\n */\n nonSeparatorTokens?: string[];\n /**\n * Custom dictionary words.\n */\n dictionary?: string[];\n /**\n * Proximity precision mode (\"byWord\" or \"byAttribute\").\n */\n proximityPrecision?: \"byWord\" | \"byAttribute\";\n /**\n * Maximum search duration before timeout in ms.\n */\n searchCutoffMs?: number;\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\nfunction areMeiliSettingsEqual(current: any, desired: any): boolean {\n if (!current || !desired) return false;\n for (const [key, value] of Object.entries(desired)) {\n if (value === undefined) continue;\n const curVal = current[key];\n if (Array.isArray(value)) {\n if (!Array.isArray(curVal)) return false;\n if (value.length !== curVal.length) return false;\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== curVal[i]) return false;\n }\n } else if (typeof value === \"object\" && value !== null) {\n if (JSON.stringify(value) !== JSON.stringify(curVal)) return false;\n } else {\n if (value !== curVal) return false;\n }\n }\n return true;\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Configured index settings */\n get indexesSettings(): MeilisearchAdapterOptions<M>[\"indexesSettings\"] {\n return this.options.indexesSettings;\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const rawSettings = this.options.indexesSettings?.[targetName];\n if (rawSettings) {\n const { retrievableAttributes, attributesToRetrieve, ...rest } = rawSettings;\n const settings = {\n ...rest,\n displayedAttributes:\n rest.displayedAttributes ?? retrievableAttributes ?? attributesToRetrieve,\n };\n if (settings.displayedAttributes === undefined) {\n delete (settings as any).displayedAttributes;\n }\n\n const index = this.client.index(targetName);\n if (typeof index.getSettings === \"function\") {\n try {\n const current = await index.getSettings();\n if (areMeiliSettingsEqual(current, settings)) {\n return;\n }\n } catch {\n // If reading current settings fails, fallback to updating\n }\n }\n\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n\n/**\n * Type-safe factory helper for creating a Meilisearch adapter bound to a repository mapping `M`.\n * Provides full autocompletion and strict type checking on repository names and nested field paths.\n *\n * @example\n * ```ts\n * const adapter = defineMeilisearchAdapter<typeof repos>({\n * client: createMeilisearchClient(),\n * indexesSettings: {\n * adminUsers: {\n * searchableAttributes: [\"docId\", \"baseUser.email\"],\n * },\n * },\n * });\n * ```\n */\nexport function defineMeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n>(options: MeilisearchAdapterOptions<M>): () => MeilisearchAdapter<M> {\n return () => new MeilisearchAdapter<M>(options);\n}\n"]}
|