@lpdjs/firestore-repo-service 2.6.57 → 3.0.1

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.
Files changed (64) hide show
  1. package/README.md +45 -27
  2. package/dist/{create-servers-BxkVVkg9.d.cts → create-servers-Cbvzs_ou.d.cts} +5 -5
  3. package/dist/{create-servers-B84cbslf.d.ts → create-servers-aWdDTcSu.d.ts} +5 -5
  4. package/dist/{firebase-auth-DZ8lb2Ec.d.cts → firebase-auth-Ds5P0kXT.d.cts} +1 -1
  5. package/dist/{firebase-auth-DZ8lb2Ec.d.ts → firebase-auth-Ds5P0kXT.d.ts} +1 -1
  6. package/dist/index.cjs +97 -85
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +9 -9
  9. package/dist/index.d.ts +9 -9
  10. package/dist/index.js +97 -85
  11. package/dist/index.js.map +1 -1
  12. package/dist/llms-full.txt +237 -263
  13. package/dist/llms.txt +5 -4
  14. package/dist/{openapi-BpbfjSHK.d.ts → openapi-BTu_1vSc.d.ts} +1 -1
  15. package/dist/{openapi-DG7aQUlX.d.cts → openapi-CoKsSOIU.d.cts} +1 -1
  16. package/dist/{queue-B4uwef6c.d.ts → queue-BQxyuEXb.d.ts} +8 -23
  17. package/dist/{queue-CQyWCQBk.d.cts → queue-CMiKvIW1.d.cts} +8 -23
  18. package/dist/rules-B3b-BZLf.d.cts +30 -0
  19. package/dist/rules-BJMT0N0i.d.ts +30 -0
  20. package/dist/servers/admin/index.d.cts +402 -6
  21. package/dist/servers/admin/index.d.ts +402 -6
  22. package/dist/servers/auth/index.d.cts +1 -1
  23. package/dist/servers/auth/index.d.ts +1 -1
  24. package/dist/servers/crud/index.cjs +2 -2
  25. package/dist/servers/crud/index.cjs.map +1 -1
  26. package/dist/servers/crud/index.d.cts +7 -6
  27. package/dist/servers/crud/index.d.ts +7 -6
  28. package/dist/servers/crud/index.js +2 -2
  29. package/dist/servers/crud/index.js.map +1 -1
  30. package/dist/servers/hono/index.d.cts +3 -3
  31. package/dist/servers/hono/index.d.ts +3 -3
  32. package/dist/servers/index.cjs +106 -94
  33. package/dist/servers/index.cjs.map +1 -1
  34. package/dist/servers/index.d.cts +10 -9
  35. package/dist/servers/index.d.ts +10 -9
  36. package/dist/servers/index.js +106 -94
  37. package/dist/servers/index.js.map +1 -1
  38. package/dist/sync/bigquery.cjs +5 -5
  39. package/dist/sync/bigquery.cjs.map +1 -1
  40. package/dist/sync/bigquery.d.cts +28 -3
  41. package/dist/sync/bigquery.d.ts +28 -3
  42. package/dist/sync/bigquery.js +5 -5
  43. package/dist/sync/bigquery.js.map +1 -1
  44. package/dist/sync/index.cjs +74 -54
  45. package/dist/sync/index.cjs.map +1 -1
  46. package/dist/sync/index.d.cts +63 -17
  47. package/dist/sync/index.d.ts +63 -17
  48. package/dist/sync/index.js +74 -54
  49. package/dist/sync/index.js.map +1 -1
  50. package/dist/sync/meilisearch.cjs +4 -0
  51. package/dist/sync/meilisearch.cjs.map +1 -0
  52. package/dist/sync/meilisearch.d.cts +114 -0
  53. package/dist/sync/meilisearch.d.ts +114 -0
  54. package/dist/sync/meilisearch.js +4 -0
  55. package/dist/sync/meilisearch.js.map +1 -0
  56. package/dist/{types-CE-EfugW.d.cts → types-B2e-T8EM.d.cts} +160 -8
  57. package/dist/{types-B4dMmfet.d.cts → types-BIZz3sxN.d.cts} +1 -1
  58. package/dist/{types-DT7Nypd_.d.ts → types-BbFZ57eK.d.ts} +101 -41
  59. package/dist/{types-DyKJJ9UQ.d.ts → types-DSMiiOrU.d.ts} +1 -1
  60. package/dist/{types-cY03CMya.d.ts → types-XRjVKN9r.d.ts} +160 -8
  61. package/dist/{types-BwH1C-wi.d.cts → types-zFrp8RnM.d.cts} +101 -41
  62. package/package.json +19 -1
  63. package/dist/index-D47y5giY.d.ts +0 -469
  64. package/dist/index-dW_7jrlK.d.cts +0 -469
@@ -1,4 +1,4 @@
1
- # @lpdjs/firestore-repo-service (v2.6.57) — full documentation
1
+ # @lpdjs/firestore-repo-service (v3.0.1) — full documentation
2
2
 
3
3
  > ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
4
4
 
@@ -1304,6 +1304,7 @@ Send complex filter conditions including `where` (AND), `orWhere` (simple OR), a
1304
1304
  | `basePath` | `string` | Base path prefix (e.g., `"/api/v1"`) |
1305
1305
  | `middlewares` | `MiddlewareHandler[]` | Custom Hono middleware array |
1306
1306
  | `repos` | `Record<string, CrudRepoConfig>` | Per-repository configuration mapping |
1307
+ | `indexesError` | `(err: { repoName, error, indexUrl, c }) => void` | Callback triggered when a Firestore missing-index error occurs |
1307
1308
  | `openapi` | `OpenAPISpecOptions` | OpenAPI 3.1 documentation settings |
1308
1309
  | `verbose` | `boolean` | Include detailed error messages in HTTP 500 responses |
1309
1310
 
@@ -1318,10 +1319,65 @@ Send complex filter conditions including `where` (AND), `orWhere` (simple OR), a
1318
1319
  | `orderableFields` | `string[]` | List of allowed fields for ordering |
1319
1320
  | `allowedIncludes` | `string[]` | List of relation keys allowed in `includes` |
1320
1321
  | `allowDelete` | `boolean` | Whether `DELETE /:id` is enabled |
1322
+ | `rules` | `CrudRule[]` | Before rules & diff engine for mutation validation |
1321
1323
  | `pageSize` | `number` | Default page size for list requests |
1322
1324
 
1323
1325
  ---
1324
1326
 
1327
+ ## Before Rules & Diff Engine (`rules`)
1328
+
1329
+ You can define validation rules executed before document mutation (`PUT`, `PATCH`, and `POST /:repoName/batch`). The rule receives the existing document state (`before`), the simulated document state (`after`), the dictionary of modified fields (`changes`), operation type (`op`), document ID, and the Hono context (`c`).
1330
+
1331
+ ```typescript
1332
+ repos: {
1333
+ events: {
1334
+ path: "events",
1335
+ rules: [
1336
+ {
1337
+ description: "Cannot cancel an event once invoiced",
1338
+ run: ({ before, changes }) => {
1339
+ if (changes.status === "cancelled" && before.isInvoiced) {
1340
+ return false; // Rejects with 403 and the rule description
1341
+ }
1342
+ return true;
1343
+ },
1344
+ },
1345
+ {
1346
+ description: "Only admins can change event ownership",
1347
+ run: ({ changes, c }) => {
1348
+ if (changes.organizerId) {
1349
+ const user = c.get("user");
1350
+ if (user?.role !== "admin") return "Forbidden: admin role required";
1351
+ }
1352
+ return true;
1353
+ },
1354
+ },
1355
+ ],
1356
+ },
1357
+ }
1358
+ ```
1359
+
1360
+ If a rule returns `false` or a string error message, the mutation is rejected with `HTTP 403 Forbidden` without writing to Firestore.
1361
+
1362
+ ---
1363
+
1364
+ ## Missing Index Detection (`indexesError` & HTTP 424)
1365
+
1366
+ When a complex filter or compound query requires a composite index that has not yet been built in Firestore, the CRUD server automatically catches the Firestore `FAILED_PRECONDITION` error:
1367
+
1368
+ 1. **Invokes `indexesError` callback**: Passes `{ repoName, error, indexUrl, c }` for error tracking, alerting, or Sentry logging.
1369
+ 2. **Returns `HTTP 424 Failed Dependency`**: Includes the direct link to the Firebase Console index creator in the JSON response:
1370
+
1371
+ ```json
1372
+ {
1373
+ "success": false,
1374
+ "error": "The query requires a composite index.",
1375
+ "indexUrl": "https://console.firebase.google.com/v1/r/project/my-project/firestore/indexes?create_composite=..."
1376
+ }
1377
+ ```
1378
+
1379
+ ---
1380
+
1325
1381
  # Change History
1326
1382
 
1327
1383
  Opt-in, per-repo change-history capture using Firestore triggers, with a typed read API on the configured repository.
@@ -1525,42 +1581,52 @@ The trigger always writes v2. v1 is read-only — no migration is required to st
1525
1581
 
1526
1582
  ---
1527
1583
 
1528
- # Firestore → SQL Sync
1584
+ # Firestore → Storage & Search Sync
1529
1585
 
1530
- Automatically replicate Firestore collections to a SQL database (BigQuery, etc.) via Cloud Pub/Sub.
1586
+ Automatically replicate Firestore collections to SQL databases (BigQuery, etc.) and search engines (Meilisearch, etc.) via Cloud Pub/Sub.
1531
1587
 
1532
1588
  ## Architecture
1533
1589
 
1534
1590
  ```
1535
- Firestore Triggers → Cloud Pub/Sub → Worker → SQL Database
1536
- (onCreate/onUpdate/onDelete) (BigQuery, etc.)
1591
+ Firestore Triggers (onDocumentWritten) → Cloud Pub/Sub → Worker → Target Adapters
1592
+ (users_onSync) (BigQuery, Meilisearch...)
1537
1593
  ```
1538
1594
 
1539
- Each document change in Firestore publishes a message to a per-repo Pub/Sub topic.
1540
- A worker subscribes to these topics, batches the changes, and flushes them to SQL.
1595
+ Each document change in Firestore triggers a single `onDocumentWritten` Cloud Function (`${repoName}_onSync`) that publishes an event (`INSERT`, `UPSERT`, or `DELETE`) to a per-repo Pub/Sub topic.
1596
+ A worker subscribes to these topics, batches the changes, and flushes them to one or more configured **Sync Adapters** concurrently.
1541
1597
 
1542
1598
  ## Quick Start
1543
1599
 
1544
1600
  ```typescript
1545
1601
  import { createServers } from "@lpdjs/firestore-repo-service";
1546
1602
  import { BigQueryAdapter } from "@lpdjs/firestore-repo-service/sync/bigquery";
1603
+ import { MeilisearchAdapter } from "@lpdjs/firestore-repo-service/sync/meilisearch";
1547
1604
  import { BigQuery } from "@google-cloud/bigquery";
1548
1605
  import { PubSub } from "@google-cloud/pubsub";
1549
- import * as firestoreTriggers from "firebase-functions/v2/firestore";
1606
+ import { onDocumentWritten } from "firebase-functions/v2/firestore";
1550
1607
  import * as pubsubHandler from "firebase-functions/v2/pubsub";
1551
1608
  import { onRequest } from "firebase-functions/v2/https";
1552
1609
 
1553
1610
  const servers = createServers(repos, { onRequest });
1554
1611
 
1555
1612
  const sync = servers.sync({
1556
- deps: { firestoreTriggers, pubsubHandler, pubsub: new PubSub() },
1557
- adapter: new BigQueryAdapter({
1558
- bigquery: new BigQuery({
1559
- projectId: "my-project",
1560
- location: "us-central1",
1613
+ deps: { firestoreTriggers: { onDocumentWritten }, pubsubHandler, pubsub: new PubSub() },
1614
+ adapters: [
1615
+ new BigQueryAdapter({
1616
+ bigquery: new BigQuery({
1617
+ projectId: "my-project",
1618
+ location: "us-central1",
1619
+ }),
1620
+ datasetId: "firestore_sync",
1561
1621
  }),
1562
- datasetId: "firestore_sync",
1563
- }),
1622
+ new MeilisearchAdapter({
1623
+ host: "http://localhost:7700",
1624
+ apiKey: "masterKey",
1625
+ indexesSettings: {
1626
+ users: { searchableAttributes: ["name", "email"], filterableAttributes: ["role"] },
1627
+ },
1628
+ }),
1629
+ ],
1564
1630
  topicPrefix: "firestore-sync",
1565
1631
  autoMigrate: true,
1566
1632
  admin: {
@@ -1577,6 +1643,7 @@ const sync = servers.sync({
1577
1643
  exclude: ["sensitiveField"],
1578
1644
  columnMap: { docId: "user_id" },
1579
1645
  tableName: "users",
1646
+ adapters: ["bigquery", "meilisearch"], // Fan-out to both
1580
1647
  },
1581
1648
  posts: { columnMap: { docId: "post_id" } },
1582
1649
  },
@@ -1584,13 +1651,9 @@ const sync = servers.sync({
1584
1651
 
1585
1652
  // Export triggers + PubSub handlers
1586
1653
  export const {
1587
- users_onCreate,
1588
- users_onUpdate,
1589
- users_onDelete,
1654
+ users_onSync,
1590
1655
  sync_users,
1591
- posts_onCreate,
1592
- posts_onUpdate,
1593
- posts_onDelete,
1656
+ posts_onSync,
1594
1657
  sync_posts,
1595
1658
  adminsync,
1596
1659
  } = sync.functions;
@@ -1604,17 +1667,18 @@ export const {
1604
1667
 
1605
1668
  The unified wrapper that creates triggers, workers, and the optional admin server (using the repository registry already bound to `createServers`).
1606
1669
 
1607
- | Option | Type | Default | Description |
1608
- | ----------------- | ---------------------- | ------------------ | --------------------------------------------------------------- |
1609
- | `deps` | `SyncDeps` | required | Firebase Functions + PubSub dependencies |
1610
- | `adapter` | `SqlAdapter` | required | SQL adapter (e.g. `BigQueryAdapter`) |
1611
- | `topicPrefix` | `string` | `"firestore-sync"` | Pub/Sub topic name prefix |
1612
- | `batchSize` | `number` | `100` | Max rows per flush batch |
1613
- | `flushIntervalMs` | `number` | `5000` | Flush interval in ms |
1614
- | `autoMigrate` | `boolean` | `false` | Auto-create/migrate tables on first event |
1615
- | `workerOptions` | `SyncWorkerOptions` | — | CF v2 options for the worker (`concurrency`, `maxInstances`, …) |
1616
- | `admin` | `adminsyncConfig` | — | Optional admin endpoint config |
1617
- | `repos` | `TypedRepoSyncConfigs` | — | Per-repo overrides |
1670
+ | Option | Type | Default | Description |
1671
+ | ----------------- | ----------------------------------- | ------------------ | --------------------------------------------------------------- |
1672
+ | `deps` | `SyncDeps` | required | Firebase Functions (`onDocumentWritten`) + PubSub dependencies |
1673
+ | `adapters` | `SyncAdapter[]` | — | List of sync adapters (e.g. `[bigquery, meilisearch]`) |
1674
+ | `adapter` | `SyncAdapter` | — | Single sync adapter (convenience alias for `adapters: [...]`) |
1675
+ | `topicPrefix` | `string` | `"firestore-sync"` | Pub/Sub topic name prefix |
1676
+ | `batchSize` | `number` | `100` | Max rows per flush batch |
1677
+ | `flushIntervalMs` | `number` | `5000` | Flush interval in ms |
1678
+ | `autoMigrate` | `boolean` | `false` | Auto-create/migrate tables and indexes on first event |
1679
+ | `workerOptions` | `SyncWorkerOptions` | — | CF v2 options for the worker (`concurrency`, `maxInstances`, …) |
1680
+ | `admin` | `adminsyncConfig` | — | Optional admin endpoint config |
1681
+ | `repos` | `TypedRepoSyncConfigs` | — | Per-repo overrides |
1618
1682
 
1619
1683
  ### Dependencies (`deps`)
1620
1684
 
@@ -1622,29 +1686,33 @@ All Firebase/GCP modules are injected — the library never imports them directl
1622
1686
 
1623
1687
  ```typescript
1624
1688
  deps: {
1625
- firestoreTriggers, // firebase-functions/v2/firestore
1626
- pubsubHandler, // firebase-functions/v2/pubsub
1689
+ firestoreTriggers: { onDocumentWritten }, // firebase-functions/v2/firestore
1690
+ pubsubHandler, // firebase-functions/v2/pubsub
1627
1691
  pubsub: new PubSub({ projectId: "my-project" }),
1628
1692
  }
1629
1693
  ```
1630
1694
 
1631
1695
  **Lazy initialization**
1632
- `deps.pubsub` and `adapter` both accept a factory function `() => T` for lazy initialization.
1696
+ `deps.pubsub` and `adapters` both accept a factory function `() => T` for lazy initialization.
1633
1697
  This avoids creating gRPC channels or BigQuery connections at module-load time for Cloud Functions
1634
1698
  that don't need them (e.g. HTTP-only functions sharing the same deploy).
1635
1699
 
1636
1700
  ```typescript
1637
- deps: { firestoreTriggers, pubsubHandler, pubsub: () => new PubSub() },
1638
- adapter: () => new BigQueryAdapter({ bigquery: new BigQuery(), datasetId: "sync" }),
1701
+ deps: { firestoreTriggers: { onDocumentWritten }, pubsubHandler, pubsub: () => new PubSub() },
1702
+ adapters: [
1703
+ () => new BigQueryAdapter({ bigquery: new BigQuery(), datasetId: "sync" }),
1704
+ () => new MeilisearchAdapter({ host: "http://localhost:7700", apiKey: "masterKey" }),
1705
+ ],
1639
1706
  ```
1640
1707
 
1641
1708
  ### Per-Repo Config (`repos`)
1642
1709
 
1643
1710
  | Option | Type | Description |
1644
1711
  | ------------- | ------------------------ | ------------------------------------------------------------------- |
1645
- | `tableName` | `string` | SQL table name (defaults to repo name) |
1646
- | `exclude` | `string[]` | Fields to exclude from SQL |
1647
- | `columnMap` | `Record<string, string>` | Rename fields → SQL columns |
1712
+ | `tableName` | `string` | SQL table / Search index name (defaults to repo name) |
1713
+ | `adapters` | `string[]` | Filter target adapters for this repo (e.g. `["bigquery"]`) |
1714
+ | `exclude` | `string[]` | Fields to exclude from sync |
1715
+ | `columnMap` | `Record<string, string>` | Rename fields → SQL columns / document properties |
1648
1716
  | `triggerPath` | `string` | **Required for collection groups** — the full document path pattern |
1649
1717
 
1650
1718
  ### Collection Groups (`triggerPath`)
@@ -1667,8 +1735,7 @@ This tells Firebase where to listen for document changes since collection groups
1667
1735
  Pub/Sub does **not** guarantee message order, and Cloud Functions v2 deliberately
1668
1736
  exposes no way to enable `enableMessageOrdering` on the auto-created push subscription
1669
1737
  behind `onMessagePublished`. For Firestore sync this means rapid successive writes to
1670
- the same document (e.g. `create` then `update`) could otherwise be flushed to SQL out
1671
- of order, leaving stale data.
1738
+ the same document (e.g. `create` then `update`) could otherwise be flushed out of order, leaving stale data.
1672
1739
 
1673
1740
  The library handles this **at the application level**:
1674
1741
 
@@ -1710,8 +1777,8 @@ application-level tombstone column.
1710
1777
  You don't need to pre-create anything. On first deploy:
1711
1778
 
1712
1779
  - Cloud Functions v2 creates the trigger topic (`{topicPrefix}-{repoName}`) via Eventarc.
1713
- - The worker creates the dead-letter topic (`{topicPrefix}-{repoName}-dlq`) the first
1714
- time a flush fails.
1780
+ - The worker creates the dead-letter topic (`{topicPrefix}-{repoName}-{adapterName}-dlq`) the first
1781
+ time a flush fails for that adapter.
1715
1782
 
1716
1783
  **Why the library doesn't pre-create subscriptions**
1717
1784
  A previous version exposed an `ensureSyncInfra` helper that created pull subscriptions
@@ -1725,18 +1792,18 @@ Three knobs let you trade latency, throughput and BigQuery quota pressure:
1725
1792
 
1726
1793
  | Option | Where | Default | What it controls |
1727
1794
  | ----------------- | ---------------- | ------- | --------------------------------------------------------------------------- |
1728
- | `batchSize` | top-level config | `100` | Max rows merged per BigQuery `MERGE` statement |
1795
+ | `batchSize` | top-level config | `100` | Max rows merged per flush batch |
1729
1796
  | `flushIntervalMs` | top-level config | `5000` | Max time a row sits in the in-memory queue before being flushed |
1730
1797
  | `workerOptions` | top-level config | — | Cloud Functions v2 options for every worker handler (concurrency, scaling…) |
1731
1798
 
1732
1799
  ```typescript
1733
1800
  createServers(repos).sync({
1734
1801
  // ...
1735
- batchSize: 500, // bigger batches → fewer DML statements → less quota pressure
1802
+ batchSize: 500, // bigger batches → fewer write requests → less quota pressure
1736
1803
  flushIntervalMs: 10_000, // wait longer to fill batches (higher latency, higher throughput)
1737
1804
  workerOptions: {
1738
1805
  concurrency: 5, // process up to 5 messages in parallel per instance
1739
- maxInstances: 1, // ⚠️ keep at 1 per repo to avoid BigQuery serialize-access errors
1806
+ maxInstances: 1, // ⚠️ keep at 1 per repo when using SQL without CDC
1740
1807
  minInstances: 0, // set to 1 to avoid cold starts (costs ~$5-15/mo)
1741
1808
  memory: "512MiB",
1742
1809
  timeoutSeconds: 120,
@@ -1752,20 +1819,20 @@ field is accepted (`cpu`, `vpcConnector`, `serviceAccount`, `secrets`, etc.).
1752
1819
 
1753
1820
  ### Concurrency & PubSub ack semantics
1754
1821
 
1755
- Each repo gets its own `SyncQueue` shared across all in-instance invocations
1822
+ Each repo and target adapter pair gets its own `SyncQueue` shared across all in-instance invocations
1756
1823
  (it lives in the worker's module closure). When `concurrency > 1`, several
1757
1824
  PubSub messages are handled in parallel **inside the same Node.js process**
1758
- and all enqueue into the same buffer.
1825
+ and all enqueue into the appropriate buffer.
1759
1826
 
1760
1827
  `SyncQueue.flush()` coalesces concurrent callers: every parallel handler
1761
1828
  awaits the same in-flight write and only resolves once its event has
1762
1829
  actually been persisted. This is what makes `await q.flush()` at the end
1763
- of the handler safe — PubSub only acks after BigQuery confirmed the write,
1830
+ of the handler safe — PubSub only acks after target adapters confirmed the write,
1764
1831
  so an instance crash before flush never loses an event.
1765
1832
 
1766
1833
  **Dead-letter & infinite retry protection**
1767
1834
 
1768
- `onFlushError` re-publishes failed events to `{topicPrefix}-{repoName}-dlq`
1835
+ `onFlushError` re-publishes failed events to `{topicPrefix}-{repoName}-{adapterName}-dlq`
1769
1836
  and re-throws if that publish itself fails — PubSub then redelivers the
1770
1837
  original message instead of acking. To avoid an infinite redelivery loop on
1771
1838
  a poison message, configure a **dead-letter policy on the PubSub
@@ -1780,21 +1847,35 @@ subscription** (Cloud Functions v2 / Eventarc subscription) with e.g.
1780
1847
  - Medium (10-100 writes/s/repo): `batchSize: 500`, `flushIntervalMs: 10_000`,
1781
1848
  `concurrency: 20`, `maxInstances: 3`.
1782
1849
  - High (> 100 writes/s/repo): `batchSize: 500–1000`, `flushIntervalMs: 10_000`,
1783
- `concurrency: 40`, `maxInstances: 5+` — the Storage Write API has no
1850
+ `concurrency: 40`, `maxInstances: 5+` — the Storage Write API and Meilisearch batching have no
1784
1851
  per-table concurrency cap, so scale horizontally as needed.
1785
- :::
1852
+
1853
+ ## Multi-Adapter Fan-Out & Fault Isolation
1854
+
1855
+ You can sync Firestore changes to multiple destinations concurrently (e.g. BigQuery for analytics and Meilisearch for full-text search) by passing an array of adapters:
1856
+
1857
+ ```typescript
1858
+ adapters: [bigQueryAdapter, meilisearchAdapter],
1859
+ repos: {
1860
+ users: {
1861
+ adapters: ["bigquery", "meilisearch"], // Fans out to both
1862
+ },
1863
+ logs: {
1864
+ adapters: ["bigquery"], // Only sent to BigQuery
1865
+ },
1866
+ }
1867
+ ```
1868
+
1869
+ ### Complete Fault Isolation
1870
+
1871
+ Each destination operates with its own isolated `SyncQueue` and dedicated dead-letter topic (`firestore-sync-users-meilisearch-dlq`). If Meilisearch is temporarily unreachable or experiences an outage, its failed batches are directed to its own DLQ, while BigQuery continues inserting and merging events seamlessly without delay or interruption.
1786
1872
 
1787
1873
  ## BigQuery Adapter
1788
1874
 
1789
- The library ships a single BigQuery adapter that streams rows through the
1790
- **BigQuery Storage Write API** in **CDC mode** (Change Data Capture).
1791
- Multiple Cloud Function instances can write in parallel with no
1792
- concurrency cap, it is ~50% cheaper than legacy streaming inserts, and
1793
- out-of-order events are deduplicated by `_CHANGE_SEQUENCE_NUMBER` derived
1794
- from each event's `__sync_version`.
1875
+ The BigQuery adapter streams rows through the **BigQuery Storage Write API** in **CDC mode** (Change Data Capture).
1876
+ Multiple Cloud Function instances can write in parallel with no concurrency cap, it is ~50% cheaper than legacy streaming inserts, and out-of-order events are deduplicated by `_CHANGE_SEQUENCE_NUMBER` derived from each event's `__sync_version`.
1795
1877
 
1796
- The Storage Write client is an **optional peer dependency** — install it
1797
- in your functions project:
1878
+ The Storage Write client is an **optional peer dependency** — install it in your functions project:
1798
1879
 
1799
1880
  ```bash
1800
1881
  npm install @google-cloud/bigquery-storage @google-cloud/bigquery
@@ -1815,63 +1896,67 @@ const adapter = new BigQueryAdapter({
1815
1896
 
1816
1897
  The adapter handles:
1817
1898
 
1818
- - Table creation via DDL with `PRIMARY KEY ... NOT ENFORCED` and clustering
1819
- on the PK (required by CDC mode)
1820
- - Streaming UPSERTs and DELETEs through the default stream (at-least-once,
1821
- no stream finalization needed)
1899
+ - Table creation via DDL with `PRIMARY KEY ... NOT ENFORCED` and clustering on the PK (required by CDC mode)
1900
+ - Streaming UPSERTs and DELETEs through the default stream (at-least-once, no stream finalization needed)
1822
1901
  - Schema introspection (for health checks)
1823
1902
  - Automatic column migration (`addColumns`) with type-drift detection
1824
- - ISO 8601 strings and `Date` instances in `TIMESTAMP` columns are encoded
1825
- as epoch microseconds (the wire format the Storage Write API expects)
1903
+ - ISO 8601 strings and `Date` instances in `TIMESTAMP` columns are encoded as epoch microseconds (the wire format the Storage Write API expects)
1826
1904
 
1827
1905
  ### Authentication
1828
1906
 
1829
1907
  - **Production (Cloud Run / Cloud Functions)**: credentials are automatic via ADC — just pass `projectId`
1830
1908
  - **Local development**: run `gcloud auth application-default login`
1831
- - The service account needs `bigquery.tables.updateData` (granted by
1832
- `roles/bigquery.dataEditor`)
1909
+ - The service account needs `bigquery.tables.updateData` (granted by `roles/bigquery.dataEditor`)
1833
1910
 
1834
1911
  ### About `maxStaleness`
1835
1912
 
1836
- CDC writes land in BigQuery's **change buffer**; rows only become visible
1837
- in the base table once an asynchronous **MERGE** applies the buffer.
1838
- `max_staleness` is the SLO for that merge:
1913
+ CDC writes land in BigQuery's **change buffer**; rows only become visible in the base table once an asynchronous **MERGE** applies the buffer. `max_staleness` is the SLO for that merge:
1914
+
1915
+ - **`INTERVAL 0`** (BigQuery's silent default if you omit the option) — every `SELECT` triggers a synchronous merge of the entire buffer before returning results. Cheap-looking, but it makes reads slow and expensive on busy tables and defeats the point of CDC.
1916
+ - **`INTERVAL N MINUTE`** — BigQuery runs the MERGE in the background at most every N minutes (free, doesn't block reads). Reads against the table see data up to N minutes stale. The library defaults to **15 minutes** — a good production tradeoff between cost and freshness.
1917
+ - For development you can set `INTERVAL 1 MINUTE` if you need to see your writes quickly in the BigQuery UI.
1839
1918
 
1840
- - **`INTERVAL 0`** (BigQuery's silent default if you omit the option) —
1841
- every `SELECT` triggers a synchronous merge of the entire buffer before
1842
- returning results. Cheap-looking, but it makes reads slow and expensive
1843
- on busy tables and defeats the point of CDC.
1844
- - **`INTERVAL N MINUTE`** — BigQuery runs the MERGE in the background at
1845
- most every N minutes (free, doesn't block reads). Reads against the
1846
- table see data up to N minutes stale. The library defaults to
1847
- **15 minutes** — a good production tradeoff between cost and freshness.
1848
- - For development you can set `INTERVAL 1 MINUTE` if you need to see your
1849
- writes quickly in the BigQuery UI.
1919
+ ## Meilisearch Adapter
1850
1920
 
1851
- ### Migrating tables created by older versions of this library
1921
+ The Meilisearch adapter streams Firestore documents into [Meilisearch](https://www.meilisearch.com/) indexes for fast, typo-tolerant full-text search.
1852
1922
 
1853
- Tables originally created by the legacy MERGE-based adapter (≤ 2.3.x) do
1854
- not have a PK constraint. Before deploying, run once per table:
1923
+ The `meilisearch` JavaScript SDK is an **optional peer dependency**:
1855
1924
 
1856
- ```sql
1857
- ALTER TABLE `dataset.posts`
1858
- ADD PRIMARY KEY (post_id) NOT ENFORCED,
1859
- SET OPTIONS (max_staleness = INTERVAL 15 MINUTE);
1925
+ ```bash
1926
+ npm install meilisearch
1860
1927
  ```
1861
1928
 
1862
- (Clustering can only be set at table creation; if your table is not
1863
- clustered on the PK, recreate it with `CREATE TABLE … AS SELECT …` or
1864
- accept the read-time penalty — Storage Write CDC still works.)
1929
+ ```typescript
1930
+ import { MeilisearchAdapter } from "@lpdjs/firestore-repo-service/sync/meilisearch";
1931
+
1932
+ const meilisearchAdapter = new MeilisearchAdapter({
1933
+ host: "http://localhost:7700",
1934
+ apiKey: "masterKey",
1935
+ indexesSettings: {
1936
+ users: {
1937
+ searchableAttributes: ["name", "email", "bio"],
1938
+ filterableAttributes: ["role", "status", "createdAt"],
1939
+ sortableAttributes: ["createdAt", "name"],
1940
+ },
1941
+ posts: {
1942
+ searchableAttributes: ["title", "content"],
1943
+ filterableAttributes: ["status", "userId"],
1944
+ },
1945
+ },
1946
+ });
1947
+ ```
1948
+
1949
+ The adapter handles:
1950
+ - Automatic index creation on first event with primary key configuration.
1951
+ - Syncing index settings (`indexesSettings`) like searchable, filterable, and sortable attributes.
1952
+ - High-throughput document batching (`addDocuments`) and document deletions (`deleteDocuments`).
1953
+ - Index statistics and health inspection via `/health` and `/config-check`.
1865
1954
 
1866
1955
  ## Schema Evolution
1867
1956
 
1868
- `autoMigrate` adds columns when your Zod schema gains fields. It **never**
1869
- changes the type of an existing column — BigQuery itself only allows narrow
1870
- widenings (`INT64 → NUMERIC → BIGNUMERIC`, `DATE → DATETIME → TIMESTAMP`),
1871
- and a wrong implicit conversion would silently corrupt data.
1957
+ `autoMigrate` adds columns when your Zod schema gains fields. It **never** changes the type of an existing column — BigQuery itself only allows narrow widenings (`INT64 → NUMERIC → BIGNUMERIC`, `DATE → DATETIME → TIMESTAMP`), and a wrong implicit conversion would silently corrupt data.
1872
1958
 
1873
- Starting with v2.3.x the worker therefore detects type drift and throws
1874
- `SchemaTypeMismatchError` on the first event:
1959
+ Starting with v2.3.x the worker detects type drift and throws `SchemaTypeMismatchError` on the first event:
1875
1960
 
1876
1961
  ```
1877
1962
  Schema drift detected on `posts`: column `view_count` has type STRING in
@@ -1882,24 +1967,14 @@ BigQuery type and add a transform in your repo to coerce values,
1882
1967
  (c) drop & recreate the table.
1883
1968
  ```
1884
1969
 
1885
- This is a **fail-fast** by design: the alternative is every flush failing
1886
- with a cryptic cast error, the dead-letter queue filling up, and PubSub
1887
- retrying forever.
1888
-
1889
1970
  ### Recommended workflow
1890
1971
 
1891
- Treat Firestore document schemas as **append-only**. When you must change
1892
- the type of a field:
1972
+ Treat Firestore document schemas as **append-only**. When you must change the type of a field:
1893
1973
 
1894
- 1. **Rename the field in Zod** (`view_count` → `view_count_v2`). The next
1895
- migration adds the new column; old rows keep `NULL` until backfilled.
1974
+ 1. **Rename the field in Zod** (`view_count` → `view_count_v2`). The next migration adds the new column; old rows keep `NULL` until backfilled.
1896
1975
  2. **Backfill** with a one-off SQL job: `UPDATE … SET view_count_v2 = CAST(view_count AS INT64)`.
1897
1976
  3. **Drop the old column** once writes have moved over.
1898
1977
 
1899
- If you really need to mutate a column in-place, do it manually before
1900
- deploying the new code (`ALTER TABLE x ALTER COLUMN y SET DATA TYPE …` —
1901
- allowed only for the widenings BigQuery accepts).
1902
-
1903
1978
  ## Sync Admin
1904
1979
 
1905
1980
  The optional admin endpoint provides a web UI for monitoring and managing the sync pipeline.
@@ -1908,9 +1983,9 @@ The optional admin endpoint provides a web UI for monitoring and managing the sy
1908
1983
 
1909
1984
  | Feature | Flag | Description |
1910
1985
  | ---------------- | ------------- | --------------------------------------------------------------------- |
1911
- | **Health Check** | `healthCheck` | Compare expected schema (from Zod) vs actual SQL columns |
1912
- | **Force Sync** | `manualSync` | Re-sync all documents from a Firestore collection |
1913
- | **Config Check** | `configCheck` | Verify GCP APIs, topics, tables, and IAM — with `gcloud` fix commands |
1986
+ | **Health Check** | `healthCheck` | Compare expected schema vs actual SQL columns & Search index stats |
1987
+ | **Force Sync** | `manualSync` | Re-sync all documents from a Firestore collection to all targets |
1988
+ | **Config Check** | `configCheck` | Verify GCP APIs, Meilisearch, topics, tables, and IAM permissions |
1914
1989
 
1915
1990
  ### Configuration
1916
1991
 
@@ -1931,105 +2006,19 @@ admin: {
1931
2006
  }
1932
2007
  ```
1933
2008
 
1934
- ### Authentication
1935
-
1936
- Same as the Admin Server — supports HTTP Basic Auth, a Firebase `AuthExtension`,
1937
- or a custom middleware function:
1938
-
1939
- ```typescript
1940
- // Custom middleware
1941
- admin: {
1942
- auth: async (req, res, next) => {
1943
- const token = req.headers["x-api-key"];
1944
- if (token !== process.env.API_KEY) {
1945
- res.status(401).send("Unauthorized");
1946
- return;
1947
- }
1948
- next();
1949
- },
1950
- }
1951
- ```
1952
-
1953
- #### Firebase Auth (unified with admin UI)
1954
-
1955
- The `auth` field also accepts the `AuthExtension` returned by
1956
- `firebaseAuth({ ... })` — the same one used by `servers.admin()`.
1957
- The inline login page, session cookies and `allow()`
1958
- callback work identically:
1959
-
1960
- ```typescript
1961
- import { firebaseAuth } from "@lpdjs/firestore-repo-service/servers/auth";
1962
- import { getAuth } from "firebase-admin/auth";
1963
-
1964
- admin: {
1965
- auth: firebaseAuth({
1966
- getAuth: () => getAuth(),
1967
- mode: "cookie",
1968
- apiKey: process.env.FIREBASE_WEB_API_KEY!,
1969
- authDomain: process.env.FIREBASE_AUTH_DOMAIN!,
1970
- allow: ({ claims }) =>
1971
- claims.role === "superAdmin" ? { role: "superAdmin" } : null,
1972
- }),
1973
- featuresFlag: { healthCheck: true, configCheck: true },
1974
- }
1975
- ```
1976
-
1977
2009
  ### Config Check
1978
2010
 
1979
- The `/config-check` endpoint verifies your GCP setup:
2011
+ The `/config-check` endpoint verifies your GCP and Search engine setup:
1980
2012
 
1981
- - **BigQuery API** — is it enabled and accessible?
1982
- - **BigQuery tables** — does each repo table exist?
2013
+ - **BigQuery API & Tables** — is it reachable and do the repo tables exist?
2014
+ - **Meilisearch API & Indexes** — is the server reachable and are indexes initialized?
1983
2015
  - **Pub/Sub topics** — does each `{topicPrefix}-{repoName}` topic exist?
1984
2016
 
1985
- For each issue, it shows:
1986
-
1987
- - A `gcloud` command to fix it
1988
- - A direct link to the GCP Console
1989
-
1990
- Supports `Accept: application/json` for programmatic use.
1991
-
1992
- ### Deploying the Admin
1993
-
1994
- The admin handler is auto-wrapped when `onRequest` is provided in the config.
1995
- Pass `httpsOptions` to configure the Cloud Function (invoker, memory, region, etc.):
1996
-
1997
- ```typescript
1998
- admin: {
1999
- onRequest,
2000
- httpsOptions: { invoker: "public", memory: "512MiB" },
2001
- auth: { type: "basic", username: "admin", password: "secret" },
2002
- featuresFlag: { healthCheck: true, configCheck: true },
2003
- }
2004
- ```
2005
-
2006
- The handler is then available in `sync.functions.adminsync` — already wrapped as a Cloud Function.
2007
-
2008
- If you omit `onRequest`, the raw handler is exposed and you wrap it manually:
2009
-
2010
- ```typescript
2011
- import { onRequest } from "firebase-functions/v2/https";
2012
-
2013
- export const adminsync = onRequest({ invoker: "public" }, sync.adminHandler!);
2014
- ```
2017
+ For each issue, it shows a `gcloud` command or hint to fix it.
2015
2018
 
2016
2019
  ### Force Sync
2017
2020
 
2018
- Triggered from the admin dashboard or via `POST /force-sync/{repo}` (HTML or
2019
- `Accept: application/json`). It re-reads every document of a Firestore collection and
2020
- republishes it through the sync pipeline.
2021
-
2022
- The response includes:
2023
-
2024
- | Field | Description |
2025
- | -------------- | --------------------------------------------------- |
2026
- | `processed` | Total documents read from Firestore |
2027
- | `published` | Successful Pub/Sub publishes |
2028
- | `errors` | Number of documents that failed to publish |
2029
- | `errorSamples` | First 5 errors (`{ docId, message }`) for diagnosis |
2030
-
2031
- Errors are also logged via `console.error('[ForceSync:{repo}] doc={docId} failed:', e)`
2032
- so they appear in Cloud Logging.
2021
+ Triggered from the admin dashboard or via `POST /force-sync/{repo}` (HTML or `Accept: application/json`). It re-reads every document of a Firestore collection and pushes it through all active target adapters for that repository.
2033
2022
 
2034
2023
  ## Generated Functions
2035
2024
 
@@ -2037,10 +2026,8 @@ so they appear in Cloud Logging.
2037
2026
 
2038
2027
  | Function | Type | Purpose |
2039
2028
  | ----------------- | ----------------- | ------------------------------------- |
2040
- | `{repo}_onCreate` | Firestore trigger | Publish UPSERT on document create |
2041
- | `{repo}_onUpdate` | Firestore trigger | Publish UPSERT on document update |
2042
- | `{repo}_onDelete` | Firestore trigger | Publish DELETE on document delete |
2043
- | `sync_{repo}` | PubSub handler | Process messages and flush to SQL |
2029
+ | `{repo}_onSync` | Firestore trigger | Single `onDocumentWritten` trigger |
2030
+ | `sync_{repo}` | PubSub handler | Process messages and flush to targets |
2044
2031
  | `adminsync` | HTTP handler | Admin UI (if `admin` config provided) |
2045
2032
 
2046
2033
  ## Schema Mapping
@@ -2058,12 +2045,7 @@ Zod schemas are automatically mapped to SQL types:
2058
2045
 
2059
2046
  ## Date Handling (`setDateHandling`)
2060
2047
 
2061
- Firestore returns dates as `Timestamp` objects. By default the library leaves them as
2062
- `Timestamp` (mode `"preserve"`), which keeps full nanosecond precision but means
2063
- consumers must call `.toDate()` themselves and Zod `z.date()` schemas will reject them.
2064
-
2065
- Switch to `"normalize"` once at app startup to convert every `Timestamp` (including
2066
- nested ones inside objects/arrays) to a JavaScript `Date` on read:
2048
+ Firestore returns dates as `Timestamp` objects. Switch to `"normalize"` once at app startup to convert every `Timestamp` to a JavaScript `Date` on read:
2067
2049
 
2068
2050
  ```typescript
2069
2051
  import { setDateHandling } from "@lpdjs/firestore-repo-service";
@@ -2071,67 +2053,59 @@ import { setDateHandling } from "@lpdjs/firestore-repo-service";
2071
2053
  setDateHandling("normalize");
2072
2054
  ```
2073
2055
 
2074
- | Mode | Behavior |
2075
- | ------------- | --------------------------------------------------------------- |
2076
- | `"preserve"` | (default) Firestore `Timestamp` instances are returned as-is |
2077
- | `"normalize"` | Recursively convert `Timestamp` → `Date` on every document read |
2078
-
2079
- This is recommended when using the BigQuery sync (Zod `z.date()` → `TIMESTAMP`) so the
2080
- schema validation and SQL serialization both see proper `Date` instances.
2056
+ ## Custom Sync Adapter
2081
2057
 
2082
- Helpers `coerceToDate(value)` and `normalizeTimestamps(value)` are also exported for
2083
- manual conversion (e.g. inside custom mappers).
2058
+ Implement the universal `SyncAdapter` interface for other storage or search engines:
2084
2059
 
2085
- ## Custom SQL Adapter
2060
+ ```typescript
2061
+ import type { SyncAdapter, SyncHealthResult } from "@lpdjs/firestore-repo-service/sync";
2086
2062
 
2087
- Implement the `SqlAdapter` interface for other databases:
2063
+ class MyCustomAdapter implements SyncAdapter {
2064
+ readonly name = "elasticsearch"; // Identifier used in repoConfigs.adapters
2088
2065
 
2089
- ```typescript
2090
- import type {
2091
- SqlAdapter,
2092
- SqlDialect,
2093
- SqlColumn,
2094
- SqlTableDef,
2095
- } from "@lpdjs/firestore-repo-service/sync";
2096
-
2097
- class MyAdapter implements SqlAdapter {
2098
- get dialect(): SqlDialect {
2099
- /* ... */
2100
- }
2101
- async tableExists(tableName: string): Promise<boolean> {
2102
- /* ... */
2103
- }
2104
- async getTableColumns(tableName: string): Promise<string[]> {
2105
- /* ... */
2106
- }
2107
- async createTable(table: SqlTableDef): Promise<void> {
2108
- /* ... */
2109
- }
2110
- async addColumns(tableName: string, columns: SqlColumn[]): Promise<void> {
2111
- /* ... */
2066
+ async targetExists(targetName: string): Promise<boolean> {
2067
+ // Check if index/table exists
2068
+ return true;
2112
2069
  }
2113
- async insertRows(
2114
- tableName: string,
2115
- rows: Record<string, unknown>[],
2116
- ): Promise<void> {
2117
- /* ... */
2118
- }
2119
- async upsertRows(
2120
- tableName: string,
2121
- rows: Record<string, unknown>[],
2070
+
2071
+ async upsert(
2072
+ targetName: string,
2073
+ items: Record<string, unknown>[],
2122
2074
  primaryKey: string,
2123
2075
  ): Promise<void> {
2124
- /* ... */
2076
+ // Bulk upsert documents
2125
2077
  }
2126
- async deleteRows(
2127
- tableName: string,
2078
+
2079
+ async delete(
2080
+ targetName: string,
2128
2081
  primaryKey: string,
2129
2082
  ids: string[],
2130
2083
  ): Promise<void> {
2131
- /* ... */
2084
+ // Bulk delete documents by IDs
2132
2085
  }
2133
- async executeRaw(sql: string): Promise<void> {
2134
- /* ... */
2086
+
2087
+ async ensureTarget(options: {
2088
+ targetName: string;
2089
+ primaryKey: string;
2090
+ schema?: any;
2091
+ exclude?: string[];
2092
+ columnMap?: Record<string, string>;
2093
+ }): Promise<void> {
2094
+ // Auto-create table/index if not exists
2095
+ }
2096
+
2097
+ async healthCheck(options: {
2098
+ targetName: string;
2099
+ primaryKey: string;
2100
+ schema?: any;
2101
+ repoConfig?: any;
2102
+ }): Promise<SyncHealthResult> {
2103
+ return {
2104
+ healthy: true,
2105
+ targetName: options.targetName,
2106
+ targetExists: true,
2107
+ error: null,
2108
+ };
2135
2109
  }
2136
2110
  }
2137
2111
  ```