@lpdjs/firestore-repo-service 3.0.2 → 3.0.5
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/{create-servers-2Hw0pkyz.d.ts → create-servers-C-X5e62o.d.ts} +5 -5
- package/dist/{create-servers-ASLcxpiS.d.cts → create-servers-CRTjY8sA.d.cts} +5 -5
- package/dist/history/index.d.cts +3 -2
- package/dist/history/index.d.ts +3 -2
- package/dist/index.cjs +18 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -7
- package/dist/index.d.ts +10 -7
- package/dist/index.js +18 -18
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/{openapi-CoKsSOIU.d.cts → openapi-Bp4vtku3.d.cts} +1 -1
- package/dist/{openapi-BTu_1vSc.d.ts → openapi-D6hEI2lq.d.ts} +1 -1
- package/dist/{queue-B9jCT62h.d.cts → queue-BYbd9y4U.d.cts} +1 -1
- package/dist/{queue-BWi6TBmf.d.ts → queue-I7Y1l3Wu.d.ts} +1 -1
- package/dist/read-DWUsiHcw.d.cts +164 -0
- package/dist/read-_6UEFCDw.d.ts +164 -0
- package/dist/{rules-BJMT0N0i.d.ts → rules-6LZ9KkR6.d.ts} +1 -1
- package/dist/{rules-B3b-BZLf.d.cts → rules-BB0w7PlS.d.cts} +1 -1
- package/dist/servers/admin/index.d.cts +4 -2
- package/dist/servers/admin/index.d.ts +4 -2
- package/dist/servers/crud/index.d.cts +8 -6
- package/dist/servers/crud/index.d.ts +8 -6
- package/dist/servers/index.cjs +30 -30
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +10 -8
- package/dist/servers/index.d.ts +10 -8
- package/dist/servers/index.js +30 -30
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +4 -1
- package/dist/sync/bigquery.d.ts +4 -1
- package/dist/sync/index.cjs +55 -55
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +29 -13
- package/dist/sync/index.d.ts +29 -13
- 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 +33 -11
- package/dist/sync/meilisearch.d.ts +33 -11
- package/dist/sync/meilisearch.js +2 -2
- package/dist/sync/meilisearch.js.map +1 -1
- package/dist/{types-LZ8dyfBz.d.cts → types-B48PI0V9.d.cts} +29 -6
- package/dist/{read-CTWZjxyh.d.cts → types-BwucrwN0.d.cts} +2 -162
- package/dist/{read-CTWZjxyh.d.ts → types-BwucrwN0.d.ts} +2 -162
- package/dist/{types-XRjVKN9r.d.ts → types-CXQeSrhO.d.ts} +4 -206
- package/dist/{types-B2e-T8EM.d.cts → types-D9Nm-4pg.d.cts} +4 -206
- package/dist/types-D_snvgmB.d.cts +207 -0
- package/dist/{types-BRPhmKFW.d.ts → types-DbtP8YCJ.d.ts} +29 -6
- package/dist/types-DgtfcerG.d.ts +207 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var f=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});function l(i){let e={};for(let[t,n]of Object.entries(i)){let r=n;if(typeof r=="string"){let a=r.trim();if(a.startsWith("[")&&a.endsWith("]")||a.startsWith("{")&&a.endsWith("}"))try{r=JSON.parse(a);}catch{}}if(t.startsWith("__")||!t.includes("__")){e[t]=r;continue}let s=t.split("__").filter(Boolean),o=e;for(let a=0;a<s.length-1;a++){let c=s[a];(!o[c]||typeof o[c]!="object"||Array.isArray(o[c]))&&(o[c]={}),o=o[c];}o[s[s.length-1]]=r;}return e}function d(i){if(i.client)return i.client;if(!i.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=f("meilisearch");return new e({host:i.host,apiKey:i.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
|
|
2
2
|
bun add meilisearch # or npm install meilisearch
|
|
3
|
-
Original error: ${e?.message??String(e)}`)}}var
|
|
3
|
+
Original error: ${e?.message??String(e)}`)}}var u=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get client(){return this._client||(this._client=d(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,n){if(t.length===0)return;let r=this.options.unflatten!==false,s=t.map(a=>{let c=r?l(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(e).addDocuments(s,{primaryKey:n});}async delete(e,t,n){if(n.length===0)return;await this.client.index(e).deleteDocuments(n);}async ensureTarget(e){let{targetName:t,primaryKey:n}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:n});let s=this.options.indexesSettings?.[t];s&&await this.client.index(t).updateSettings(s);}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let r=this.client.index(t),s=await r.getStats(),o=typeof r.getRawInfo=="function"?await r.getRawInfo():{};return {healthy:!0,targetName:t,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:o?.primaryKey??e.primaryKey}}}catch(n){return {healthy:false,targetName:t,targetExists:false,error:n?.message??String(n)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let n=await this.client.isHealthy();e=n?.status==="available"||n===!0;}else if(typeof this.client.health=="function"){let n=await this.client.health();e=n?.status==="available"||n===!0;}let t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};exports.MeilisearchAdapter=u;//# sourceMappingURL=meilisearch.cjs.map
|
|
4
4
|
//# sourceMappingURL=meilisearch.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sync/adapters/meilisearch.ts"],"names":["loadMeilisearchClient","options","MeiliSearch","err","MeilisearchAdapter","targetName","items","primaryKey","_primaryKey","ids","settings","index","stats","rawInfo","isHealthy","res","version"],"mappings":"sQA2EA,SAASA,CAAAA,CAAsBC,EAAqD,CAClF,GAAIA,EAAQ,MAAA,CAAQ,OAAOA,EAAQ,MAAA,CACnC,GAAI,CAACA,CAAAA,CAAQ,IAAA,CACX,MAAM,IAAI,KAAA,CACR,4EACF,CAAA,CAEF,GAAI,CAEF,GAAM,CAAE,YAAAC,CAAY,CAAA,CAAI,EAAQ,aAAa,CAAA,CAC7C,OAAO,IAAIA,CAAAA,CAAY,CACrB,IAAA,CAAMD,CAAAA,CAAQ,KACd,MAAA,CAAQA,CAAAA,CAAQ,MAClB,CAAC,CACH,OAASE,CAAAA,CAAU,CACjB,MAAM,IAAI,KAAA,CACR,CAAA;AAAA;AAAA,gBAAA,EAEqBA,GAAK,OAAA,EAAW,MAAA,CAAOA,CAAG,CAAC,CAAA,CAClD,CACF,CACF,CAKO,IAAMC,CAAAA,CAAN,KAAgD,CAKrD,WAAA,CAAYH,EAAoC,CAJhD,IAAA,CAAS,KAAO,aAAA,CAChB,IAAA,CAAQ,OAAA,CAAkC,IAAA,CAIxC,KAAK,OAAA,CAAUA,CAAAA,CACXA,EAAQ,MAAA,GACV,IAAA,CAAK,QAAUA,CAAAA,CAAQ,MAAA,EAE3B,CAGA,IAAI,MAAA,EAA0B,CAC5B,OAAK,IAAA,CAAK,UACR,IAAA,CAAK,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AW,UAAA,CAAY,CACnD,IAAMA,CAAAA,CAAM,MAAM,KAAK,MAAA,CAAO,MAAA,EAAO,CACrCD,CAAAA,CAAYC,GAAK,MAAA,GAAW,WAAA,EAAeA,IAAQ,CAAA,EACrD,CACA,IAAIC,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,YAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,YAAW,GAC1B,UAAA,CAAA,CAER,CAAE,OAAA,CAASF,EAAW,OAAA,CAAAE,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,QAAS,KAAA,CAAO,KAAA,CAAO,GAAG,OAAA,EAAW,MAAA,CAAO,CAAC,CAAE,CAC1D,CACF,CACF","file":"meilisearch.cjs","sourcesContent":["/**\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 type { RepoSyncConfig, SyncAdapter, SyncHealthResult } 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 {\n filterableAttributes?: string[];\n sortableAttributes?: string[];\n searchableAttributes?: string[];\n rankingRules?: string[];\n stopWords?: string[];\n synonyms?: Record<string, string[]>;\n distinctAttribute?: string;\n [key: string]: any;\n}\n\nexport interface MeilisearchAdapterOptions {\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 */\n indexesSettings?: Record<string, MeilisearchIndexSettings>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions;\n\n constructor(options: MeilisearchAdapterOptions) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\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?.statusCode === 404 ||\n err?.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 index = this.client.index(targetName);\n await index.addDocuments(items, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const settings = this.options.indexesSettings?.[targetName];\n if (settings) {\n const index = this.client.index(targetName);\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sync/serializer.ts","../../src/sync/adapters/meilisearch.ts"],"names":["unflattenDocument","doc","result","key","rawValue","value","trimmed","parts","current","i","part","loadMeilisearchClient","options","MeiliSearch","err","MeilisearchAdapter","targetName","items","primaryKey","shouldUnflatten","docs","item","_primaryKey","ids","settings","index","stats","rawInfo","isHealthy","res","version"],"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,CAA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,OAAO,IAAA,CAAK,OAAO,SAAA,EAAc,UAAA,CAAY,CAC/C,IAAMC,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,GAC9BD,CAAAA,CAAYC,CAAAA,EAAK,SAAW,WAAA,EAAeA,CAAAA,GAAQ,GACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,MAAA,CAAO,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,GACrD,CACA,IAAIC,EACJ,OAAI,OAAO,KAAK,MAAA,CAAO,UAAA,EAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,OAAO,UAAA,EAAW,GAC1B,YAER,CAAE,OAAA,CAASF,EAAW,OAAA,CAAAE,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,KAAA,CAAO,KAAA,CAAO,CAAA,EAAG,OAAA,EAAW,OAAO,CAAC,CAAE,CAC1D,CACF,CACF","file":"meilisearch.cjs","sourcesContent":["import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(doc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n filterableAttributes?: (Fields | (string & {}))[];\n sortableAttributes?: (Fields | (string & {}))[];\n searchableAttributes?: (Fields | (string & {}))[];\n rankingRules?: string[];\n stopWords?: string[];\n synonyms?: Record<string, string[]>;\n distinctAttribute?: Fields | (string & {});\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const settings = this.options.indexesSettings?.[targetName];\n if (settings) {\n const index = this.client.index(targetName);\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n"]}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { a as SyncAdapter, R as RepoSyncConfig, d as SyncHealthResult } from '../types-
|
|
2
|
+
import { a as SyncAdapter, E as ExtractRepoFieldPaths, R as RepoSyncConfig, d as SyncHealthResult } from '../types-B48PI0V9.cjs';
|
|
3
3
|
import '../firebase-auth-Ds5P0kXT.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-D_snvgmB.cjs';
|
|
8
|
+
import '../types-BwucrwN0.cjs';
|
|
9
|
+
import 'firebase-admin/firestore';
|
|
7
10
|
|
|
8
11
|
/**
|
|
9
12
|
* Meilisearch adapter — streams Firestore changes to Meilisearch indexes.
|
|
@@ -48,17 +51,24 @@ interface MeilisearchLike {
|
|
|
48
51
|
health?(): Promise<any>;
|
|
49
52
|
getVersion?(): Promise<any>;
|
|
50
53
|
}
|
|
51
|
-
interface MeilisearchIndexSettings {
|
|
52
|
-
filterableAttributes?: string[];
|
|
53
|
-
sortableAttributes?: string[];
|
|
54
|
-
searchableAttributes?: string[];
|
|
54
|
+
interface MeilisearchIndexSettings<Fields extends string = string> {
|
|
55
|
+
filterableAttributes?: (Fields | (string & {}))[];
|
|
56
|
+
sortableAttributes?: (Fields | (string & {}))[];
|
|
57
|
+
searchableAttributes?: (Fields | (string & {}))[];
|
|
55
58
|
rankingRules?: string[];
|
|
56
59
|
stopWords?: string[];
|
|
57
60
|
synonyms?: Record<string, string[]>;
|
|
58
|
-
distinctAttribute?: string;
|
|
61
|
+
distinctAttribute?: Fields | (string & {});
|
|
59
62
|
[key: string]: any;
|
|
60
63
|
}
|
|
61
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Typed index settings map constrained to the repos in repository mapping `M`.
|
|
66
|
+
* Field attributes autocomplete and check dot-notation nested paths.
|
|
67
|
+
*/
|
|
68
|
+
type TypedMeilisearchIndexesSettings<M> = {
|
|
69
|
+
[K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;
|
|
70
|
+
};
|
|
71
|
+
interface MeilisearchAdapterOptions<M extends Record<string, any> = Record<string, any>> {
|
|
62
72
|
/**
|
|
63
73
|
* Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).
|
|
64
74
|
* Required if `client` is not provided.
|
|
@@ -74,17 +84,29 @@ interface MeilisearchAdapterOptions {
|
|
|
74
84
|
client?: MeilisearchLike | any;
|
|
75
85
|
/**
|
|
76
86
|
* Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).
|
|
87
|
+
* When typed with repository mapping `M`, keys are constrained to repo names and attributes
|
|
88
|
+
* are typed with dot-notation field paths.
|
|
89
|
+
*/
|
|
90
|
+
indexesSettings?: string extends keyof M ? Record<string, MeilisearchIndexSettings> : TypedMeilisearchIndexesSettings<M>;
|
|
91
|
+
/**
|
|
92
|
+
* Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)
|
|
93
|
+
* and parse stringified JSON arrays back into native arrays.
|
|
94
|
+
* Default: `true`.
|
|
95
|
+
*/
|
|
96
|
+
unflatten?: boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Optional custom document transformation before indexing in Meilisearch.
|
|
77
99
|
*/
|
|
78
|
-
|
|
100
|
+
transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;
|
|
79
101
|
}
|
|
80
102
|
/**
|
|
81
103
|
* SyncAdapter implementation for Meilisearch.
|
|
82
104
|
*/
|
|
83
|
-
declare class MeilisearchAdapter implements SyncAdapter {
|
|
105
|
+
declare class MeilisearchAdapter<M extends Record<string, any> = Record<string, any>> implements SyncAdapter {
|
|
84
106
|
readonly name = "meilisearch";
|
|
85
107
|
private _client;
|
|
86
108
|
private readonly options;
|
|
87
|
-
constructor(options: MeilisearchAdapterOptions);
|
|
109
|
+
constructor(options: MeilisearchAdapterOptions<M>);
|
|
88
110
|
/** Resolved Meilisearch client instance. */
|
|
89
111
|
get client(): MeilisearchLike;
|
|
90
112
|
targetExists(targetName: string): Promise<boolean>;
|
|
@@ -111,4 +133,4 @@ declare class MeilisearchAdapter implements SyncAdapter {
|
|
|
111
133
|
}>;
|
|
112
134
|
}
|
|
113
135
|
|
|
114
|
-
export { MeilisearchAdapter, type MeilisearchAdapterOptions, type MeilisearchIndexSettings, type MeilisearchLike };
|
|
136
|
+
export { MeilisearchAdapter, type MeilisearchAdapterOptions, type MeilisearchIndexSettings, type MeilisearchLike, type TypedMeilisearchIndexesSettings };
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { a as SyncAdapter, R as RepoSyncConfig, d as SyncHealthResult } from '../types-
|
|
2
|
+
import { a as SyncAdapter, E as ExtractRepoFieldPaths, R as RepoSyncConfig, d as SyncHealthResult } from '../types-DbtP8YCJ.js';
|
|
3
3
|
import '../firebase-auth-Ds5P0kXT.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-DgtfcerG.js';
|
|
8
|
+
import '../types-BwucrwN0.js';
|
|
9
|
+
import 'firebase-admin/firestore';
|
|
7
10
|
|
|
8
11
|
/**
|
|
9
12
|
* Meilisearch adapter — streams Firestore changes to Meilisearch indexes.
|
|
@@ -48,17 +51,24 @@ interface MeilisearchLike {
|
|
|
48
51
|
health?(): Promise<any>;
|
|
49
52
|
getVersion?(): Promise<any>;
|
|
50
53
|
}
|
|
51
|
-
interface MeilisearchIndexSettings {
|
|
52
|
-
filterableAttributes?: string[];
|
|
53
|
-
sortableAttributes?: string[];
|
|
54
|
-
searchableAttributes?: string[];
|
|
54
|
+
interface MeilisearchIndexSettings<Fields extends string = string> {
|
|
55
|
+
filterableAttributes?: (Fields | (string & {}))[];
|
|
56
|
+
sortableAttributes?: (Fields | (string & {}))[];
|
|
57
|
+
searchableAttributes?: (Fields | (string & {}))[];
|
|
55
58
|
rankingRules?: string[];
|
|
56
59
|
stopWords?: string[];
|
|
57
60
|
synonyms?: Record<string, string[]>;
|
|
58
|
-
distinctAttribute?: string;
|
|
61
|
+
distinctAttribute?: Fields | (string & {});
|
|
59
62
|
[key: string]: any;
|
|
60
63
|
}
|
|
61
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Typed index settings map constrained to the repos in repository mapping `M`.
|
|
66
|
+
* Field attributes autocomplete and check dot-notation nested paths.
|
|
67
|
+
*/
|
|
68
|
+
type TypedMeilisearchIndexesSettings<M> = {
|
|
69
|
+
[K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;
|
|
70
|
+
};
|
|
71
|
+
interface MeilisearchAdapterOptions<M extends Record<string, any> = Record<string, any>> {
|
|
62
72
|
/**
|
|
63
73
|
* Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).
|
|
64
74
|
* Required if `client` is not provided.
|
|
@@ -74,17 +84,29 @@ interface MeilisearchAdapterOptions {
|
|
|
74
84
|
client?: MeilisearchLike | any;
|
|
75
85
|
/**
|
|
76
86
|
* Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).
|
|
87
|
+
* When typed with repository mapping `M`, keys are constrained to repo names and attributes
|
|
88
|
+
* are typed with dot-notation field paths.
|
|
89
|
+
*/
|
|
90
|
+
indexesSettings?: string extends keyof M ? Record<string, MeilisearchIndexSettings> : TypedMeilisearchIndexesSettings<M>;
|
|
91
|
+
/**
|
|
92
|
+
* Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)
|
|
93
|
+
* and parse stringified JSON arrays back into native arrays.
|
|
94
|
+
* Default: `true`.
|
|
95
|
+
*/
|
|
96
|
+
unflatten?: boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Optional custom document transformation before indexing in Meilisearch.
|
|
77
99
|
*/
|
|
78
|
-
|
|
100
|
+
transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;
|
|
79
101
|
}
|
|
80
102
|
/**
|
|
81
103
|
* SyncAdapter implementation for Meilisearch.
|
|
82
104
|
*/
|
|
83
|
-
declare class MeilisearchAdapter implements SyncAdapter {
|
|
105
|
+
declare class MeilisearchAdapter<M extends Record<string, any> = Record<string, any>> implements SyncAdapter {
|
|
84
106
|
readonly name = "meilisearch";
|
|
85
107
|
private _client;
|
|
86
108
|
private readonly options;
|
|
87
|
-
constructor(options: MeilisearchAdapterOptions);
|
|
109
|
+
constructor(options: MeilisearchAdapterOptions<M>);
|
|
88
110
|
/** Resolved Meilisearch client instance. */
|
|
89
111
|
get client(): MeilisearchLike;
|
|
90
112
|
targetExists(targetName: string): Promise<boolean>;
|
|
@@ -111,4 +133,4 @@ declare class MeilisearchAdapter implements SyncAdapter {
|
|
|
111
133
|
}>;
|
|
112
134
|
}
|
|
113
135
|
|
|
114
|
-
export { MeilisearchAdapter, type MeilisearchAdapterOptions, type MeilisearchIndexSettings, type MeilisearchLike };
|
|
136
|
+
export { MeilisearchAdapter, type MeilisearchAdapterOptions, type MeilisearchIndexSettings, type MeilisearchLike, type TypedMeilisearchIndexesSettings };
|
package/dist/sync/meilisearch.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});function l(i){let e={};for(let[t,n]of Object.entries(i)){let r=n;if(typeof r=="string"){let a=r.trim();if(a.startsWith("[")&&a.endsWith("]")||a.startsWith("{")&&a.endsWith("}"))try{r=JSON.parse(a);}catch{}}if(t.startsWith("__")||!t.includes("__")){e[t]=r;continue}let s=t.split("__").filter(Boolean),o=e;for(let a=0;a<s.length-1;a++){let c=s[a];(!o[c]||typeof o[c]!="object"||Array.isArray(o[c]))&&(o[c]={}),o=o[c];}o[s[s.length-1]]=r;}return e}function d(i){if(i.client)return i.client;if(!i.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=f("meilisearch");return new e({host:i.host,apiKey:i.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
|
|
2
2
|
bun add meilisearch # or npm install meilisearch
|
|
3
|
-
Original error: ${e?.message??String(e)}`)}}var
|
|
3
|
+
Original error: ${e?.message??String(e)}`)}}var u=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get client(){return this._client||(this._client=d(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,n){if(t.length===0)return;let r=this.options.unflatten!==false,s=t.map(a=>{let c=r?l(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(e).addDocuments(s,{primaryKey:n});}async delete(e,t,n){if(n.length===0)return;await this.client.index(e).deleteDocuments(n);}async ensureTarget(e){let{targetName:t,primaryKey:n}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:n});let s=this.options.indexesSettings?.[t];s&&await this.client.index(t).updateSettings(s);}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let r=this.client.index(t),s=await r.getStats(),o=typeof r.getRawInfo=="function"?await r.getRawInfo():{};return {healthy:!0,targetName:t,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:o?.primaryKey??e.primaryKey}}}catch(n){return {healthy:false,targetName:t,targetExists:false,error:n?.message??String(n)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let n=await this.client.isHealthy();e=n?.status==="available"||n===!0;}else if(typeof this.client.health=="function"){let n=await this.client.health();e=n?.status==="available"||n===!0;}let t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};export{u as MeilisearchAdapter};//# sourceMappingURL=meilisearch.js.map
|
|
4
4
|
//# sourceMappingURL=meilisearch.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sync/adapters/meilisearch.ts"],"names":["loadMeilisearchClient","options","MeiliSearch","err","MeilisearchAdapter","targetName","items","primaryKey","_primaryKey","ids","settings","index","stats","rawInfo","isHealthy","res","version"],"mappings":"yPA2EA,SAASA,CAAAA,CAAsBC,EAAqD,CAClF,GAAIA,EAAQ,MAAA,CAAQ,OAAOA,EAAQ,MAAA,CACnC,GAAI,CAACA,CAAAA,CAAQ,IAAA,CACX,MAAM,IAAI,KAAA,CACR,4EACF,CAAA,CAEF,GAAI,CAEF,GAAM,CAAE,YAAAC,CAAY,CAAA,CAAI,EAAQ,aAAa,CAAA,CAC7C,OAAO,IAAIA,CAAAA,CAAY,CACrB,IAAA,CAAMD,CAAAA,CAAQ,KACd,MAAA,CAAQA,CAAAA,CAAQ,MAClB,CAAC,CACH,OAASE,CAAAA,CAAU,CACjB,MAAM,IAAI,KAAA,CACR,CAAA;AAAA;AAAA,gBAAA,EAEqBA,GAAK,OAAA,EAAW,MAAA,CAAOA,CAAG,CAAC,CAAA,CAClD,CACF,CACF,CAKO,IAAMC,CAAAA,CAAN,KAAgD,CAKrD,WAAA,CAAYH,EAAoC,CAJhD,IAAA,CAAS,KAAO,aAAA,CAChB,I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AAc,UAAA,CAAY,CAC/C,IAAMC,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,WAAU,CACxCD,CAAAA,CAAYC,GAAK,MAAA,GAAW,WAAA,EAAeA,IAAQ,CAAA,EACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,MAAA,CAAO,QAAW,UAAA,CAAY,CACnD,IAAMA,CAAAA,CAAM,MAAM,KAAK,MAAA,CAAO,MAAA,EAAO,CACrCD,CAAAA,CAAYC,GAAK,MAAA,GAAW,WAAA,EAAeA,IAAQ,CAAA,EACrD,CACA,IAAIC,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,YAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,YAAW,GAC1B,UAAA,CAAA,CAER,CAAE,OAAA,CAASF,EAAW,OAAA,CAAAE,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,QAAS,KAAA,CAAO,KAAA,CAAO,GAAG,OAAA,EAAW,MAAA,CAAO,CAAC,CAAE,CAC1D,CACF,CACF","file":"meilisearch.js","sourcesContent":["/**\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 type { RepoSyncConfig, SyncAdapter, SyncHealthResult } 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 {\n filterableAttributes?: string[];\n sortableAttributes?: string[];\n searchableAttributes?: string[];\n rankingRules?: string[];\n stopWords?: string[];\n synonyms?: Record<string, string[]>;\n distinctAttribute?: string;\n [key: string]: any;\n}\n\nexport interface MeilisearchAdapterOptions {\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 */\n indexesSettings?: Record<string, MeilisearchIndexSettings>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions;\n\n constructor(options: MeilisearchAdapterOptions) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\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?.statusCode === 404 ||\n err?.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 index = this.client.index(targetName);\n await index.addDocuments(items, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const settings = this.options.indexesSettings?.[targetName];\n if (settings) {\n const index = this.client.index(targetName);\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sync/serializer.ts","../../src/sync/adapters/meilisearch.ts"],"names":["unflattenDocument","doc","result","key","rawValue","value","trimmed","parts","current","i","part","loadMeilisearchClient","options","MeiliSearch","err","MeilisearchAdapter","targetName","items","primaryKey","shouldUnflatten","docs","item","_primaryKey","ids","settings","index","stats","rawInfo","isHealthy","res","version"],"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,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AA,CACT,UAAA,CAAAE,EACA,YAAA,CAAc,KAAA,CACd,KAAA,CAAOF,CAAAA,EAAK,OAAA,EAAW,MAAA,CAAOA,CAAG,CACnC,CACF,CACF,CAGA,MAAM,iBAIH,CACD,GAAI,CACF,IAAIc,CAAAA,CAAY,CAAA,CAAA,CAChB,GAAI,OAAO,IAAA,CAAK,OAAO,SAAA,EAAc,UAAA,CAAY,CAC/C,IAAMC,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,GAC9BD,CAAAA,CAAYC,CAAAA,EAAK,SAAW,WAAA,EAAeA,CAAAA,GAAQ,GACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,MAAA,CAAO,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,GACrD,CACA,IAAIC,EACJ,OAAI,OAAO,KAAK,MAAA,CAAO,UAAA,EAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,OAAO,UAAA,EAAW,GAC1B,YAER,CAAE,OAAA,CAASF,EAAW,OAAA,CAAAE,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,KAAA,CAAO,KAAA,CAAO,CAAA,EAAG,OAAA,EAAW,OAAO,CAAC,CAAE,CAC1D,CACF,CACF","file":"meilisearch.js","sourcesContent":["import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(doc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n filterableAttributes?: (Fields | (string & {}))[];\n sortableAttributes?: (Fields | (string & {}))[];\n searchableAttributes?: (Fields | (string & {}))[];\n rankingRules?: string[];\n stopWords?: string[];\n synonyms?: Record<string, string[]>;\n distinctAttribute?: Fields | (string & {});\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const settings = this.options.indexesSettings?.[targetName];\n if (settings) {\n const index = this.client.index(targetName);\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n"]}
|
|
@@ -3,6 +3,7 @@ import { onDocumentWritten } from 'firebase-functions/v2/firestore';
|
|
|
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-D_snvgmB.cjs';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Cloud Functions v2 options forwarded to `onMessagePublished()` for every
|
|
@@ -220,20 +221,42 @@ interface RepoSyncConfig<F extends string = string> {
|
|
|
220
221
|
* When omitted or empty, the repo is synced to all configured adapters.
|
|
221
222
|
*/
|
|
222
223
|
adapters?: string[];
|
|
224
|
+
/**
|
|
225
|
+
* Whether to flatten nested objects and stringify arrays into SQL-compatible columns.
|
|
226
|
+
* - `true` (default): Flattens `{ address: { city: "Paris" } }` into `address__city: "Paris"` and stringifies arrays.
|
|
227
|
+
* - `false`: Preserves nested objects and native arrays (ideal for Meilisearch / NoSQL search engines).
|
|
228
|
+
*/
|
|
229
|
+
flat?: boolean;
|
|
230
|
+
/**
|
|
231
|
+
* Optional custom document transformation function applied after serialization.
|
|
232
|
+
*/
|
|
233
|
+
transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;
|
|
223
234
|
}
|
|
235
|
+
|
|
224
236
|
/**
|
|
225
|
-
* Extract
|
|
237
|
+
* Extract the model type from a repo value.
|
|
226
238
|
* Works with ConfiguredRepository (_modelType), raw config (schema.shape), or fallback (type).
|
|
227
239
|
*/
|
|
228
|
-
type
|
|
240
|
+
type ExtractRepoModel<R> = R extends {
|
|
229
241
|
_modelType: infer Model;
|
|
230
|
-
} ?
|
|
242
|
+
} ? Model : R extends {
|
|
231
243
|
schema: {
|
|
232
244
|
shape: infer S;
|
|
233
245
|
};
|
|
234
|
-
} ?
|
|
246
|
+
} ? {
|
|
247
|
+
[K in keyof S]: z.infer<S[K]>;
|
|
248
|
+
} : R extends {
|
|
235
249
|
type: infer T;
|
|
236
|
-
} ?
|
|
250
|
+
} ? T : Record<string, unknown>;
|
|
251
|
+
/**
|
|
252
|
+
* Extract field names from a repo value.
|
|
253
|
+
* Works with ConfiguredRepository (_modelType), raw config (schema.shape), or fallback (type).
|
|
254
|
+
*/
|
|
255
|
+
type ExtractRepoFields<R> = string & keyof ExtractRepoModel<R>;
|
|
256
|
+
/**
|
|
257
|
+
* Extract all dot-notation field paths (including nested objects) from a repo value.
|
|
258
|
+
*/
|
|
259
|
+
type ExtractRepoFieldPaths<R> = FieldPath<ExtractRepoModel<R>>;
|
|
237
260
|
/** Keys of repos where `_isGroup` or `isGroup` is `true`. */
|
|
238
261
|
type GroupRepoKeys<M> = {
|
|
239
262
|
[K in string & keyof M]: M[K] extends {
|
|
@@ -430,4 +453,4 @@ interface FirestoreSyncConfig<M = Record<string, any>> {
|
|
|
430
453
|
repos?: TypedRepoSyncConfigs<M>;
|
|
431
454
|
}
|
|
432
455
|
|
|
433
|
-
export type { AdminHttpsOptions as A, FirestoreSyncConfig as F, GenerateDDLConfig as G, LogicalType as L, OrFactory as O, PubSubClientDep as P, RepoSyncConfig as R, SyncEvent as S, SyncAdapter as a, SqlAdapter as b, SqlDialect as c, SyncHealthResult as d, SqlTableDef as e, SqlColumn as f, adminsyncConfig as g, SyncTriggersConfig as h, SyncWorkerConfig as i, FirestoreTriggersDep as j, PubSubHandlerDep as k, SyncDeps as l, SyncOperation as m, SyncWorkerOptions as n, adminsyncBasicAuth as o, adminsyncFeaturesFlag as p };
|
|
456
|
+
export type { AdminHttpsOptions as A, ExtractRepoFieldPaths as E, FirestoreSyncConfig as F, GenerateDDLConfig as G, LogicalType as L, OrFactory as O, PubSubClientDep as P, RepoSyncConfig as R, SyncEvent as S, SyncAdapter as a, SqlAdapter as b, SqlDialect as c, SyncHealthResult as d, SqlTableDef as e, SqlColumn as f, adminsyncConfig as g, SyncTriggersConfig as h, SyncWorkerConfig as i, FirestoreTriggersDep as j, PubSubHandlerDep as k, SyncDeps as l, SyncOperation as m, SyncWorkerOptions as n, adminsyncBasicAuth as o, adminsyncFeaturesFlag as p, ExtractRepoModel as q };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Timestamp
|
|
1
|
+
import { Timestamp } from 'firebase-admin/firestore';
|
|
2
2
|
import { onDocumentWritten } from 'firebase-functions/v2/firestore';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -197,164 +197,4 @@ interface HistoryTriggersConfig<M = Record<string, any>> {
|
|
|
197
197
|
repos?: Partial<Record<keyof M & string, HistoryTriggerRepoOverride>>;
|
|
198
198
|
}
|
|
199
199
|
|
|
200
|
-
|
|
201
|
-
* `repo.history.*` read API.
|
|
202
|
-
*
|
|
203
|
-
* - `list(docId, opts)` → unified, paginated, normalised entries (v1 + v2).
|
|
204
|
-
* - `raw(docId, opts)` → raw Firestore docs (no normalisation).
|
|
205
|
-
* - `byField(docId, field, opts)` / `byOperation(docId, op, opts)` →
|
|
206
|
-
* convenience wrappers.
|
|
207
|
-
* - `recordManual(docId, payload)` → bypass the trigger and write a v2 entry
|
|
208
|
-
* synchronously (use sparingly; prefer trigger-based capture).
|
|
209
|
-
*/
|
|
210
|
-
|
|
211
|
-
/**
|
|
212
|
-
* Build the `repo.history` API for a given configured repository.
|
|
213
|
-
* Returns `null` when history is not enabled — the factory then skips
|
|
214
|
-
* exposing the namespace.
|
|
215
|
-
*/
|
|
216
|
-
declare function createHistoryMethods<T>(documentRef: (...args: any[]) => DocumentReference, systemKeys: string[], repoName: string, config: HistoryConfigForModel<T> & {
|
|
217
|
-
enabled: boolean;
|
|
218
|
-
}): HistoryMethods<T> | null;
|
|
219
|
-
/**
|
|
220
|
-
* Public, strongly-typed surface of the `repo.history` namespace.
|
|
221
|
-
*
|
|
222
|
-
* Exposed on a repository **only when** `history.enabled: true` is set in
|
|
223
|
-
* its config. Reads from the entity's `history` subcollection (or the custom
|
|
224
|
-
* name set via `history.subcollection`) and normalises both schema versions
|
|
225
|
-
* (v1 = one doc per modified field, v2 = one doc per write) into a single
|
|
226
|
-
* {@link HistoryEntry} shape.
|
|
227
|
-
*
|
|
228
|
-
* ### Path arguments
|
|
229
|
-
*
|
|
230
|
-
* Every method's leading positional arguments mirror
|
|
231
|
-
* `Parameters<repo.documentRef>`, so the call signature stays consistent with
|
|
232
|
-
* the rest of the repo API:
|
|
233
|
-
*
|
|
234
|
-
* - **Top-level collection** (`documentRef: (db, docId) => …`)
|
|
235
|
-
* → `repo.history.list("doc_42", opts?)`
|
|
236
|
-
* - **Subcollection** (`documentRef: (db, parentId, docId) => …`)
|
|
237
|
-
* → `repo.history.list("parent_1", "doc_42", opts?)`
|
|
238
|
-
*
|
|
239
|
-
* The trailing options/payload argument keeps the same position whatever the
|
|
240
|
-
* depth of the path.
|
|
241
|
-
*
|
|
242
|
-
* ### Pagination
|
|
243
|
-
*
|
|
244
|
-
* `list` / `byField` / `byOperation` use real Firestore cursors via the
|
|
245
|
-
* `cursor` + `limit` options on {@link HistoryListOptions} — no in-memory
|
|
246
|
-
* slicing, safe for large histories.
|
|
247
|
-
*
|
|
248
|
-
* @example Basic read
|
|
249
|
-
* ```ts
|
|
250
|
-
* const entries = await repos.residences.history!.list("residence_123", {
|
|
251
|
-
* limit: 50,
|
|
252
|
-
* direction: "desc",
|
|
253
|
-
* });
|
|
254
|
-
* for (const e of entries) {
|
|
255
|
-
* console.log(e.historySetAt.toDate(), e.operation, e.meta.userId);
|
|
256
|
-
* }
|
|
257
|
-
* ```
|
|
258
|
-
*
|
|
259
|
-
* @example Filter by field (autocompleted on `keyof T`)
|
|
260
|
-
* ```ts
|
|
261
|
-
* const addressChanges = await repos.residences.history!.byField(
|
|
262
|
-
* "residence_123",
|
|
263
|
-
* "address",
|
|
264
|
-
* );
|
|
265
|
-
* ```
|
|
266
|
-
*
|
|
267
|
-
* @template T - The repository's model type. Field-name parameters
|
|
268
|
-
* (e.g. `byField`'s `K`) and `HistoryEntry<T>` payloads
|
|
269
|
-
* are derived from this.
|
|
270
|
-
* @template PathArgs - Tuple of path-segment args inherited from the repo's
|
|
271
|
-
* `documentRef`. Defaults to `[string]` (a single
|
|
272
|
-
* `docId`) when used standalone.
|
|
273
|
-
*
|
|
274
|
-
* @see {@link createHistoryMethods} - factory used internally by `createRepository`.
|
|
275
|
-
* @see {@link HistoryEntry} - normalised return shape.
|
|
276
|
-
* @see {@link HistoryListOptions} - pagination + filter options.
|
|
277
|
-
*/
|
|
278
|
-
interface HistoryMethods<T, PathArgs extends readonly unknown[] = [string]> {
|
|
279
|
-
/**
|
|
280
|
-
* List normalised history entries for a single document.
|
|
281
|
-
*
|
|
282
|
-
* Reads both v1 and v2 docs and folds v1 field-per-doc entries that share
|
|
283
|
-
* the same author + timestamp (±5 ms) into a single logical entry, so the
|
|
284
|
-
* caller never has to care about the storage version.
|
|
285
|
-
*
|
|
286
|
-
* @param args - `[...pathArgs, options?]`. `pathArgs` mirror the repo's
|
|
287
|
-
* `documentRef`. `options` accepts `limit`, `cursor`,
|
|
288
|
-
* `direction`, `fields`, `operations`.
|
|
289
|
-
* @returns Array of {@link HistoryEntry} ordered by `historySetAt`
|
|
290
|
-
* (`direction` defaults to `"desc"`).
|
|
291
|
-
*/
|
|
292
|
-
list(...args: [...PathArgs, HistoryListOptions<T>?]): Promise<HistoryEntry<T>[]>;
|
|
293
|
-
/**
|
|
294
|
-
* Escape hatch returning **raw** Firestore documents (v1 or v2) without
|
|
295
|
-
* normalisation. Use only when {@link list} doesn't expose the field you
|
|
296
|
-
* need (custom legacy fields, debugging, migrations).
|
|
297
|
-
*
|
|
298
|
-
* @param args - `[...pathArgs, options?]`. Supports the same pagination
|
|
299
|
-
* options as `list`, minus model-aware filters.
|
|
300
|
-
*/
|
|
301
|
-
raw(...args: [...PathArgs, HistoryRawListOptions?]): Promise<Array<{
|
|
302
|
-
id: string;
|
|
303
|
-
data: V1HistoryDoc | V2HistoryDoc;
|
|
304
|
-
}>>;
|
|
305
|
-
/**
|
|
306
|
-
* Convenience wrapper around {@link list} that only returns entries
|
|
307
|
-
* touching a specific field. Field name is checked against `keyof T` at
|
|
308
|
-
* compile time.
|
|
309
|
-
*
|
|
310
|
-
* @typeParam K - A literal key of the model `T`.
|
|
311
|
-
* @param args - `[...pathArgs, field, options?]`.
|
|
312
|
-
*
|
|
313
|
-
* @example
|
|
314
|
-
* ```ts
|
|
315
|
-
* await repos.users.history!.byField("user_42", "email");
|
|
316
|
-
* ```
|
|
317
|
-
*/
|
|
318
|
-
byField<K extends keyof T & string>(...args: [...PathArgs, K, HistoryListOptions<T>?]): Promise<HistoryEntry<T>[]>;
|
|
319
|
-
/**
|
|
320
|
-
* Convenience wrapper around {@link list} filtering on the operation type.
|
|
321
|
-
*
|
|
322
|
-
* @param args - `[...pathArgs, operation, options?]` where `operation` is
|
|
323
|
-
* `"create" | "update" | "delete"`.
|
|
324
|
-
*
|
|
325
|
-
* @example
|
|
326
|
-
* ```ts
|
|
327
|
-
* await repos.residences.history!.byOperation("residence_123", "delete");
|
|
328
|
-
* ```
|
|
329
|
-
*/
|
|
330
|
-
byOperation(...args: [...PathArgs, HistoryOperation, HistoryListOptions<T>?]): Promise<HistoryEntry<T>[]>;
|
|
331
|
-
/**
|
|
332
|
-
* Synchronously append a custom history entry, bypassing the trigger.
|
|
333
|
-
*
|
|
334
|
-
* Useful when:
|
|
335
|
-
* - You already have richer business context than the trigger can extract
|
|
336
|
-
* (e.g. inside an HTTP handler that knows the authenticated user).
|
|
337
|
-
* - You want to record an event that isn't a Firestore write (e.g.
|
|
338
|
-
* `meta.reason = "exported-to-pdf"`).
|
|
339
|
-
*
|
|
340
|
-
* Honours the same `include` / `exclude` / meta auto-exclusion rules as
|
|
341
|
-
* the trigger. Returns `null` when the diff is empty (no changes recorded).
|
|
342
|
-
*
|
|
343
|
-
* > ⚠️ Use sparingly — combining manual records with the trigger can
|
|
344
|
-
* > produce duplicate entries if both fire for the same write.
|
|
345
|
-
*
|
|
346
|
-
* @param args - `[...pathArgs, payload]` where `payload` is
|
|
347
|
-
* `{ operation, before?, after?, meta? }`.
|
|
348
|
-
*/
|
|
349
|
-
recordManual(...args: [
|
|
350
|
-
...PathArgs,
|
|
351
|
-
{
|
|
352
|
-
operation: HistoryOperation;
|
|
353
|
-
before?: T | null;
|
|
354
|
-
after?: T | null;
|
|
355
|
-
meta?: HistoryMeta;
|
|
356
|
-
}
|
|
357
|
-
]): Promise<HistoryEntry<T> | null>;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
export { type HistoryTriggersConfig as H, type V2HistoryDoc as V, type HistoryOperation as a, type HistoryFieldChange as b, type HistoryMeta as c, type HistoryConfigForModel as d, type HistoryValueType as e, type V1HistoryDoc as f, type HistoryEntry as g, createHistoryMethods as h, type HistoryMethods as i, type HistoryConfigBase as j, type HistoryFirestoreTriggersDep as k, type HistoryListOptions as l, type HistoryRawListOptions as m, type HistoryTriggerRepoOverride as n };
|
|
200
|
+
export type { HistoryTriggersConfig as H, V1HistoryDoc as V, HistoryConfigForModel as a, HistoryListOptions as b, HistoryEntry as c, HistoryRawListOptions as d, V2HistoryDoc as e, HistoryOperation as f, HistoryMeta as g, HistoryFieldChange as h, HistoryValueType as i, HistoryConfigBase as j, HistoryFirestoreTriggersDep as k, HistoryTriggerRepoOverride as l };
|