@lpdjs/firestore-repo-service 3.0.13 → 3.0.15
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/actor-context-DQZgWqj3.d.cts +117 -0
- package/dist/actor-context-DQZgWqj3.d.ts +117 -0
- package/dist/{create-servers-LyRLAOh3.d.cts → create-servers-B5Z5v2SP.d.cts} +11 -5
- package/dist/{create-servers-Db1xUY2N.d.ts → create-servers-p1-jJNTG.d.ts} +11 -5
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +67 -7
- package/dist/history/index.d.ts +67 -7
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +81 -81
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -14
- package/dist/index.d.ts +20 -14
- package/dist/index.js +81 -81
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/{openapi-QVpqnnes.d.cts → openapi-B9utXiEH.d.cts} +1 -1
- package/dist/{openapi-CNIA7QRw.d.ts → openapi-Bsqq2zgh.d.ts} +1 -1
- package/dist/{queue-BEB-ujA3.d.ts → queue-NFod6hTT.d.ts} +1 -1
- package/dist/{queue-CpHe6M5j.d.cts → queue-zw2B7GPx.d.cts} +1 -1
- package/dist/{read-15-TcgCz.d.ts → read-BPov7lws.d.ts} +30 -7
- package/dist/{read-B15YaPyR.d.cts → read-Dfah1PPl.d.cts} +30 -7
- package/dist/{rules-Cafrkb9v.d.ts → rules-18wH7Uak.d.ts} +1 -1
- package/dist/{rules-Bu2NB7Eb.d.cts → rules-oSXoV4Js.d.cts} +1 -1
- package/dist/servers/admin/index.cjs +5 -5
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.d.cts +5 -4
- package/dist/servers/admin/index.d.ts +5 -4
- package/dist/servers/admin/index.js +5 -5
- package/dist/servers/admin/index.js.map +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +10 -9
- package/dist/servers/crud/index.d.ts +10 -9
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.cjs +14 -14
- package/dist/servers/hono/index.cjs.map +1 -1
- package/dist/servers/hono/index.d.cts +11 -3
- package/dist/servers/hono/index.d.ts +11 -3
- package/dist/servers/hono/index.js +14 -14
- package/dist/servers/hono/index.js.map +1 -1
- package/dist/servers/index.cjs +94 -94
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +13 -12
- package/dist/servers/index.d.ts +13 -12
- package/dist/servers/index.js +94 -94
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +2 -2
- package/dist/sync/bigquery.d.ts +2 -2
- package/dist/sync/index.cjs +55 -55
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +6 -6
- package/dist/sync/index.d.ts +6 -6
- package/dist/sync/index.js +55 -55
- 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 +2 -2
- package/dist/sync/meilisearch.d.ts +2 -2
- package/dist/sync/meilisearch.js +2 -2
- package/dist/sync/meilisearch.js.map +1 -1
- package/dist/{types-o-9qoExc.d.cts → types-BDTx8VPg.d.cts} +8 -0
- package/dist/{types-CNseHqF7.d.cts → types-BGh5_2fl.d.cts} +4 -4
- package/dist/{types-DGQURFSq.d.ts → types-B_FrzmO4.d.ts} +1 -1
- package/dist/{types-DmXW_fVz.d.ts → types-Cc6lelk1.d.ts} +4 -4
- package/dist/{types--RamYGF1.d.cts → types-D6zvWzRt.d.cts} +96 -2
- package/dist/{types--RamYGF1.d.ts → types-D6zvWzRt.d.ts} +96 -2
- package/dist/{types-VVuLlmfc.d.cts → types-D78FPJeF.d.cts} +1 -1
- package/dist/{types-B51LYvQZ.d.cts → types-Dc3lX99O.d.cts} +20 -19
- package/dist/{types-Ci0dGbuW.d.ts → types-DgFJLwAu.d.ts} +20 -19
- package/dist/{types-D3W_RaDA.d.ts → types-w1rEqs0Z.d.ts} +8 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var g=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e
|
|
1
|
+
'use strict';var g=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):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 t={};for(let[e,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(e.startsWith("__")||!e.includes("__")){t[e]=i;continue}let s=e.split("__").filter(Boolean),o=t;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 t}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:t}=g("meilisearch");return new t({host:r.host,apiKey:r.apiKey})}catch(t){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: ${t?.message??String(t)}`)}}function p(r,t){if(!r||!t)return false;for(let[e,n]of Object.entries(t)){if(n===void 0)continue;let i=r[e];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(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=h(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(e){if(e?.code==="index_not_found"||e?.cause?.code==="index_not_found"||e?.statusCode===404||e?.status===404||e?.response?.status===404||e?.cause?.status===404||e?.cause?.statusCode===404||e?.cause?.response?.status===404)return false;throw e}}async upsert(t,e,n){if(e.length===0)return;let i=this.options.unflatten!==false,s=e.map(a=>{let c=i?d(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:n});}async delete(t,e,n){if(n.length===0)return;await this.client.index(t).deleteDocuments(n);}async ensureTarget(t){let{targetName:e,primaryKey:n}=t;await this.targetExists(e)||await this.client.createIndex(e,{primaryKey:n});let s=this.options.indexesSettings?.[e];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(e);if(typeof u.getSettings=="function")try{let y=await u.getSettings();if(p(y,l))return}catch{}await u.updateSettings(l);}}async healthCheck(t){let{targetName:e}=t;try{if(!await this.targetExists(e))return {healthy:!1,targetName:e,targetExists:!1,error:`Meilisearch index "${e}" does not exist`};let i=this.client.index(e),s=await i.getStats(),o=typeof i.getRawInfo=="function"?await i.getRawInfo():{};return {healthy:!0,targetName:e,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:o?.primaryKey??t.primaryKey}}}catch(n){return {healthy:false,targetName:e,targetExists:false,error:n?.message??String(n)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let n=await this.client.isHealthy();t=n?.status==="available"||n===!0;}else if(typeof this.client.health=="function"){let n=await this.client.health();t=n?.status==="available"||n===!0;}let e;return typeof this.client.getVersion=="function"&&(e=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:e}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};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","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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} 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"]}
|
|
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","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,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,CAAAA,CAAQ,QAAA,CAAS,GAAG,EAEhD,GAAI,CACFD,EAAQ,I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M,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,MAASC,CAAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,MAAO,KAAA,CAAOA,CAAAA,EAAG,OAAA,EAAW,MAAA,CAAOA,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAASC,CAAAA,CAEd3B,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 // Drop excluded top-level keys before flattening so keys starting with\n // \"__\" (e.g. \"__audit\") are reliably excluded without splitting issues.\n let sourceDoc = doc;\n if (exclude.size > 0) {\n let dropped = false;\n const filtered: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(doc)) {\n if (exclude.has(k)) {\n dropped = true;\n continue;\n }\n filtered[k] = v;\n }\n if (dropped) sourceDoc = filtered;\n }\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(sourceDoc, \"\", 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"]}
|
|
@@ -4,8 +4,8 @@ import '../firebase-auth-nG3prKoj.cjs';
|
|
|
4
4
|
import 'firebase-functions/v2/firestore';
|
|
5
5
|
import 'firebase-functions/v2/https';
|
|
6
6
|
import 'firebase-functions/v2/pubsub';
|
|
7
|
-
import '../types-
|
|
8
|
-
import '../types
|
|
7
|
+
import '../types-Dc3lX99O.cjs';
|
|
8
|
+
import '../types-D6zvWzRt.cjs';
|
|
9
9
|
import 'firebase-admin/firestore';
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -4,8 +4,8 @@ import '../firebase-auth-nG3prKoj.js';
|
|
|
4
4
|
import 'firebase-functions/v2/firestore';
|
|
5
5
|
import 'firebase-functions/v2/https';
|
|
6
6
|
import 'firebase-functions/v2/pubsub';
|
|
7
|
-
import '../types-
|
|
8
|
-
import '../types
|
|
7
|
+
import '../types-DgFJLwAu.js';
|
|
8
|
+
import '../types-D6zvWzRt.js';
|
|
9
9
|
import 'firebase-admin/firestore';
|
|
10
10
|
|
|
11
11
|
/**
|
package/dist/sync/meilisearch.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var g=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e
|
|
1
|
+
var g=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):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 t={};for(let[e,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(e.startsWith("__")||!e.includes("__")){t[e]=i;continue}let s=e.split("__").filter(Boolean),o=t;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 t}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:t}=g("meilisearch");return new t({host:r.host,apiKey:r.apiKey})}catch(t){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: ${t?.message??String(t)}`)}}function p(r,t){if(!r||!t)return false;for(let[e,n]of Object.entries(t)){if(n===void 0)continue;let i=r[e];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(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=h(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(e){if(e?.code==="index_not_found"||e?.cause?.code==="index_not_found"||e?.statusCode===404||e?.status===404||e?.response?.status===404||e?.cause?.status===404||e?.cause?.statusCode===404||e?.cause?.response?.status===404)return false;throw e}}async upsert(t,e,n){if(e.length===0)return;let i=this.options.unflatten!==false,s=e.map(a=>{let c=i?d(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:n});}async delete(t,e,n){if(n.length===0)return;await this.client.index(t).deleteDocuments(n);}async ensureTarget(t){let{targetName:e,primaryKey:n}=t;await this.targetExists(e)||await this.client.createIndex(e,{primaryKey:n});let s=this.options.indexesSettings?.[e];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(e);if(typeof u.getSettings=="function")try{let y=await u.getSettings();if(p(y,l))return}catch{}await u.updateSettings(l);}}async healthCheck(t){let{targetName:e}=t;try{if(!await this.targetExists(e))return {healthy:!1,targetName:e,targetExists:!1,error:`Meilisearch index "${e}" does not exist`};let i=this.client.index(e),s=await i.getStats(),o=typeof i.getRawInfo=="function"?await i.getRawInfo():{};return {healthy:!0,targetName:e,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:o?.primaryKey??t.primaryKey}}}catch(n){return {healthy:false,targetName:e,targetExists:false,error:n?.message??String(n)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let n=await this.client.isHealthy();t=n?.status==="available"||n===!0;}else if(typeof this.client.health=="function"){let n=await this.client.health();t=n?.status==="available"||n===!0;}let e;return typeof this.client.getVersion=="function"&&(e=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:e}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};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","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,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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"]}
|
|
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","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,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CAAA,oBAAA,CAAA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,CAAOA,CAAAA,EAAG,OAAA,EAAW,MAAA,CAAOA,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAASC,CAAAA,CAEd3B,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 // Drop excluded top-level keys before flattening so keys starting with\n // \"__\" (e.g. \"__audit\") are reliably excluded without splitting issues.\n let sourceDoc = doc;\n if (exclude.size > 0) {\n let dropped = false;\n const filtered: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(doc)) {\n if (exclude.has(k)) {\n dropped = true;\n continue;\n }\n filtered[k] = v;\n }\n if (dropped) sourceDoc = filtered;\n }\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(sourceDoc, \"\", 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"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z, ZodError } from 'zod';
|
|
2
2
|
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
3
|
import { F as FirebaseAdminAuthLike, D as DecodedIdTokenLike } from './firebase-auth-nG3prKoj.cjs';
|
|
4
|
+
import { A as ActorResolverOption } from './actor-context-DQZgWqj3.cjs';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Global DI services container for the Hono server.
|
|
@@ -855,6 +856,13 @@ interface HonoServerOptions<TEnv extends Env = Env> {
|
|
|
855
856
|
* project — declare it once and pass it to {@link createApiRegistry}.
|
|
856
857
|
*/
|
|
857
858
|
services?: AnyServicesContainer;
|
|
859
|
+
/**
|
|
860
|
+
* Optional resolver (function or declarative field config) used to extract
|
|
861
|
+
* the authenticated actor from the Hono `Context` for automatic history
|
|
862
|
+
* shadow metadata injection. Defaults to {@link defaultActorResolver}
|
|
863
|
+
* (`c.get("user") ?? c.get("docsUser")`).
|
|
864
|
+
*/
|
|
865
|
+
actorResolver?: ActorResolverOption;
|
|
858
866
|
}
|
|
859
867
|
|
|
860
868
|
export { basicAuth as N, createRequestContextMiddleware as Q, createServices as T, defineRoutes as U, ValidationError as V, firebaseBearerAuth as W, firebaseDocsAuth as X, isDocsAuthExtension as Y, withRequestContext as Z };
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { b as AuthUser } from './firebase-auth-nG3prKoj.cjs';
|
|
2
|
-
import { H as HonoServerOptions, O as OpenAPIConfig } from './types-
|
|
2
|
+
import { H as HonoServerOptions, O as OpenAPIConfig } from './types-BDTx8VPg.cjs';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
5
|
-
import { H as HistoryMethods } from './read-
|
|
5
|
+
import { H as HistoryMethods } from './read-Dfah1PPl.cjs';
|
|
6
6
|
import { DocumentSnapshot, Query, CollectionReference, WriteBatch, Transaction, DocumentReference } from 'firebase-admin/firestore';
|
|
7
|
-
import { Q as QueryOptions, R as RepositoryConfig, G as GetOptions,
|
|
7
|
+
import { Q as QueryOptions, R as RepositoryConfig, G as GetOptions, g as GetResult, i as ExtractReturnDoc, a as RelationConfig, D as DeepPartial, b as DotNotationUpdate, F as FieldPath } from './types-Dc3lX99O.cjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Pagination result with data and cursor information
|
|
@@ -1020,7 +1020,7 @@ interface QueryRequestBody {
|
|
|
1020
1020
|
*/
|
|
1021
1021
|
select?: string[];
|
|
1022
1022
|
/**
|
|
1023
|
-
* Number of items per page (max
|
|
1023
|
+
* Number of items per page (min 1, max 1000).
|
|
1024
1024
|
* @default 25
|
|
1025
1025
|
*/
|
|
1026
1026
|
pageSize?: number;
|
|
@@ -3,7 +3,7 @@ import { onDocumentWritten, DocumentOptions } from 'firebase-functions/v2/firest
|
|
|
3
3
|
import { onRequest, HttpsOptions } from 'firebase-functions/v2/https';
|
|
4
4
|
import { onMessagePublished, PubSubOptions } from 'firebase-functions/v2/pubsub';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
import { F as FieldPath } from './types-
|
|
6
|
+
import { F as FieldPath } from './types-DgFJLwAu.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Cloud Functions v2 options forwarded to `onDocumentWritten()` for every
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { b as AuthUser } from './firebase-auth-nG3prKoj.js';
|
|
2
|
-
import { H as HonoServerOptions, O as OpenAPIConfig } from './types-
|
|
2
|
+
import { H as HonoServerOptions, O as OpenAPIConfig } from './types-w1rEqs0Z.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
5
|
-
import { H as HistoryMethods } from './read-
|
|
5
|
+
import { H as HistoryMethods } from './read-BPov7lws.js';
|
|
6
6
|
import { DocumentSnapshot, Query, CollectionReference, WriteBatch, Transaction, DocumentReference } from 'firebase-admin/firestore';
|
|
7
|
-
import { Q as QueryOptions, R as RepositoryConfig, G as GetOptions,
|
|
7
|
+
import { Q as QueryOptions, R as RepositoryConfig, G as GetOptions, g as GetResult, i as ExtractReturnDoc, a as RelationConfig, D as DeepPartial, b as DotNotationUpdate, F as FieldPath } from './types-DgFJLwAu.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Pagination result with data and cursor information
|
|
@@ -1020,7 +1020,7 @@ interface QueryRequestBody {
|
|
|
1020
1020
|
*/
|
|
1021
1021
|
select?: string[];
|
|
1022
1022
|
/**
|
|
1023
|
-
* Number of items per page (max
|
|
1023
|
+
* Number of items per page (min 1, max 1000).
|
|
1024
1024
|
* @default 25
|
|
1025
1025
|
*/
|
|
1026
1026
|
pageSize?: number;
|
|
@@ -16,7 +16,32 @@ import { DocumentOptions, onDocumentWritten } from 'firebase-functions/v2/firest
|
|
|
16
16
|
*/
|
|
17
17
|
type TriggerOptions = Omit<DocumentOptions, "document">;
|
|
18
18
|
type HistoryTriggerOptions = TriggerOptions;
|
|
19
|
-
type HistoryOperation = "create" | "update" | "delete";
|
|
19
|
+
type HistoryOperation = "create" | "update" | "delete" | "custom";
|
|
20
|
+
/**
|
|
21
|
+
* Structured payload attached to `operation: "custom"` history entries
|
|
22
|
+
* (business actions independent of model fields, e.g. manual invoice creation,
|
|
23
|
+
* PDF export, email sent, etc.).
|
|
24
|
+
*/
|
|
25
|
+
interface HistoryCustomData {
|
|
26
|
+
/** Human-readable title (e.g. `"Création de la facture"`). */
|
|
27
|
+
title: string;
|
|
28
|
+
/** Optional human-readable description (e.g. `"Facture #F-2026-042 créée manuellement"`). */
|
|
29
|
+
description?: string;
|
|
30
|
+
/** Optional business action key for filtering/grouping/icons (e.g. `"invoice_create_manually"`). */
|
|
31
|
+
key?: string;
|
|
32
|
+
/** Optional front-end visibility flag (default: `true`). */
|
|
33
|
+
display?: boolean;
|
|
34
|
+
/** Optional arbitrary structured business payload (e.g. `{ invoiceId, amount }`). */
|
|
35
|
+
data?: Record<string, unknown>;
|
|
36
|
+
}
|
|
37
|
+
/** Input payload accepted by `repo.history.recordCustom(...)`. */
|
|
38
|
+
interface HistoryCustomInput extends HistoryCustomData {
|
|
39
|
+
/**
|
|
40
|
+
* Optional metadata overrides (`reason`, `comment`, `extras`, `userId`,
|
|
41
|
+
* `userEmail`). Automatically merged on top of the active ALS actor.
|
|
42
|
+
*/
|
|
43
|
+
meta?: HistoryMeta;
|
|
44
|
+
}
|
|
20
45
|
/**
|
|
21
46
|
* Detected JS/Firestore type of a value as stored in a history entry.
|
|
22
47
|
* Matches the values returned by {@link valueType}.
|
|
@@ -57,6 +82,8 @@ interface HistoryEntry<T = Record<string, unknown>> {
|
|
|
57
82
|
operation: HistoryOperation;
|
|
58
83
|
/** Captured author / context information. */
|
|
59
84
|
meta: HistoryMeta;
|
|
85
|
+
/** Present on `operation: "custom"` entries (business actions independent of model fields). */
|
|
86
|
+
custom?: HistoryCustomData;
|
|
60
87
|
/** Per-field changes. Keys are field names of T. */
|
|
61
88
|
changes: {
|
|
62
89
|
[K in keyof T & string]?: HistoryFieldChange;
|
|
@@ -72,6 +99,8 @@ interface V2HistoryDoc {
|
|
|
72
99
|
historySetAt: Timestamp;
|
|
73
100
|
operation: HistoryOperation;
|
|
74
101
|
meta: HistoryMeta;
|
|
102
|
+
/** Present on `operation: "custom"` entries. */
|
|
103
|
+
custom?: HistoryCustomData;
|
|
75
104
|
changes: Record<string, HistoryFieldChange>;
|
|
76
105
|
/** Optional TTL marker (Firestore deletes the doc after this date). */
|
|
77
106
|
expiresAt?: Timestamp;
|
|
@@ -105,6 +134,49 @@ interface V1HistoryDoc {
|
|
|
105
134
|
extraContentKeys?: Record<string, unknown> | null;
|
|
106
135
|
objectType?: string;
|
|
107
136
|
}
|
|
137
|
+
/** Default top-level shadow field name stored on Firestore documents for auto-injected history metadata. */
|
|
138
|
+
declare const DEFAULT_HISTORY_SHADOW_KEY = "_historyMeta";
|
|
139
|
+
/**
|
|
140
|
+
* Customize (or disable via `false`) the sub-field names stored inside the
|
|
141
|
+
* shadow metadata object on Firestore documents.
|
|
142
|
+
*/
|
|
143
|
+
interface HistoryShadowFieldsConfig {
|
|
144
|
+
/** Key inside the shadow object for author userId, or `false` to omit. Default: `"userId"`. */
|
|
145
|
+
userId?: string | false;
|
|
146
|
+
/** Key inside the shadow object for author userEmail, or `false` to omit. Default: `"userEmail"`. */
|
|
147
|
+
userEmail?: string | false;
|
|
148
|
+
/** Key inside the shadow object for change reason, or `false` to omit. Default: `"reason"`. */
|
|
149
|
+
reason?: string | false;
|
|
150
|
+
/** Key inside the shadow object for change comment, or `false` to omit. Default: `"comment"`. */
|
|
151
|
+
comment?: string | false;
|
|
152
|
+
/** Key inside the shadow object for extras map, or `false` to omit. Default: `"extras"`. */
|
|
153
|
+
extras?: string | false;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Configuration for the internal shadow field used to transport actor metadata
|
|
157
|
+
* to Firestore `onDocumentWritten` triggers without modifying Zod schemas.
|
|
158
|
+
*/
|
|
159
|
+
interface HistoryShadowConfig {
|
|
160
|
+
/**
|
|
161
|
+
* Top-level field name stored on the Firestore document (not required in the
|
|
162
|
+
* Zod schema, automatically excluded from diffs and sync, and stripped on read).
|
|
163
|
+
* Default: `"_historyMeta"`.
|
|
164
|
+
*/
|
|
165
|
+
key?: string;
|
|
166
|
+
/**
|
|
167
|
+
* Customize or disable individual sub-field names inside the shadow object.
|
|
168
|
+
* Default: `{ userId: "userId", userEmail: "userEmail", reason: "reason", comment: "comment", extras: "extras" }`.
|
|
169
|
+
*/
|
|
170
|
+
fields?: HistoryShadowFieldsConfig;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Fallback author values written when no actor is active in `AsyncLocalStorage`
|
|
174
|
+
* (crons, scripts, admin UI, public routes).
|
|
175
|
+
*/
|
|
176
|
+
interface HistoryFallbackActor {
|
|
177
|
+
userId?: string | null;
|
|
178
|
+
userEmail?: string | null;
|
|
179
|
+
}
|
|
108
180
|
/**
|
|
109
181
|
* Per-repo history configuration. Attached on the repository config under
|
|
110
182
|
* the `history` key. All meta sub-keys must reference fields that exist on
|
|
@@ -115,6 +187,27 @@ interface HistoryConfigBase {
|
|
|
115
187
|
enabled: boolean;
|
|
116
188
|
/** Subcollection name used to store history docs. Default: "history". */
|
|
117
189
|
subcollection?: string;
|
|
190
|
+
/**
|
|
191
|
+
* Automatically inject actor metadata from `AsyncLocalStorage` into the
|
|
192
|
+
* shadow field on repository writes (`create`, `set`, `update`, `batch`,
|
|
193
|
+
* `transaction`, `bulk`). Default: `true` when `enabled: true`.
|
|
194
|
+
*/
|
|
195
|
+
autoInjectMeta?: boolean;
|
|
196
|
+
/**
|
|
197
|
+
* Shadow field configuration (zero Zod schema changes).
|
|
198
|
+
*
|
|
199
|
+
* - Omitted or `true` (when `meta` is absent): uses `"_historyMeta"` with default sub-fields.
|
|
200
|
+
* - `string`: shorthand for `{ key: "<customKey>" }`.
|
|
201
|
+
* - `HistoryShadowConfig`: customize both `key` and nested `fields`.
|
|
202
|
+
* - `false`: disable shadow metadata injection/reading.
|
|
203
|
+
*/
|
|
204
|
+
shadow?: boolean | string | HistoryShadowConfig;
|
|
205
|
+
/**
|
|
206
|
+
* Fallback actor written when no actor is active in `AsyncLocalStorage` so
|
|
207
|
+
* previous author metadata never leaks onto subsequent writes.
|
|
208
|
+
* Default: `{ userId: null, userEmail: null }`.
|
|
209
|
+
*/
|
|
210
|
+
fallbackActor?: HistoryFallbackActor;
|
|
118
211
|
/**
|
|
119
212
|
* Optional Firestore TTL configuration. When set, every written history doc
|
|
120
213
|
* gets an `expiresAt` Timestamp at `now + days`. You still need to enable
|
|
@@ -219,4 +312,5 @@ interface HistoryTriggersConfig<M = Record<string, any>> {
|
|
|
219
312
|
repos?: Partial<Record<keyof M & string, HistoryTriggerRepoOverride>>;
|
|
220
313
|
}
|
|
221
314
|
|
|
222
|
-
export
|
|
315
|
+
export { DEFAULT_HISTORY_SHADOW_KEY as D };
|
|
316
|
+
export type { HistoryTriggersConfig as H, TriggerOptions as T, V1HistoryDoc as V, HistoryListOptions as a, HistoryEntry as b, HistoryRawListOptions as c, V2HistoryDoc as d, HistoryOperation as e, HistoryMeta as f, HistoryCustomData as g, HistoryCustomInput as h, HistoryConfigForModel as i, HistoryFieldChange as j, HistoryValueType as k, HistoryConfigBase as l, HistoryFallbackActor as m, HistoryFirestoreTriggersDep as n, HistoryShadowConfig as o, HistoryShadowFieldsConfig as p, HistoryTriggerOptions as q, HistoryTriggerRepoOverride as r };
|