@ttt-productions/query-core 0.14.22 → 0.14.24

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 (137) hide show
  1. package/README.md +6 -6
  2. package/dist/defaults.d.ts +0 -15
  3. package/dist/defaults.d.ts.map +1 -1
  4. package/dist/defaults.js +0 -15
  5. package/dist/defaults.js.map +1 -1
  6. package/dist/firestore/types.d.ts +5 -49
  7. package/dist/firestore/types.d.ts.map +1 -1
  8. package/dist/firestore/types.js.map +1 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +0 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/keys.d.ts +0 -22
  13. package/dist/keys.d.ts.map +1 -1
  14. package/dist/keys.js +0 -4
  15. package/dist/keys.js.map +1 -1
  16. package/dist/react/cache-helpers.d.ts +0 -32
  17. package/dist/react/cache-helpers.d.ts.map +1 -1
  18. package/dist/react/cache-helpers.js +0 -28
  19. package/dist/react/cache-helpers.js.map +1 -1
  20. package/dist/react/callables/create-callables.d.ts +40 -0
  21. package/dist/react/callables/create-callables.d.ts.map +1 -0
  22. package/dist/react/callables/create-callables.js +101 -0
  23. package/dist/react/callables/create-callables.js.map +1 -0
  24. package/dist/react/defaults.d.ts +0 -4
  25. package/dist/react/defaults.d.ts.map +1 -1
  26. package/dist/react/defaults.js +2 -6
  27. package/dist/react/defaults.js.map +1 -1
  28. package/dist/react/domain-events/cache-invalidation.d.ts +0 -37
  29. package/dist/react/domain-events/cache-invalidation.d.ts.map +1 -1
  30. package/dist/react/domain-events/cache-invalidation.js +4 -53
  31. package/dist/react/domain-events/cache-invalidation.js.map +1 -1
  32. package/dist/react/domain-events/create-domain-event-invalidator.d.ts +0 -18
  33. package/dist/react/domain-events/create-domain-event-invalidator.d.ts.map +1 -1
  34. package/dist/react/domain-events/create-domain-event-invalidator.js +0 -5
  35. package/dist/react/domain-events/create-domain-event-invalidator.js.map +1 -1
  36. package/dist/react/firestore/absence-scheduler.d.ts +0 -28
  37. package/dist/react/firestore/absence-scheduler.d.ts.map +1 -1
  38. package/dist/react/firestore/absence-scheduler.js +1 -39
  39. package/dist/react/firestore/absence-scheduler.js.map +1 -1
  40. package/dist/react/firestore/batch-doc-loader.d.ts +0 -30
  41. package/dist/react/firestore/batch-doc-loader.d.ts.map +1 -1
  42. package/dist/react/firestore/batch-doc-loader.js +0 -34
  43. package/dist/react/firestore/batch-doc-loader.js.map +1 -1
  44. package/dist/react/firestore/context.d.ts +0 -19
  45. package/dist/react/firestore/context.d.ts.map +1 -1
  46. package/dist/react/firestore/context.js +0 -19
  47. package/dist/react/firestore/context.js.map +1 -1
  48. package/dist/react/firestore/doc-subscription-registry.d.ts +0 -23
  49. package/dist/react/firestore/doc-subscription-registry.d.ts.map +1 -1
  50. package/dist/react/firestore/doc-subscription-registry.js +5 -26
  51. package/dist/react/firestore/doc-subscription-registry.js.map +1 -1
  52. package/dist/react/firestore/infinite-helpers.d.ts +0 -12
  53. package/dist/react/firestore/infinite-helpers.d.ts.map +1 -1
  54. package/dist/react/firestore/infinite-helpers.js +0 -12
  55. package/dist/react/firestore/infinite-helpers.js.map +1 -1
  56. package/dist/react/firestore/resubscribe.d.ts +0 -20
  57. package/dist/react/firestore/resubscribe.d.ts.map +1 -1
  58. package/dist/react/firestore/resubscribe.js +0 -20
  59. package/dist/react/firestore/resubscribe.js.map +1 -1
  60. package/dist/react/firestore/subscription-status.d.ts +0 -29
  61. package/dist/react/firestore/subscription-status.d.ts.map +1 -1
  62. package/dist/react/firestore/subscription-status.js +1 -34
  63. package/dist/react/firestore/subscription-status.js.map +1 -1
  64. package/dist/react/firestore/types.d.ts +0 -64
  65. package/dist/react/firestore/types.d.ts.map +1 -1
  66. package/dist/react/firestore/types.js +0 -3
  67. package/dist/react/firestore/types.js.map +1 -1
  68. package/dist/react/firestore/use-firestore-collection.d.ts +0 -20
  69. package/dist/react/firestore/use-firestore-collection.d.ts.map +1 -1
  70. package/dist/react/firestore/use-firestore-collection.js +1 -35
  71. package/dist/react/firestore/use-firestore-collection.js.map +1 -1
  72. package/dist/react/firestore/use-firestore-count.d.ts +0 -15
  73. package/dist/react/firestore/use-firestore-count.d.ts.map +1 -1
  74. package/dist/react/firestore/use-firestore-count.js +0 -15
  75. package/dist/react/firestore/use-firestore-count.js.map +1 -1
  76. package/dist/react/firestore/use-firestore-doc.d.ts +0 -23
  77. package/dist/react/firestore/use-firestore-doc.d.ts.map +1 -1
  78. package/dist/react/firestore/use-firestore-doc.js +3 -40
  79. package/dist/react/firestore/use-firestore-doc.js.map +1 -1
  80. package/dist/react/firestore/use-firestore-infinite.d.ts +0 -29
  81. package/dist/react/firestore/use-firestore-infinite.d.ts.map +1 -1
  82. package/dist/react/firestore/use-firestore-infinite.js +0 -32
  83. package/dist/react/firestore/use-firestore-infinite.js.map +1 -1
  84. package/dist/react/firestore/use-firestore-live-infinite.d.ts +0 -34
  85. package/dist/react/firestore/use-firestore-live-infinite.d.ts.map +1 -1
  86. package/dist/react/firestore/use-firestore-live-infinite.js +1 -35
  87. package/dist/react/firestore/use-firestore-live-infinite.js.map +1 -1
  88. package/dist/react/firestore/use-firestore-mutations.d.ts.map +1 -1
  89. package/dist/react/firestore/use-firestore-mutations.js +6 -5
  90. package/dist/react/firestore/use-firestore-mutations.js.map +1 -1
  91. package/dist/react/firestore/use-firestore-paginated.d.ts +0 -30
  92. package/dist/react/firestore/use-firestore-paginated.d.ts.map +1 -1
  93. package/dist/react/firestore/use-firestore-paginated.js +2 -33
  94. package/dist/react/firestore/use-firestore-paginated.js.map +1 -1
  95. package/dist/react/firestore/useBatchFirestoreDocs.d.ts +1 -123
  96. package/dist/react/firestore/useBatchFirestoreDocs.d.ts.map +1 -1
  97. package/dist/react/firestore/useBatchFirestoreDocs.js +23 -64
  98. package/dist/react/firestore/useBatchFirestoreDocs.js.map +1 -1
  99. package/dist/react/index.d.ts +4 -0
  100. package/dist/react/index.d.ts.map +1 -1
  101. package/dist/react/index.js +2 -13
  102. package/dist/react/index.js.map +1 -1
  103. package/dist/react/pending-mutations.d.ts +1 -21
  104. package/dist/react/pending-mutations.d.ts.map +1 -1
  105. package/dist/react/pending-mutations.js +1 -32
  106. package/dist/react/pending-mutations.js.map +1 -1
  107. package/dist/react/provider.d.ts +0 -5
  108. package/dist/react/provider.d.ts.map +1 -1
  109. package/dist/react/provider.js +0 -4
  110. package/dist/react/provider.js.map +1 -1
  111. package/dist/react/query-client.d.ts +0 -4
  112. package/dist/react/query-client.d.ts.map +1 -1
  113. package/dist/react/query-client.js +0 -4
  114. package/dist/react/query-client.js.map +1 -1
  115. package/dist/react/search/types.d.ts +0 -12
  116. package/dist/react/search/types.d.ts.map +1 -1
  117. package/dist/react/search/types.js.map +1 -1
  118. package/dist/react/search/use-firestore-search.d.ts +0 -29
  119. package/dist/react/search/use-firestore-search.d.ts.map +1 -1
  120. package/dist/react/search/use-firestore-search.js +3 -41
  121. package/dist/react/search/use-firestore-search.js.map +1 -1
  122. package/dist/react/session-mutation.d.ts +27 -0
  123. package/dist/react/session-mutation.d.ts.map +1 -0
  124. package/dist/react/session-mutation.js +150 -0
  125. package/dist/react/session-mutation.js.map +1 -0
  126. package/dist/react/use-read-retry-state.d.ts +1 -21
  127. package/dist/react/use-read-retry-state.d.ts.map +1 -1
  128. package/dist/react/use-read-retry-state.js +2 -21
  129. package/dist/react/use-read-retry-state.js.map +1 -1
  130. package/dist/search/rule.d.ts +0 -6
  131. package/dist/search/rule.d.ts.map +1 -1
  132. package/dist/search/rule.js +0 -6
  133. package/dist/search/rule.js.map +1 -1
  134. package/dist/search/types.d.ts +1 -13
  135. package/dist/search/types.d.ts.map +1 -1
  136. package/dist/search/types.js.map +1 -1
  137. package/package.json +4 -4
@@ -2,10 +2,6 @@ import { type UseQueryResult } from '@tanstack/react-query';
2
2
  import { type DocumentData } from 'firebase/firestore';
3
3
  import type { WithId } from '../../firestore/types.js';
4
4
  import type { FirestorePaginatedOptions, PaginatedPage } from './types.js';
5
- /**
6
- * Return type for useFirestorePaginated hook. `data` is the displayed page's rows; the
7
- * page's cache entry (rows, cursor, has-more) lives at `paginatedPageKey(queryKey, page)`.
8
- */
9
5
  export type UseFirestorePaginatedResult<T> = Omit<UseQueryResult<PaginatedPage<WithId<T>>, Error>, 'data'> & {
10
6
  data: WithId<T>[] | undefined;
11
7
  page: number;
@@ -16,31 +12,5 @@ export type UseFirestorePaginatedResult<T> = Omit<UseQueryResult<PaginatedPage<W
16
12
  nextPage: () => void;
17
13
  prevPage: () => void;
18
14
  };
19
- /**
20
- * Page-based pagination for Firestore collections (Previous / Next, one page at a time).
21
- *
22
- * Each page is ONE cache entry at `[...queryKey, 'page', n]` holding its rows, its last
23
- * row as the next page's cursor, and whether a further page exists — read with a one-row
24
- * look-ahead, so `hasNextPage` is false exactly when nothing follows the displayed page.
25
- * Page n reads page n-1's cursor from the cache (loading the chain first if it is
26
- * missing) and records it as `after`. A displayed page whose `after` no longer matches
27
- * page n-1's cached cursor (page n-1 was re-read and its last row moved) is re-read before
28
- * it is shown, so every instance, remount, and refetch of a key agrees on where a page
29
- * starts. The page number belongs to the query identity (path, key, constraints, page
30
- * size): a new identity renders `initialPage` in its first render.
31
- *
32
- * `queryKey` must encode everything that changes the read — path, filters, ordering, and
33
- * page size — because the cache entries are shared by key.
34
- *
35
- * @example
36
- * ```tsx
37
- * const { data, page, nextPage, prevPage, hasNextPage, hasPrevPage } = useFirestorePaginated<Task>({
38
- * collectionPath: 'tasks',
39
- * queryKey: ['tasks', 'active', { pageSize: 10 }],
40
- * constraints: [where('status', '==', 'active'), orderBy('createdAt', 'desc')],
41
- * pageSize: 10,
42
- * });
43
- * ```
44
- */
45
15
  export declare function useFirestorePaginated<T extends DocumentData = DocumentData>({ collectionPath, queryKey, constraints, pageSize, initialPage, enabled, staleTime, gcTime, refetchInterval, select, }: FirestorePaginatedOptions<T>): UseFirestorePaginatedResult<T>;
46
16
  //# sourceMappingURL=use-firestore-paginated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-firestore-paginated.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/use-firestore-paginated.ts"],"names":[],"mappings":"AAGA,OAAO,EAA4B,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAML,KAAK,YAAY,EAElB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,KAAK,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAI3E;;;GAGG;AACH,MAAM,MAAM,2BAA2B,CAAC,CAAC,IAAI,IAAI,CAC/C,cAAc,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAC/C,MAAM,CACP,GAAG;IACF,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,CAAC;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;IACrB,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,QAAQ,EAAE,MAAM,IAAI,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,EAAE,EAC3E,cAAc,EACd,QAAQ,EACR,WAAgB,EAChB,QAA4B,EAC5B,WAAe,EACf,OAAc,EACd,SAAS,EACT,MAAM,EACN,eAAe,EACf,MAAM,GACP,EAAE,yBAAyB,CAAC,CAAC,CAAC,GAAG,2BAA2B,CAAC,CAAC,CAAC,CAsH/D"}
1
+ {"version":3,"file":"use-firestore-paginated.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/use-firestore-paginated.ts"],"names":[],"mappings":"AAGA,OAAO,EAA4B,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAML,KAAK,YAAY,EAElB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,KAAK,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAI3E,MAAM,MAAM,2BAA2B,CAAC,CAAC,IAAI,IAAI,CAC/C,cAAc,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAC/C,MAAM,CACP,GAAG;IACF,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,CAAC;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;IACrB,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,QAAQ,EAAE,MAAM,IAAI,CAAC;CACtB,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,EAAE,EAC3E,cAAc,EACd,QAAQ,EACR,WAAgB,EAChB,QAA4B,EAC5B,WAAe,EACf,OAAc,EACd,SAAS,EACT,MAAM,EACN,eAAe,EACf,MAAM,GACP,EAAE,yBAAyB,CAAC,CAAC,CAAC,GAAG,2BAA2B,CAAC,CAAC,CAAC,CAiH/D"}
@@ -5,32 +5,6 @@ import { collection, query, getDocs, limit, startAfter, } from 'firebase/firesto
5
5
  import { useFirestoreDb } from './context.js';
6
6
  import { paginatedPageKey } from '../cache-helpers.js';
7
7
  const DEFAULT_PAGE_SIZE = 10;
8
- /**
9
- * Page-based pagination for Firestore collections (Previous / Next, one page at a time).
10
- *
11
- * Each page is ONE cache entry at `[...queryKey, 'page', n]` holding its rows, its last
12
- * row as the next page's cursor, and whether a further page exists — read with a one-row
13
- * look-ahead, so `hasNextPage` is false exactly when nothing follows the displayed page.
14
- * Page n reads page n-1's cursor from the cache (loading the chain first if it is
15
- * missing) and records it as `after`. A displayed page whose `after` no longer matches
16
- * page n-1's cached cursor (page n-1 was re-read and its last row moved) is re-read before
17
- * it is shown, so every instance, remount, and refetch of a key agrees on where a page
18
- * starts. The page number belongs to the query identity (path, key, constraints, page
19
- * size): a new identity renders `initialPage` in its first render.
20
- *
21
- * `queryKey` must encode everything that changes the read — path, filters, ordering, and
22
- * page size — because the cache entries are shared by key.
23
- *
24
- * @example
25
- * ```tsx
26
- * const { data, page, nextPage, prevPage, hasNextPage, hasPrevPage } = useFirestorePaginated<Task>({
27
- * collectionPath: 'tasks',
28
- * queryKey: ['tasks', 'active', { pageSize: 10 }],
29
- * constraints: [where('status', '==', 'active'), orderBy('createdAt', 'desc')],
30
- * pageSize: 10,
31
- * });
32
- * ```
33
- */
34
8
  export function useFirestorePaginated({ collectionPath, queryKey, constraints = [], pageSize = DEFAULT_PAGE_SIZE, initialPage = 1, enabled = true, staleTime, gcTime, refetchInterval, select, }) {
35
9
  const db = useFirestoreDb();
36
10
  const queryClient = useQueryClient();
@@ -68,8 +42,7 @@ export function useFirestorePaginated({ collectionPath, queryKey, constraints =
68
42
  after: cursor?.id ?? null,
69
43
  };
70
44
  },
71
- // queryKey and constraints are captured through their serialized identity.
72
- // eslint-disable-next-line react-hooks/exhaustive-deps
45
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- queryKey and constraints are captured through their serialized identity
73
46
  [db, queryClient, identity, selectRef]);
74
47
  const queryResult = useQuery({
75
48
  queryKey: paginatedPageKey(queryKey, page),
@@ -79,9 +52,6 @@ export function useFirestorePaginated({ collectionPath, queryKey, constraints =
79
52
  gcTime,
80
53
  refetchInterval,
81
54
  });
82
- // The page before the displayed one, observed from the cache only (never fetched here).
83
- // When it is re-read and its last row moves, the displayed entry no longer starts where the
84
- // chain says it must: it is re-read before it is shown as current.
85
55
  const previousPage = useQuery({
86
56
  queryKey: paginatedPageKey(queryKey, Math.max(1, page - 1)),
87
57
  queryFn: () => fetchPage(Math.max(1, page - 1)),
@@ -112,8 +82,7 @@ export function useFirestorePaginated({ collectionPath, queryKey, constraints =
112
82
  return;
113
83
  setPageState({ identity, page: next });
114
84
  },
115
- // queryKey is captured through its serialized identity.
116
- // eslint-disable-next-line react-hooks/exhaustive-deps
85
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- queryKey is captured through its serialized identity
117
86
  [page, hasNextPage, identity, queryClient]);
118
87
  const nextPage = useCallback(() => setPage(page + 1), [page, setPage]);
119
88
  const prevPage = useCallback(() => setPage(page - 1), [page, setPage]);
@@ -1 +1 @@
1
- {"version":3,"file":"use-firestore-paginated.js","sourceRoot":"","sources":["../../../src/react/firestore/use-firestore-paginated.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAuB,MAAM,uBAAuB,CAAC;AACtF,OAAO,EACL,UAAU,EACV,KAAK,EACL,OAAO,EACP,KAAK,EACL,UAAU,GAGX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAoB7B;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,UAAU,qBAAqB,CAAwC,EAC3E,cAAc,EACd,QAAQ,EACR,WAAW,GAAG,EAAE,EAChB,QAAQ,GAAG,iBAAiB,EAC5B,WAAW,GAAG,CAAC,EACf,OAAO,GAAG,IAAI,EACd,SAAS,EACT,MAAM,EACN,eAAe,EACf,MAAM,GACuB;IAC7B,MAAM,EAAE,GAAG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,EAAE,MAAM,EAAE,SAAkB,EAAE;YACpF,CAAC,CAAC,EAAE,CAAC;QACP,IAAI,EAAE,KAAK,EAAE,KAAK;QAClB,IAAI;QACJ,QAAQ;QACR,WAAW;QACX,WAAW,EAAE,IAAI,GAAG,CAAC;QACrB,OAAO;QACP,QAAQ;QACR,QAAQ;KACyB,CAAC;AACtC,CAAC","sourcesContent":["'use client';\n\nimport { useState, useCallback, useEffect, useRef } from 'react';\nimport { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';\nimport {\n collection,\n query,\n getDocs,\n limit,\n startAfter,\n type DocumentData,\n type DocumentSnapshot,\n} from 'firebase/firestore';\nimport { useFirestoreDb } from './context.js';\nimport { paginatedPageKey } from '../cache-helpers.js';\nimport type { WithId } from '../../firestore/types.js';\nimport type { FirestorePaginatedOptions, PaginatedPage } from './types.js';\n\nconst DEFAULT_PAGE_SIZE = 10;\n\n/**\n * Return type for useFirestorePaginated hook. `data` is the displayed page's rows; the\n * page's cache entry (rows, cursor, has-more) lives at `paginatedPageKey(queryKey, page)`.\n */\nexport type UseFirestorePaginatedResult<T> = Omit<\n UseQueryResult<PaginatedPage<WithId<T>>, Error>,\n 'data'\n> & {\n data: WithId<T>[] | undefined;\n page: number;\n pageSize: number;\n hasNextPage: boolean;\n hasPrevPage: boolean;\n setPage: (page: number) => void;\n nextPage: () => void;\n prevPage: () => void;\n};\n\n/**\n * Page-based pagination for Firestore collections (Previous / Next, one page at a time).\n *\n * Each page is ONE cache entry at `[...queryKey, 'page', n]` holding its rows, its last\n * row as the next page's cursor, and whether a further page exists — read with a one-row\n * look-ahead, so `hasNextPage` is false exactly when nothing follows the displayed page.\n * Page n reads page n-1's cursor from the cache (loading the chain first if it is\n * missing) and records it as `after`. A displayed page whose `after` no longer matches\n * page n-1's cached cursor (page n-1 was re-read and its last row moved) is re-read before\n * it is shown, so every instance, remount, and refetch of a key agrees on where a page\n * starts. The page number belongs to the query identity (path, key, constraints, page\n * size): a new identity renders `initialPage` in its first render.\n *\n * `queryKey` must encode everything that changes the read — path, filters, ordering, and\n * page size — because the cache entries are shared by key.\n *\n * @example\n * ```tsx\n * const { data, page, nextPage, prevPage, hasNextPage, hasPrevPage } = useFirestorePaginated<Task>({\n * collectionPath: 'tasks',\n * queryKey: ['tasks', 'active', { pageSize: 10 }],\n * constraints: [where('status', '==', 'active'), orderBy('createdAt', 'desc')],\n * pageSize: 10,\n * });\n * ```\n */\nexport function useFirestorePaginated<T extends DocumentData = DocumentData>({\n collectionPath,\n queryKey,\n constraints = [],\n pageSize = DEFAULT_PAGE_SIZE,\n initialPage = 1,\n enabled = true,\n staleTime,\n gcTime,\n refetchInterval,\n select,\n}: FirestorePaginatedOptions<T>): UseFirestorePaginatedResult<T> {\n const db = useFirestoreDb();\n const queryClient = useQueryClient();\n\n const queryKeyMemo = JSON.stringify(queryKey);\n const constraintsMemo = JSON.stringify(constraints);\n const identity = JSON.stringify([collectionPath, queryKeyMemo, constraintsMemo, pageSize]);\n const firstPage = Math.max(1, Math.floor(initialPage));\n\n const [pageState, setPageState] = useState(() => ({ identity, page: firstPage }));\n const page = pageState.identity === identity ? pageState.page : firstPage;\n\n const selectRef = useRef(select);\n selectRef.current = select;\n\n const fetchPage = useCallback(\n async (n: number): Promise<PaginatedPage<WithId<T>>> => {\n let cursor: DocumentSnapshot | null = null;\n if (n > 1) {\n const previous = await queryClient.ensureQueryData<PaginatedPage<WithId<T>>>({\n queryKey: paginatedPageKey(queryKey, n - 1),\n queryFn: () => fetchPage(n - 1),\n });\n if (!previous.hasMore || !previous.cursor) {\n return { items: [], cursor: null, hasMore: false, after: previous.cursor?.id ?? null };\n }\n cursor = previous.cursor;\n }\n const q = query(\n collection(db, collectionPath),\n ...constraints,\n ...(cursor ? [startAfter(cursor)] : []),\n limit(pageSize + 1),\n );\n const snapshot = await getDocs(q);\n const pageDocs = snapshot.docs.slice(0, pageSize);\n return {\n items: pageDocs.map((docSnap) => {\n const dataWithId = { id: docSnap.id, ...docSnap.data() };\n const mapped = selectRef.current ? selectRef.current(dataWithId) : dataWithId;\n return mapped as WithId<T>;\n }),\n cursor: pageDocs[pageDocs.length - 1] ?? null,\n hasMore: snapshot.docs.length > pageSize,\n after: cursor?.id ?? null,\n };\n },\n // queryKey and constraints are captured through their serialized identity.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [db, queryClient, identity, selectRef],\n );\n\n const queryResult = useQuery({\n queryKey: paginatedPageKey(queryKey, page),\n queryFn: () => fetchPage(page),\n enabled,\n staleTime,\n gcTime,\n refetchInterval,\n });\n\n // The page before the displayed one, observed from the cache only (never fetched here).\n // When it is re-read and its last row moves, the displayed entry no longer starts where the\n // chain says it must: it is re-read before it is shown as current.\n const previousPage = useQuery({\n queryKey: paginatedPageKey(queryKey, Math.max(1, page - 1)),\n queryFn: () => fetchPage(Math.max(1, page - 1)),\n enabled: false,\n });\n const cachedEntry = queryResult.data;\n const outOfChain =\n page > 1 &&\n cachedEntry !== undefined &&\n (previousPage.data === undefined ||\n cachedEntry.after !== (previousPage.data.cursor?.id ?? null));\n const { refetch, isFetching } = queryResult;\n useEffect(() => {\n if (enabled && outOfChain && !isFetching) void refetch();\n }, [enabled, outOfChain, isFetching, refetch]);\n\n const entry = outOfChain ? undefined : cachedEntry;\n const hasNextPage = Boolean(entry?.hasMore && entry.cursor);\n\n const setPage = useCallback(\n (target: number) => {\n const next = Math.floor(target);\n if (next < 1 || next === page) return;\n if (next > page + 1) {\n const before = queryClient.getQueryData<PaginatedPage<unknown>>(\n paginatedPageKey(queryKey, next - 1),\n );\n if (!before?.hasMore) return;\n }\n if (next === page + 1 && !hasNextPage) return;\n setPageState({ identity, page: next });\n },\n // queryKey is captured through its serialized identity.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [page, hasNextPage, identity, queryClient],\n );\n\n const nextPage = useCallback(() => setPage(page + 1), [page, setPage]);\n const prevPage = useCallback(() => setPage(page - 1), [page, setPage]);\n\n return {\n ...queryResult,\n ...(outOfChain\n ? { isLoading: true, isPending: true, isSuccess: false, status: 'pending' as const }\n : {}),\n data: entry?.items,\n page,\n pageSize,\n hasNextPage,\n hasPrevPage: page > 1,\n setPage,\n nextPage,\n prevPage,\n } as UseFirestorePaginatedResult<T>;\n}\n"]}
1
+ {"version":3,"file":"use-firestore-paginated.js","sourceRoot":"","sources":["../../../src/react/firestore/use-firestore-paginated.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAuB,MAAM,uBAAuB,CAAC;AACtF,OAAO,EACL,UAAU,EACV,KAAK,EACL,OAAO,EACP,KAAK,EACL,UAAU,GAGX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAgB7B,MAAM,UAAU,qBAAqB,CAAwC,EAC3E,cAAc,EACd,QAAQ,EACR,WAAW,GAAG,EAAE,EAChB,QAAQ,GAAG,iBAAiB,EAC5B,WAAW,GAAG,CAAC,EACf,OAAO,GAAG,IAAI,EACd,SAAS,EACT,MAAM,EACN,eAAe,EACf,MAAM,GACuB;IAC7B,MAAM,EAAE,GAAG,cAAc,EAAE,CAAC;IAC5B,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IAErC,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;IACpD,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,cAAc,EAAE,YAAY,EAAE,eAAe,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC3F,MAAM,SAAS,GAAG,IAAI,CAAC,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C,YAAY,CACrC,gBAAgB,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,CAAC,CACrC,CAAC;YACF,IAAI,CAAC,MAAM,EAAE,OAAO;gBAAE,OAAO;QAC/B,CAAC;QACD,IAAI,IAAI,KAAK,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW;YAAE,OAAO;QAC9C,YAAY,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;IACD,+GAA+G;IAC/G,CAAC,IAAI,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,CAAC,CAC3C,CAAC;IAEF,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACvE,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IAEvE,OAAO;QACL,GAAG,WAAW;QACd,GAAG,CAAC,UAAU;YACZ,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,SAAkB,EAAE;YACpF,CAAC,CAAC,EAAE,CAAC;QACP,IAAI,EAAE,KAAK,EAAE,KAAK;QAClB,IAAI;QACJ,QAAQ;QACR,WAAW;QACX,WAAW,EAAE,IAAI,GAAG,CAAC;QACrB,OAAO;QACP,QAAQ;QACR,QAAQ;KACyB,CAAC;AACtC,CAAC","sourcesContent":["'use client';\n\nimport { useState, useCallback, useEffect, useRef } from 'react';\nimport { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';\nimport {\n collection,\n query,\n getDocs,\n limit,\n startAfter,\n type DocumentData,\n type DocumentSnapshot,\n} from 'firebase/firestore';\nimport { useFirestoreDb } from './context.js';\nimport { paginatedPageKey } from '../cache-helpers.js';\nimport type { WithId } from '../../firestore/types.js';\nimport type { FirestorePaginatedOptions, PaginatedPage } from './types.js';\n\nconst DEFAULT_PAGE_SIZE = 10;\n\nexport type UseFirestorePaginatedResult<T> = Omit<\n UseQueryResult<PaginatedPage<WithId<T>>, Error>,\n 'data'\n> & {\n data: WithId<T>[] | undefined;\n page: number;\n pageSize: number;\n hasNextPage: boolean;\n hasPrevPage: boolean;\n setPage: (page: number) => void;\n nextPage: () => void;\n prevPage: () => void;\n};\n\nexport function useFirestorePaginated<T extends DocumentData = DocumentData>({\n collectionPath,\n queryKey,\n constraints = [],\n pageSize = DEFAULT_PAGE_SIZE,\n initialPage = 1,\n enabled = true,\n staleTime,\n gcTime,\n refetchInterval,\n select,\n}: FirestorePaginatedOptions<T>): UseFirestorePaginatedResult<T> {\n const db = useFirestoreDb();\n const queryClient = useQueryClient();\n\n const queryKeyMemo = JSON.stringify(queryKey);\n const constraintsMemo = JSON.stringify(constraints);\n const identity = JSON.stringify([collectionPath, queryKeyMemo, constraintsMemo, pageSize]);\n const firstPage = Math.max(1, Math.floor(initialPage));\n\n const [pageState, setPageState] = useState(() => ({ identity, page: firstPage }));\n const page = pageState.identity === identity ? pageState.page : firstPage;\n\n const selectRef = useRef(select);\n selectRef.current = select;\n\n const fetchPage = useCallback(\n async (n: number): Promise<PaginatedPage<WithId<T>>> => {\n let cursor: DocumentSnapshot | null = null;\n if (n > 1) {\n const previous = await queryClient.ensureQueryData<PaginatedPage<WithId<T>>>({\n queryKey: paginatedPageKey(queryKey, n - 1),\n queryFn: () => fetchPage(n - 1),\n });\n if (!previous.hasMore || !previous.cursor) {\n return { items: [], cursor: null, hasMore: false, after: previous.cursor?.id ?? null };\n }\n cursor = previous.cursor;\n }\n const q = query(\n collection(db, collectionPath),\n ...constraints,\n ...(cursor ? [startAfter(cursor)] : []),\n limit(pageSize + 1),\n );\n const snapshot = await getDocs(q);\n const pageDocs = snapshot.docs.slice(0, pageSize);\n return {\n items: pageDocs.map((docSnap) => {\n const dataWithId = { id: docSnap.id, ...docSnap.data() };\n const mapped = selectRef.current ? selectRef.current(dataWithId) : dataWithId;\n return mapped as WithId<T>;\n }),\n cursor: pageDocs[pageDocs.length - 1] ?? null,\n hasMore: snapshot.docs.length > pageSize,\n after: cursor?.id ?? null,\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- queryKey and constraints are captured through their serialized identity\n [db, queryClient, identity, selectRef],\n );\n\n const queryResult = useQuery({\n queryKey: paginatedPageKey(queryKey, page),\n queryFn: () => fetchPage(page),\n enabled,\n staleTime,\n gcTime,\n refetchInterval,\n });\n\n const previousPage = useQuery({\n queryKey: paginatedPageKey(queryKey, Math.max(1, page - 1)),\n queryFn: () => fetchPage(Math.max(1, page - 1)),\n enabled: false,\n });\n const cachedEntry = queryResult.data;\n const outOfChain =\n page > 1 &&\n cachedEntry !== undefined &&\n (previousPage.data === undefined ||\n cachedEntry.after !== (previousPage.data.cursor?.id ?? null));\n const { refetch, isFetching } = queryResult;\n useEffect(() => {\n if (enabled && outOfChain && !isFetching) void refetch();\n }, [enabled, outOfChain, isFetching, refetch]);\n\n const entry = outOfChain ? undefined : cachedEntry;\n const hasNextPage = Boolean(entry?.hasMore && entry.cursor);\n\n const setPage = useCallback(\n (target: number) => {\n const next = Math.floor(target);\n if (next < 1 || next === page) return;\n if (next > page + 1) {\n const before = queryClient.getQueryData<PaginatedPage<unknown>>(\n paginatedPageKey(queryKey, next - 1),\n );\n if (!before?.hasMore) return;\n }\n if (next === page + 1 && !hasNextPage) return;\n setPageState({ identity, page: next });\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- queryKey is captured through its serialized identity\n [page, hasNextPage, identity, queryClient],\n );\n\n const nextPage = useCallback(() => setPage(page + 1), [page, setPage]);\n const prevPage = useCallback(() => setPage(page - 1), [page, setPage]);\n\n return {\n ...queryResult,\n ...(outOfChain\n ? { isLoading: true, isPending: true, isSuccess: false, status: 'pending' as const }\n : {}),\n data: entry?.items,\n page,\n pageSize,\n hasNextPage,\n hasPrevPage: page > 1,\n setPage,\n nextPage,\n prevPage,\n } as UseFirestorePaginatedResult<T>;\n}\n"]}
@@ -1,150 +1,28 @@
1
1
  import type { Firestore } from 'firebase/firestore';
2
2
  import type { BatchFirestoreDocOutcome } from '../../firestore/types.js';
3
- /** Transport used to resolve an id in one-shot mode. */
4
3
  export type BatchFirestoreDocsTransport = 'batch' | 'get';
5
4
  export type BatchFirestoreDocsOptions = {
6
- /**
7
- * Firestore instance to use for queries
8
- */
9
5
  db: Firestore;
10
- /**
11
- * Full collection path (e.g., 'publicUsers', 'entities/public')
12
- */
13
6
  collectionPath: string;
14
- /**
15
- * Array of document IDs to fetch
16
- */
17
7
  ids: string[];
18
- /**
19
- * Query key prefix for individual document cache entries
20
- * Each document is cached as [queryKeyPrefix, docId]
21
- * @example 'publicUser' -> ['publicUser', 'user123']
22
- */
23
8
  queryKeyPrefix: string;
24
- /**
25
- * Time in milliseconds a PRESENT document stays fresh (default: 30 minutes).
26
- * An absent document uses `absentStaleTime` instead.
27
- */
28
9
  staleTime?: number;
29
- /**
30
- * Time in milliseconds to keep unused data in cache (default: 1 hour)
31
- */
32
10
  gcTime?: number;
33
- /**
34
- * Whether queries should be enabled (default: true)
35
- */
36
11
  enabled?: boolean;
37
- /**
38
- * Real-time mode (default: false). When true, each id is resolved via a shared,
39
- * reference-counted `onSnapshot` listener instead of a one-shot read:
40
- * - a missing doc caches `null` (negative caching) and resolves the instant it appears,
41
- * - identity edits propagate live, and every browser tab stays consistent,
42
- * - `staleTime` is irrelevant (listeners keep the cache fresh) and `refetch()` is a no-op.
43
- * Initial read cost matches the one-shot path; listeners then stay open while mounted.
44
- * Use for small, frequently-rendered, change-sensitive docs owned by the signed-in user.
45
- */
46
12
  subscribe?: boolean;
47
- /**
48
- * One-shot transport (default: `'batch'`).
49
- *
50
- * - `'batch'` — ids enqueued in the same microtask are coalesced into
51
- * `where(documentId(), 'in', …)` queries of at most `FIRESTORE_IN_FILTER_LIMIT` (firebase-helpers) ids each. Fewest round-trips.
52
- * - `'get'` — one `getDoc` per id, run concurrently. Required for a collection whose
53
- * Firestore rules gate reads on `resource.data`: an unconstrained id-list query is
54
- * denied WHOLESALE there, while per-document gets are evaluated per document, so one
55
- * unreadable id errors alone instead of failing every id with it. On such a collection
56
- * a get against a nonexistent doc is also denied, so "absent" and "hidden" are the same
57
- * client-visible signal — the id surfaces as that query's error, never as a null.
58
- */
13
+ /** `'get'` is required where rules gate reads on `resource.data`: there an id-list query is denied wholesale. */
59
14
  transport?: BatchFirestoreDocsTransport;
60
- /**
61
- * Time in milliseconds an ABSENT (`null`) result stays fresh (default: 30 seconds).
62
- * Deliberately much shorter than `staleTime`: a missing doc is usually a doc that has
63
- * not been mirrored/created YET, and holding "missing" as fresh for the full staleTime
64
- * is what leaves a row blank long after the doc appears.
65
- */
66
15
  absentStaleTime?: number;
67
- /**
68
- * Backoff ladder (ms) for re-reading an id that resolved absent, one re-read per rung
69
- * per absence episode (default: {@link ABSENT_RETRY_DELAYS_MS}). Pass `[]` to ask for no
70
- * re-reads.
71
- *
72
- * The timer is per cache key, so many consumers of the same absent id still cost one
73
- * re-read per rung — and consumers that disagree combine by UNION, never by mount order:
74
- * the key polls if ANY mounted consumer wants polling, on the LONGEST ladder among them.
75
- * `[]` therefore only silences re-reads that no other mounted consumer asked for. The
76
- * effective ladder is recomputed on every mount and unmount; an episode already in
77
- * progress continues on the new ladder's remaining rungs, or stops if it is now empty.
78
- */
79
16
  absentRetryDelaysMs?: readonly number[];
80
17
  };
81
18
  export type BatchFirestoreDocsResult<T> = {
82
- /**
83
- * Map of docId -> document data.
84
- * Only includes documents that exist AND are currently readable: an id whose query is in
85
- * an error state is excluded, so a previously cached doc is never presented as readable
86
- * after access to it fails.
87
- */
88
19
  data: Record<string, T>;
89
- /**
90
- * True while any requested id has not resolved yet
91
- */
92
20
  isLoading: boolean;
93
- /**
94
- * True if any requested id is in an error state
95
- */
96
21
  isError: boolean;
97
- /**
98
- * First error across the requested ids, if any
99
- */
100
22
  error: Error | null;
101
- /**
102
- * One entry per requested id (empty ids and duplicates dropped): `loading`, `present` with
103
- * its data, `absent`, or `failed` with that id's own error. A multi-id consumer reads which
104
- * ids are missing and which failed here — `data` / `isError` / `error` are the aggregate
105
- * view and cannot tell them apart. The map, and each unchanged entry, keep their identity
106
- * across renders.
107
- */
108
23
  outcomes: Record<string, BatchFirestoreDocOutcome<T>>;
109
- /**
110
- * True while a read of an id whose last settled read failed is fetching or waiting for the
111
- * network — a retry of a failure. A first load, and the absence ladder's re-read of an id that
112
- * answered absent, never count. TanStack clears a never-answered id's error as its refetch
113
- * starts, so this is the running flag a retry state (`useReadRetryState`) is built from.
114
- */
115
24
  failedReadsRunning: boolean;
116
- /**
117
- * Refetch every requested id, cached ones included. A no-op in subscribe mode.
118
- */
119
25
  refetch: () => Promise<void>;
120
26
  };
121
- /**
122
- * Resolve many document ids into individually observed, individually cached React Query
123
- * entries at `[queryKeyPrefix, id]`.
124
- *
125
- * There is exactly ONE data cache: the per-id entries. Each id owns a real query with a
126
- * real `queryFn`, so exact-key invalidation, `refetchQueries({ type: 'active' })`, and
127
- * `refetchOnMount` all work on a single id the way they work on any other query — and the
128
- * returned `data` is derived reactively from those query results, never read imperatively.
129
- *
130
- * A nonexistent document resolves to `null` (negative caching) and is excluded from `data`;
131
- * an absent id is then re-read on a bounded ladder (see `absentRetryDelaysMs`) so a doc
132
- * that appears shortly afterwards shows up without an invalidation.
133
- *
134
- * Each id's own answer — loading, present, absent, or failed with its own error — is in
135
- * `outcomes`; the aggregate fields cannot tell an absent id from a failed one.
136
- *
137
- * @example
138
- * ```typescript
139
- * const { data: users, isLoading } = useBatchFirestoreDocs<PublicUser>({
140
- * db,
141
- * collectionPath: 'publicUsers',
142
- * ids: ['user1', 'user2', 'user3'],
143
- * queryKeyPrefix: 'publicUser',
144
- * staleTime: 30 * 60 * 1000,
145
- * });
146
- * // users = { user1: {...}, user2: {...}, user3: {...} }
147
- * ```
148
- */
149
27
  export declare function useBatchFirestoreDocs<T extends Record<string, any>>({ db, collectionPath, ids, queryKeyPrefix, staleTime, gcTime, enabled, subscribe, transport, absentStaleTime, absentRetryDelaysMs, }: BatchFirestoreDocsOptions): BatchFirestoreDocsResult<T>;
150
28
  //# sourceMappingURL=useBatchFirestoreDocs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useBatchFirestoreDocs.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/useBatchFirestoreDocs.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAIpD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AAGzE,wDAAwD;AACxD,MAAM,MAAM,2BAA2B,GAAG,OAAO,GAAG,KAAK,CAAC;AAE1D,MAAM,MAAM,yBAAyB,GAAG;IACtC;;OAEG;IACH,EAAE,EAAE,SAAS,CAAC;IAEd;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IAEvB;;OAEG;IACH,GAAG,EAAE,MAAM,EAAE,CAAC;IAEd;;;;OAIG;IACH,cAAc,EAAE,MAAM,CAAC;IAEvB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,EAAE,2BAA2B,CAAC;IAExC;;;;;OAKG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;;;;;;;;OAWG;IACH,mBAAmB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACzC,CAAC;AAEF,MAAM,MAAM,wBAAwB,CAAC,CAAC,IAAI;IACxC;;;;;OAKG;IACH,IAAI,EAAE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AAC,EAAE,MAAM,CAAC;IAEhB,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,iHAAiH;IACjH,SAAS,CAAC,EAAE,2BAA2B,CAAC;IAExC,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB,mBAAmB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACzC,CAAC;AAEF,MAAM,MAAM,wBAAwB,CAAC,CAAC,IAAI;IACxC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAExB,SAAS,EAAE,OAAO,CAAC;IAEnB,OAAO,EAAE,OAAO,CAAC;IAEjB,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IAEpB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC,CAAC,CAAC,CAAC;IAEtD,kBAAkB,EAAE,OAAO,CAAC;IAE5B,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B,CAAC;AA2CF,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,EACnE,EAAE,EACF,cAAc,EACd,GAAG,EACH,cAAc,EACd,SAA0B,EAC1B,MAAuB,EACvB,OAAc,EACd,SAAiB,EACjB,SAAmB,EACnB,eAA2B,EAC3B,mBAA4C,GAC7C,EAAE,yBAAyB,GAAG,wBAAwB,CAAC,CAAC,CAAC,CAiLzD"}
@@ -5,20 +5,31 @@ import { isListenerOwned, listenerErrorOf, subscribeDoc } from './doc-subscripti
5
5
  import { getDocLoader } from './batch-doc-loader.js';
6
6
  import { ABSENT_RETRY_DELAYS_MS, trackAbsentDoc } from './absence-scheduler.js';
7
7
  import { useReadRetryStates } from '../use-read-retry-state.js';
8
+ import { isPermissionDeniedError } from './resubscribe.js';
8
9
  const LOADING_OUTCOME = { status: 'loading' };
9
10
  const IDLE_SOURCE = { error: null, isFetching: false, isLoading: false };
10
11
  const ABSENT_OUTCOME = { status: 'absent' };
11
12
  function sameOutcome(a, b) {
12
13
  if (a.status !== b.status)
13
14
  return false;
14
- if (a.status === 'present')
15
- return a.data === b.data;
15
+ if (a.status === 'present') {
16
+ const other = b;
17
+ return (a.data === other.data &&
18
+ a.failure?.error === other.failure?.error &&
19
+ a.failure?.retrying === other.failure?.retrying);
20
+ }
16
21
  if (a.status === 'failed') {
17
22
  const other = b;
18
23
  return a.error === other.error && a.retrying === other.retrying;
19
24
  }
20
25
  return true;
21
26
  }
27
+ function failedOrHeld(value, error, retrying) {
28
+ if (value === null || value === undefined || isPermissionDeniedError(error)) {
29
+ return { status: 'failed', error, retrying };
30
+ }
31
+ return { status: 'present', data: value, failure: { error, retrying } };
32
+ }
22
33
  function shallowRecordEqual(a, b) {
23
34
  const aKeys = Object.keys(a);
24
35
  if (aKeys.length !== Object.keys(b).length)
@@ -29,50 +40,15 @@ function shallowRecordEqual(a, b) {
29
40
  }
30
41
  return true;
31
42
  }
32
- /**
33
- * Resolve many document ids into individually observed, individually cached React Query
34
- * entries at `[queryKeyPrefix, id]`.
35
- *
36
- * There is exactly ONE data cache: the per-id entries. Each id owns a real query with a
37
- * real `queryFn`, so exact-key invalidation, `refetchQueries({ type: 'active' })`, and
38
- * `refetchOnMount` all work on a single id the way they work on any other query — and the
39
- * returned `data` is derived reactively from those query results, never read imperatively.
40
- *
41
- * A nonexistent document resolves to `null` (negative caching) and is excluded from `data`;
42
- * an absent id is then re-read on a bounded ladder (see `absentRetryDelaysMs`) so a doc
43
- * that appears shortly afterwards shows up without an invalidation.
44
- *
45
- * Each id's own answer — loading, present, absent, or failed with its own error — is in
46
- * `outcomes`; the aggregate fields cannot tell an absent id from a failed one.
47
- *
48
- * @example
49
- * ```typescript
50
- * const { data: users, isLoading } = useBatchFirestoreDocs<PublicUser>({
51
- * db,
52
- * collectionPath: 'publicUsers',
53
- * ids: ['user1', 'user2', 'user3'],
54
- * queryKeyPrefix: 'publicUser',
55
- * staleTime: 30 * 60 * 1000,
56
- * });
57
- * // users = { user1: {...}, user2: {...}, user3: {...} }
58
- * ```
59
- */
60
43
  export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix, staleTime = 30 * 60 * 1000, gcTime = 60 * 60 * 1000, enabled = true, subscribe = false, transport = 'batch', absentStaleTime = 30 * 1000, absentRetryDelaysMs = ABSENT_RETRY_DELAYS_MS, }) {
61
44
  const queryClient = useQueryClient();
62
- // Stabilize ids reference to prevent cascading re-renders
63
45
  const idsKey = JSON.stringify(ids);
64
- // Deduplicate and filter out empty IDs
65
46
  const uniqueIds = useMemo(() => {
66
47
  const parsed = JSON.parse(idsKey);
67
48
  return Array.from(new Set(parsed.filter(Boolean)));
68
49
  }, [idsKey]);
69
- // ── Real-time subscribe mode ──────────────────────────────────────────────
70
- // Listener errors cannot surface through the per-id queries (they are disabled while
71
- // subscribed), so they are tracked here, per id, and merged into the returned result.
72
50
  const [subscribeErrors, setSubscribeErrors] = useState({});
73
- // Snapshot re-render trigger. The per-id query observers do notify on the listener's
74
- // cache write, but only on React Query's batched microtask; bumping state in the
75
- // snapshot callback keeps a landed snapshot visible in the SAME tick it arrives.
51
+ // Query observers notify on React Query's batched microtask; bumping state here shows a snapshot in the tick it lands.
76
52
  const [, setSnapshotVersion] = useState(0);
77
53
  const results = useQueries({
78
54
  queries: uniqueIds.map((id) => ({
@@ -82,10 +58,7 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
82
58
  const loaded = transport === 'get'
83
59
  ? await loader.loadOne(id, signal)
84
60
  : await loader.loadBatched(id, signal);
85
- // If a shared listener took ownership of this key while the read was in flight, the
86
- // listener's value is the newer truth — `onSnapshot` will not re-emit until the doc
87
- // changes, so returning the read result here would leave a stale value stuck. A listener
88
- // that errored left only a `null` placeholder; its error is the answer, never an absence.
61
+ // `onSnapshot` does not re-emit until the document changes, so a read that lands after a listener took the key yields to it.
89
62
  if (isListenerOwned(queryClient, queryKeyPrefix, id)) {
90
63
  const listenerError = listenerErrorOf(queryClient, queryKeyPrefix, id);
91
64
  if (listenerError)
@@ -97,9 +70,7 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
97
70
  return loaded;
98
71
  },
99
72
  enabled: enabled && !subscribe,
100
- // The consuming app's global default is `refetchOnMount: false`; these lookups opt
101
- // back in so a remount re-reads a STALE id (refetch-on-mount never fires on a fresh
102
- // one, so an all-cache-hit mount still costs nothing).
73
+ // Opts back into refetch-on-mount (the package default is off) so a remount re-reads a stale id.
103
74
  refetchOnMount: !subscribe,
104
75
  staleTime: subscribe
105
76
  ? Infinity
@@ -133,9 +104,6 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
133
104
  unsubscribe();
134
105
  };
135
106
  }, [uniqueIds, subscribe, enabled, collectionPath, queryKeyPrefix, queryClient, db]);
136
- // Bounded re-read ladder for ids that resolved absent. Registration is per cache key, so
137
- // overlapping consumers share one episode budget. The ladder is rebuilt from its own
138
- // serialized form so an inline array literal cannot re-register (and reset it) every render.
139
107
  const absentDelaysKey = absentRetryDelaysMs.join(',');
140
108
  const absentDelays = useMemo(() => absentDelaysKey.split(',').filter(Boolean).map(Number), [absentDelaysKey]);
141
109
  useEffect(() => {
@@ -147,14 +115,10 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
147
115
  release();
148
116
  };
149
117
  }, [uniqueIds, queryKeyPrefix, queryClient, absentDelays]);
150
- // The maps are rebuilt every render; the committed refs below hand back the last
151
- // COMMITTED objects while nothing changed, so consumers can depend on their identity. Only
152
- // the effect writes the refs, so a concurrent render React discards can never leave them
153
- // pointing at an uncommitted map.
118
+ // Only the effect writes these refs, so a concurrent render React discards never leaves them on an uncommitted map.
154
119
  const committedDataRef = useRef({});
155
120
  const committedOutcomesRef = useRef({});
156
- // Each id's one-shot failure is held through its retry: TanStack clears a never-answered
157
- // read's error as its refetch starts, which would turn the id's failure into `loading`.
121
+ // TanStack clears a never-answered read's error as its refetch starts, so the failure is held through the retry.
158
122
  const retryStates = useReadRetryStates(uniqueIds.map((id, index) => ({
159
123
  source: (results[index] ?? IDLE_SOURCE),
160
124
  queryKey: [queryKeyPrefix, id],
@@ -170,8 +134,6 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
170
134
  const id = uniqueIds[index];
171
135
  const result = results[index];
172
136
  let outcome = LOADING_OUTCOME;
173
- // A one-shot reader of a key a failed shared listener owns sees that listener's `null`
174
- // placeholder in the cache; the registry's error is what it stands for.
175
137
  const listenerError = (subscribe ? subscribeErrors[id] : undefined) ??
176
138
  listenerErrorOf(queryClient, queryKeyPrefix, id) ??
177
139
  undefined;
@@ -183,27 +145,28 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
183
145
  const retryState = retryStates[index];
184
146
  if (result?.isError)
185
147
  anyError ??= result.error;
148
+ const value = result?.data;
186
149
  if (retryState && retryState.error !== null) {
187
- outcome = { status: 'failed', error: retryState.error, retrying: retryState.isRetrying };
150
+ outcome = failedOrHeld(value, retryState.error, retryState.isRetrying);
188
151
  }
189
152
  else if (result) {
190
153
  if (result.isLoading)
191
154
  oneShotLoading = true;
192
- const value = result.data;
193
155
  if (value === undefined)
194
156
  anyUnresolved = true;
195
157
  if (listenerError) {
196
158
  anyListenerError ??= listenerError;
197
- outcome = { status: 'failed', error: listenerError, retrying: false };
159
+ outcome = failedOrHeld(value, listenerError, false);
198
160
  }
199
161
  else if (value === null) {
200
162
  outcome = ABSENT_OUTCOME;
201
163
  }
202
164
  else if (value !== undefined) {
203
- nextData[id] = value;
204
165
  outcome = { status: 'present', data: value };
205
166
  }
206
167
  }
168
+ if (outcome.status === 'present')
169
+ nextData[id] = outcome.data;
207
170
  const committed = committedOutcomesRef.current[id];
208
171
  nextOutcomes[id] = committed && sameOutcome(committed, outcome) ? committed : outcome;
209
172
  }
@@ -218,14 +181,10 @@ export function useBatchFirestoreDocs({ db, collectionPath, ids, queryKeyPrefix,
218
181
  committedOutcomesRef.current = outcomes;
219
182
  }, [data, outcomes]);
220
183
  const refetch = useCallback(async () => {
221
- // Subscribe mode owns its freshness through the shared listeners — refetching would
222
- // issue reads against disabled queries and race the listener's value.
223
184
  if (subscribe || !enabled)
224
185
  return;
225
186
  await Promise.all(uniqueIds.map((id) => queryClient.refetchQueries({ queryKey: [queryKeyPrefix, id], exact: true })));
226
187
  }, [uniqueIds, subscribe, enabled, queryClient, queryKeyPrefix]);
227
- // In subscribe mode "loading" means a subscribed id has no cache entry yet (`null`
228
- // counts as resolved-missing).
229
188
  const isLoading = subscribe ? enabled && anyUnresolved : oneShotLoading;
230
189
  return {
231
190
  data,
@@ -1 +1 @@
1
- {"version":3,"file":"useBatchFirestoreDocs.js","sourceRoot":"","sources":["../../../src/react/firestore/useBatchFirestoreDocs.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEnE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAwB,MAAM,4BAA4B,CAAC;AA2ItF,MAAM,eAAe,GAAG,EAAE,MAAM,EAAE,SAAS,EAAW,CAAC;AACvD,MAAM,WAAW,GAA2B,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;AACjG,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAW,CAAC;AAErD,SAAS,WAAW,CAAI,CAA8B,EAA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,IAAI,EAAE,CAAC,CAC5E,CACF,CAAC;IACJ,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;IAEjE,mFAAmF;IACnF,+BAA+B;IAC/B,MAAM,SAAS,GAAG,SAAS,CAAC,CAAC,CAAC,OAAO,IAAI,aAAa,CAAC,CAAC,CAAC,cAAc,CAAC;IAExE,OAAO;QACL,IAAI;QACJ,SAAS;QACT,OAAO,EAAE,QAAQ,KAAK,IAAI,IAAI,gBAAgB,KAAK,IAAI;QACvD,KAAK,EAAE,QAAQ,IAAI,gBAAgB;QACnC,QAAQ;QACR,kBAAkB;QAClB,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueries, useQueryClient } from '@tanstack/react-query';\nimport type { Firestore } from 'firebase/firestore';\nimport { isListenerOwned, listenerErrorOf, subscribeDoc } from './doc-subscription-registry.js';\nimport { getDocLoader } from './batch-doc-loader.js';\nimport { ABSENT_RETRY_DELAYS_MS, trackAbsentDoc } from './absence-scheduler.js';\nimport type { BatchFirestoreDocOutcome } from '../../firestore/types.js';\nimport { useReadRetryStates, type ReadRetrySource } from '../use-read-retry-state.js';\n\n/** Transport used to resolve an id in one-shot mode. */\nexport type BatchFirestoreDocsTransport = 'batch' | 'get';\n\nexport type BatchFirestoreDocsOptions = {\n /**\n * Firestore instance to use for queries\n */\n db: Firestore;\n\n /**\n * Full collection path (e.g., 'publicUsers', 'entities/public')\n */\n collectionPath: string;\n\n /**\n * Array of document IDs to fetch\n */\n ids: string[];\n\n /**\n * Query key prefix for individual document cache entries\n * Each document is cached as [queryKeyPrefix, docId]\n * @example 'publicUser' -> ['publicUser', 'user123']\n */\n queryKeyPrefix: string;\n\n /**\n * Time in milliseconds a PRESENT document stays fresh (default: 30 minutes).\n * An absent document uses `absentStaleTime` instead.\n */\n staleTime?: number;\n\n /**\n * Time in milliseconds to keep unused data in cache (default: 1 hour)\n */\n gcTime?: number;\n\n /**\n * Whether queries should be enabled (default: true)\n */\n enabled?: boolean;\n\n /**\n * Real-time mode (default: false). When true, each id is resolved via a shared,\n * reference-counted `onSnapshot` listener instead of a one-shot read:\n * - a missing doc caches `null` (negative caching) and resolves the instant it appears,\n * - identity edits propagate live, and every browser tab stays consistent,\n * - `staleTime` is irrelevant (listeners keep the cache fresh) and `refetch()` is a no-op.\n * Initial read cost matches the one-shot path; listeners then stay open while mounted.\n * Use for small, frequently-rendered, change-sensitive docs owned by the signed-in user.\n */\n subscribe?: boolean;\n\n /**\n * One-shot transport (default: `'batch'`).\n *\n * - `'batch'` — ids enqueued in the same microtask are coalesced into\n * `where(documentId(), 'in', …)` queries of at most `FIRESTORE_IN_FILTER_LIMIT` (firebase-helpers) ids each. Fewest round-trips.\n * - `'get'` — one `getDoc` per id, run concurrently. Required for a collection whose\n * Firestore rules gate reads on `resource.data`: an unconstrained id-list query is\n * denied WHOLESALE there, while per-document gets are evaluated per document, so one\n * unreadable id errors alone instead of failing every id with it. On such a collection\n * a get against a nonexistent doc is also denied, so \"absent\" and \"hidden\" are the same\n * client-visible signal — the id surfaces as that query's error, never as a null.\n */\n transport?: BatchFirestoreDocsTransport;\n\n /**\n * Time in milliseconds an ABSENT (`null`) result stays fresh (default: 30 seconds).\n * Deliberately much shorter than `staleTime`: a missing doc is usually a doc that has\n * not been mirrored/created YET, and holding \"missing\" as fresh for the full staleTime\n * is what leaves a row blank long after the doc appears.\n */\n absentStaleTime?: number;\n\n /**\n * Backoff ladder (ms) for re-reading an id that resolved absent, one re-read per rung\n * per absence episode (default: {@link ABSENT_RETRY_DELAYS_MS}). Pass `[]` to ask for no\n * re-reads.\n *\n * The timer is per cache key, so many consumers of the same absent id still cost one\n * re-read per rung — and consumers that disagree combine by UNION, never by mount order:\n * the key polls if ANY mounted consumer wants polling, on the LONGEST ladder among them.\n * `[]` therefore only silences re-reads that no other mounted consumer asked for. The\n * effective ladder is recomputed on every mount and unmount; an episode already in\n * progress continues on the new ladder's remaining rungs, or stops if it is now empty.\n */\n absentRetryDelaysMs?: readonly number[];\n};\n\nexport type BatchFirestoreDocsResult<T> = {\n /**\n * Map of docId -> document data.\n * Only includes documents that exist AND are currently readable: an id whose query is in\n * an error state is excluded, so a previously cached doc is never presented as readable\n * after access to it fails.\n */\n data: Record<string, T>;\n\n /**\n * True while any requested id has not resolved yet\n */\n isLoading: boolean;\n\n /**\n * True if any requested id is in an error state\n */\n isError: boolean;\n\n /**\n * First error across the requested ids, if any\n */\n error: Error | null;\n\n /**\n * One entry per requested id (empty ids and duplicates dropped): `loading`, `present` with\n * its data, `absent`, or `failed` with that id's own error. A multi-id consumer reads which\n * ids are missing and which failed here — `data` / `isError` / `error` are the aggregate\n * view and cannot tell them apart. The map, and each unchanged entry, keep their identity\n * across renders.\n */\n outcomes: Record<string, BatchFirestoreDocOutcome<T>>;\n\n /**\n * True while a read of an id whose last settled read failed is fetching or waiting for the\n * network — a retry of a failure. A first load, and the absence ladder's re-read of an id that\n * answered absent, never count. TanStack clears a never-answered id's error as its refetch\n * starts, so this is the running flag a retry state (`useReadRetryState`) is built from.\n */\n failedReadsRunning: boolean;\n\n /**\n * Refetch every requested id, cached ones included. A no-op in subscribe mode.\n */\n refetch: () => Promise<void>;\n};\n\nconst LOADING_OUTCOME = { status: 'loading' } as const;\nconst IDLE_SOURCE: ReadRetrySource<Error> = { error: null, isFetching: false, isLoading: false };\nconst ABSENT_OUTCOME = { status: 'absent' } as const;\n\nfunction sameOutcome<T>(a: BatchFirestoreDocOutcome<T>, b: BatchFirestoreDocOutcome<T>): boolean {\n if (a.status !== b.status) return false;\n if (a.status === 'present') return a.data === (b as { data: T }).data;\n if (a.status === 'failed') {\n const other = b as { error: Error; retrying: boolean };\n return a.error === other.error && a.retrying === other.retrying;\n }\n return true;\n}\n\nfunction shallowRecordEqual<T>(a: Record<string, T>, b: Record<string, T>): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if (!Object.prototype.hasOwnProperty.call(b, key) || a[key] !== b[key]) return false;\n }\n return true;\n}\n\n/**\n * Resolve many document ids into individually observed, individually cached React Query\n * entries at `[queryKeyPrefix, id]`.\n *\n * There is exactly ONE data cache: the per-id entries. Each id owns a real query with a\n * real `queryFn`, so exact-key invalidation, `refetchQueries({ type: 'active' })`, and\n * `refetchOnMount` all work on a single id the way they work on any other query — and the\n * returned `data` is derived reactively from those query results, never read imperatively.\n *\n * A nonexistent document resolves to `null` (negative caching) and is excluded from `data`;\n * an absent id is then re-read on a bounded ladder (see `absentRetryDelaysMs`) so a doc\n * that appears shortly afterwards shows up without an invalidation.\n *\n * Each id's own answer — loading, present, absent, or failed with its own error — is in\n * `outcomes`; the aggregate fields cannot tell an absent id from a failed one.\n *\n * @example\n * ```typescript\n * const { data: users, isLoading } = useBatchFirestoreDocs<PublicUser>({\n * db,\n * collectionPath: 'publicUsers',\n * ids: ['user1', 'user2', 'user3'],\n * queryKeyPrefix: 'publicUser',\n * staleTime: 30 * 60 * 1000,\n * });\n * // users = { user1: {...}, user2: {...}, user3: {...} }\n * ```\n */\nexport function useBatchFirestoreDocs<T extends Record<string, any>>({\n db,\n collectionPath,\n ids,\n queryKeyPrefix,\n staleTime = 30 * 60 * 1000,\n gcTime = 60 * 60 * 1000,\n enabled = true,\n subscribe = false,\n transport = 'batch',\n absentStaleTime = 30 * 1000,\n absentRetryDelaysMs = ABSENT_RETRY_DELAYS_MS,\n}: BatchFirestoreDocsOptions): BatchFirestoreDocsResult<T> {\n const queryClient = useQueryClient();\n\n // Stabilize ids reference to prevent cascading re-renders\n const idsKey = JSON.stringify(ids);\n\n // Deduplicate and filter out empty IDs\n const uniqueIds = useMemo(() => {\n const parsed: string[] = JSON.parse(idsKey);\n return Array.from(new Set(parsed.filter(Boolean)));\n }, [idsKey]);\n\n // ── Real-time subscribe mode ──────────────────────────────────────────────\n // Listener errors cannot surface through the per-id queries (they are disabled while\n // subscribed), so they are tracked here, per id, and merged into the returned result.\n const [subscribeErrors, setSubscribeErrors] = useState<Record<string, Error>>({});\n // Snapshot re-render trigger. The per-id query observers do notify on the listener's\n // cache write, but only on React Query's batched microtask; bumping state in the\n // snapshot callback keeps a landed snapshot visible in the SAME tick it arrives.\n const [, setSnapshotVersion] = useState(0);\n\n const results = useQueries({\n queries: uniqueIds.map((id) => ({\n queryKey: [queryKeyPrefix, id],\n queryFn: async ({ signal }: { signal: AbortSignal }): Promise<T | null> => {\n const loader = getDocLoader(queryClient, db, collectionPath);\n const loaded =\n transport === 'get'\n ? await loader.loadOne(id, signal)\n : await loader.loadBatched(id, signal);\n // If a shared listener took ownership of this key while the read was in flight, the\n // listener's value is the newer truth — `onSnapshot` will not re-emit until the doc\n // changes, so returning the read result here would leave a stale value stuck. A listener\n // that errored left only a `null` placeholder; its error is the answer, never an absence.\n if (isListenerOwned(queryClient, queryKeyPrefix, id)) {\n const listenerError = listenerErrorOf(queryClient, queryKeyPrefix, id);\n if (listenerError) throw listenerError;\n const owned = queryClient.getQueryData([queryKeyPrefix, id]);\n if (owned !== undefined) return owned as T | null;\n }\n return loaded as T | null;\n },\n enabled: enabled && !subscribe,\n // The consuming app's global default is `refetchOnMount: false`; these lookups opt\n // back in so a remount re-reads a STALE id (refetch-on-mount never fires on a fresh\n // one, so an all-cache-hit mount still costs nothing).\n refetchOnMount: !subscribe,\n staleTime: subscribe\n ? Infinity\n : (query: { state: { data: unknown } }) =>\n query.state.data === null ? absentStaleTime : staleTime,\n gcTime,\n })),\n });\n\n useEffect(() => {\n if (!subscribe || !enabled || uniqueIds.length === 0) return;\n setSubscribeErrors({});\n const unsubscribers = uniqueIds.map((id) =>\n subscribeDoc({\n queryClient,\n db,\n collectionPath,\n queryKeyPrefix,\n id,\n onUpdate: () => {\n setSubscribeErrors((errors) => {\n if (!(id in errors)) return errors;\n const { [id]: _cleared, ...rest } = errors;\n return rest;\n });\n setSnapshotVersion((version) => version + 1);\n },\n onError: (error) =>\n setSubscribeErrors((errors) =>\n errors[id] === error ? errors : { ...errors, [id]: error },\n ),\n }),\n );\n return () => {\n for (const unsubscribe of unsubscribers) unsubscribe();\n };\n }, [uniqueIds, subscribe, enabled, collectionPath, queryKeyPrefix, queryClient, db]);\n\n // Bounded re-read ladder for ids that resolved absent. Registration is per cache key, so\n // overlapping consumers share one episode budget. The ladder is rebuilt from its own\n // serialized form so an inline array literal cannot re-register (and reset it) every render.\n const absentDelaysKey = absentRetryDelaysMs.join(',');\n const absentDelays = useMemo(\n () => absentDelaysKey.split(',').filter(Boolean).map(Number),\n [absentDelaysKey],\n );\n\n useEffect(() => {\n if (uniqueIds.length === 0) return;\n const releases = uniqueIds.map((id) =>\n trackAbsentDoc({ queryClient, queryKey: [queryKeyPrefix, id], delays: absentDelays }),\n );\n return () => {\n for (const release of releases) release();\n };\n }, [uniqueIds, queryKeyPrefix, queryClient, absentDelays]);\n\n // The maps are rebuilt every render; the committed refs below hand back the last\n // COMMITTED objects while nothing changed, so consumers can depend on their identity. Only\n // the effect writes the refs, so a concurrent render React discards can never leave them\n // pointing at an uncommitted map.\n const committedDataRef = useRef<Record<string, T>>({});\n const committedOutcomesRef = useRef<Record<string, BatchFirestoreDocOutcome<T>>>({});\n\n // Each id's one-shot failure is held through its retry: TanStack clears a never-answered\n // read's error as its refetch starts, which would turn the id's failure into `loading`.\n const retryStates = useReadRetryStates(\n uniqueIds.map((id, index) => ({\n source: (results[index] ?? IDLE_SOURCE) as ReadRetrySource<Error>,\n queryKey: [queryKeyPrefix, id],\n })),\n );\n\n const nextData: Record<string, T> = {};\n const nextOutcomes: Record<string, BatchFirestoreDocOutcome<T>> = {};\n let anyError: Error | null = null;\n let anyListenerError: Error | null = null;\n let oneShotLoading = false;\n let anyUnresolved = false;\n let failedReadsRunning = false;\n\n for (let index = 0; index < uniqueIds.length; index += 1) {\n const id = uniqueIds[index];\n const result = results[index];\n let outcome: BatchFirestoreDocOutcome<T> = LOADING_OUTCOME;\n // A one-shot reader of a key a failed shared listener owns sees that listener's `null`\n // placeholder in the cache; the registry's error is what it stands for.\n const listenerError =\n (subscribe ? subscribeErrors[id] : undefined) ??\n listenerErrorOf(queryClient, queryKeyPrefix, id) ??\n undefined;\n if (\n result &&\n (result.isFetching || result.isPaused) &&\n result.errorUpdatedAt > result.dataUpdatedAt\n ) {\n failedReadsRunning = true;\n }\n const retryState = retryStates[index];\n if (result?.isError) anyError ??= result.error as Error;\n if (retryState && retryState.error !== null) {\n outcome = { status: 'failed', error: retryState.error, retrying: retryState.isRetrying };\n } else if (result) {\n if (result.isLoading) oneShotLoading = true;\n const value = result.data as T | null | undefined;\n if (value === undefined) anyUnresolved = true;\n if (listenerError) {\n anyListenerError ??= listenerError;\n outcome = { status: 'failed', error: listenerError, retrying: false };\n } else if (value === null) {\n outcome = ABSENT_OUTCOME;\n } else if (value !== undefined) {\n nextData[id] = value;\n outcome = { status: 'present', data: value };\n }\n }\n const committed = committedOutcomesRef.current[id];\n nextOutcomes[id] = committed && sameOutcome(committed, outcome) ? committed : outcome;\n }\n\n const data = shallowRecordEqual(committedDataRef.current, nextData)\n ? committedDataRef.current\n : nextData;\n const outcomes = shallowRecordEqual(committedOutcomesRef.current, nextOutcomes)\n ? committedOutcomesRef.current\n : nextOutcomes;\n\n useEffect(() => {\n committedDataRef.current = data;\n committedOutcomesRef.current = outcomes;\n }, [data, outcomes]);\n\n const refetch = useCallback(async () => {\n // Subscribe mode owns its freshness through the shared listeners — refetching would\n // issue reads against disabled queries and race the listener's value.\n if (subscribe || !enabled) return;\n await Promise.all(\n uniqueIds.map((id) =>\n queryClient.refetchQueries({ queryKey: [queryKeyPrefix, id], exact: true }),\n ),\n );\n }, [uniqueIds, subscribe, enabled, queryClient, queryKeyPrefix]);\n\n // In subscribe mode \"loading\" means a subscribed id has no cache entry yet (`null`\n // counts as resolved-missing).\n const isLoading = subscribe ? enabled && anyUnresolved : oneShotLoading;\n\n return {\n data,\n isLoading,\n isError: anyError !== null || anyListenerError !== null,\n error: anyError ?? anyListenerError,\n outcomes,\n failedReadsRunning,\n refetch,\n };\n}\n"]}
1
+ {"version":3,"file":"useBatchFirestoreDocs.js","sourceRoot":"","sources":["../../../src/react/firestore/useBatchFirestoreDocs.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEnE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAChG,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAwB,MAAM,4BAA4B,CAAC;AACtF,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AA6C3D,MAAM,eAAe,GAAG,EAAE,MAAM,EAAE,SAAS,EAAW,CAAC;AACvD,MAAM,WAAW,GAA2B,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;AACjG,MAAM,cAAc,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAW,CAAC;AAErD,SAAS,WAAW,CAAI,CAA8B,EAAE,CAA8B;IACpF,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,CAA+D,CAAC;QAC9E,OAAO,CACL,CAAC,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI;YACrB,CAAC,CAAC,OAAO,EAAE,KAAK,KAAK,KAAK,CAAC,OAAO,EAAE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EAAE,cAAc,CAAC,CAAC,CAAC;IAEjE,MAAM,SAAS,GAAG,SAAS,CAAC,CAAC,CAAC,OAAO,IAAI,aAAa,CAAC,CAAC,CAAC,cAAc,CAAC;IAExE,OAAO;QACL,IAAI;QACJ,SAAS;QACT,OAAO,EAAE,QAAQ,KAAK,IAAI,IAAI,gBAAgB,KAAK,IAAI;QACvD,KAAK,EAAE,QAAQ,IAAI,gBAAgB;QACnC,QAAQ;QACR,kBAAkB;QAClB,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueries, useQueryClient } from '@tanstack/react-query';\nimport type { Firestore } from 'firebase/firestore';\nimport { isListenerOwned, listenerErrorOf, subscribeDoc } from './doc-subscription-registry.js';\nimport { getDocLoader } from './batch-doc-loader.js';\nimport { ABSENT_RETRY_DELAYS_MS, trackAbsentDoc } from './absence-scheduler.js';\nimport type { BatchFirestoreDocOutcome } from '../../firestore/types.js';\nimport { useReadRetryStates, type ReadRetrySource } from '../use-read-retry-state.js';\nimport { isPermissionDeniedError } from './resubscribe.js';\n\nexport type BatchFirestoreDocsTransport = 'batch' | 'get';\n\nexport type BatchFirestoreDocsOptions = {\n db: Firestore;\n\n collectionPath: string;\n\n ids: string[];\n\n queryKeyPrefix: string;\n\n staleTime?: number;\n\n gcTime?: number;\n\n enabled?: boolean;\n\n subscribe?: boolean;\n\n /** `'get'` is required where rules gate reads on `resource.data`: there an id-list query is denied wholesale. */\n transport?: BatchFirestoreDocsTransport;\n\n absentStaleTime?: number;\n\n absentRetryDelaysMs?: readonly number[];\n};\n\nexport type BatchFirestoreDocsResult<T> = {\n data: Record<string, T>;\n\n isLoading: boolean;\n\n isError: boolean;\n\n error: Error | null;\n\n outcomes: Record<string, BatchFirestoreDocOutcome<T>>;\n\n failedReadsRunning: boolean;\n\n refetch: () => Promise<void>;\n};\n\nconst LOADING_OUTCOME = { status: 'loading' } as const;\nconst IDLE_SOURCE: ReadRetrySource<Error> = { error: null, isFetching: false, isLoading: false };\nconst ABSENT_OUTCOME = { status: 'absent' } as const;\n\nfunction sameOutcome<T>(a: BatchFirestoreDocOutcome<T>, b: BatchFirestoreDocOutcome<T>): boolean {\n if (a.status !== b.status) return false;\n if (a.status === 'present') {\n const other = b as { data: T; failure?: { error: Error; retrying: boolean } };\n return (\n a.data === other.data &&\n a.failure?.error === other.failure?.error &&\n a.failure?.retrying === other.failure?.retrying\n );\n }\n if (a.status === 'failed') {\n const other = b as { error: Error; retrying: boolean };\n return a.error === other.error && a.retrying === other.retrying;\n }\n return true;\n}\n\nfunction failedOrHeld<T>(\n value: T | null | undefined,\n error: Error,\n retrying: boolean,\n): BatchFirestoreDocOutcome<T> {\n if (value === null || value === undefined || isPermissionDeniedError(error)) {\n return { status: 'failed', error, retrying };\n }\n return { status: 'present', data: value, failure: { error, retrying } };\n}\n\nfunction shallowRecordEqual<T>(a: Record<string, T>, b: Record<string, T>): boolean {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if (!Object.prototype.hasOwnProperty.call(b, key) || a[key] !== b[key]) return false;\n }\n return true;\n}\n\nexport function useBatchFirestoreDocs<T extends Record<string, any>>({\n db,\n collectionPath,\n ids,\n queryKeyPrefix,\n staleTime = 30 * 60 * 1000,\n gcTime = 60 * 60 * 1000,\n enabled = true,\n subscribe = false,\n transport = 'batch',\n absentStaleTime = 30 * 1000,\n absentRetryDelaysMs = ABSENT_RETRY_DELAYS_MS,\n}: BatchFirestoreDocsOptions): BatchFirestoreDocsResult<T> {\n const queryClient = useQueryClient();\n\n const idsKey = JSON.stringify(ids);\n\n const uniqueIds = useMemo(() => {\n const parsed: string[] = JSON.parse(idsKey);\n return Array.from(new Set(parsed.filter(Boolean)));\n }, [idsKey]);\n\n const [subscribeErrors, setSubscribeErrors] = useState<Record<string, Error>>({});\n // Query observers notify on React Query's batched microtask; bumping state here shows a snapshot in the tick it lands.\n const [, setSnapshotVersion] = useState(0);\n\n const results = useQueries({\n queries: uniqueIds.map((id) => ({\n queryKey: [queryKeyPrefix, id],\n queryFn: async ({ signal }: { signal: AbortSignal }): Promise<T | null> => {\n const loader = getDocLoader(queryClient, db, collectionPath);\n const loaded =\n transport === 'get'\n ? await loader.loadOne(id, signal)\n : await loader.loadBatched(id, signal);\n // `onSnapshot` does not re-emit until the document changes, so a read that lands after a listener took the key yields to it.\n if (isListenerOwned(queryClient, queryKeyPrefix, id)) {\n const listenerError = listenerErrorOf(queryClient, queryKeyPrefix, id);\n if (listenerError) throw listenerError;\n const owned = queryClient.getQueryData([queryKeyPrefix, id]);\n if (owned !== undefined) return owned as T | null;\n }\n return loaded as T | null;\n },\n enabled: enabled && !subscribe,\n // Opts back into refetch-on-mount (the package default is off) so a remount re-reads a stale id.\n refetchOnMount: !subscribe,\n staleTime: subscribe\n ? Infinity\n : (query: { state: { data: unknown } }) =>\n query.state.data === null ? absentStaleTime : staleTime,\n gcTime,\n })),\n });\n\n useEffect(() => {\n if (!subscribe || !enabled || uniqueIds.length === 0) return;\n setSubscribeErrors({});\n const unsubscribers = uniqueIds.map((id) =>\n subscribeDoc({\n queryClient,\n db,\n collectionPath,\n queryKeyPrefix,\n id,\n onUpdate: () => {\n setSubscribeErrors((errors) => {\n if (!(id in errors)) return errors;\n const { [id]: _cleared, ...rest } = errors;\n return rest;\n });\n setSnapshotVersion((version) => version + 1);\n },\n onError: (error) =>\n setSubscribeErrors((errors) =>\n errors[id] === error ? errors : { ...errors, [id]: error },\n ),\n }),\n );\n return () => {\n for (const unsubscribe of unsubscribers) unsubscribe();\n };\n }, [uniqueIds, subscribe, enabled, collectionPath, queryKeyPrefix, queryClient, db]);\n\n const absentDelaysKey = absentRetryDelaysMs.join(',');\n const absentDelays = useMemo(\n () => absentDelaysKey.split(',').filter(Boolean).map(Number),\n [absentDelaysKey],\n );\n\n useEffect(() => {\n if (uniqueIds.length === 0) return;\n const releases = uniqueIds.map((id) =>\n trackAbsentDoc({ queryClient, queryKey: [queryKeyPrefix, id], delays: absentDelays }),\n );\n return () => {\n for (const release of releases) release();\n };\n }, [uniqueIds, queryKeyPrefix, queryClient, absentDelays]);\n\n // Only the effect writes these refs, so a concurrent render React discards never leaves them on an uncommitted map.\n const committedDataRef = useRef<Record<string, T>>({});\n const committedOutcomesRef = useRef<Record<string, BatchFirestoreDocOutcome<T>>>({});\n\n // TanStack clears a never-answered read's error as its refetch starts, so the failure is held through the retry.\n const retryStates = useReadRetryStates(\n uniqueIds.map((id, index) => ({\n source: (results[index] ?? IDLE_SOURCE) as ReadRetrySource<Error>,\n queryKey: [queryKeyPrefix, id],\n })),\n );\n\n const nextData: Record<string, T> = {};\n const nextOutcomes: Record<string, BatchFirestoreDocOutcome<T>> = {};\n let anyError: Error | null = null;\n let anyListenerError: Error | null = null;\n let oneShotLoading = false;\n let anyUnresolved = false;\n let failedReadsRunning = false;\n\n for (let index = 0; index < uniqueIds.length; index += 1) {\n const id = uniqueIds[index];\n const result = results[index];\n let outcome: BatchFirestoreDocOutcome<T> = LOADING_OUTCOME;\n const listenerError =\n (subscribe ? subscribeErrors[id] : undefined) ??\n listenerErrorOf(queryClient, queryKeyPrefix, id) ??\n undefined;\n if (\n result &&\n (result.isFetching || result.isPaused) &&\n result.errorUpdatedAt > result.dataUpdatedAt\n ) {\n failedReadsRunning = true;\n }\n const retryState = retryStates[index];\n if (result?.isError) anyError ??= result.error as Error;\n const value = result?.data as T | null | undefined;\n if (retryState && retryState.error !== null) {\n outcome = failedOrHeld(value, retryState.error, retryState.isRetrying);\n } else if (result) {\n if (result.isLoading) oneShotLoading = true;\n if (value === undefined) anyUnresolved = true;\n if (listenerError) {\n anyListenerError ??= listenerError;\n outcome = failedOrHeld(value, listenerError, false);\n } else if (value === null) {\n outcome = ABSENT_OUTCOME;\n } else if (value !== undefined) {\n outcome = { status: 'present', data: value };\n }\n }\n if (outcome.status === 'present') nextData[id] = outcome.data;\n const committed = committedOutcomesRef.current[id];\n nextOutcomes[id] = committed && sameOutcome(committed, outcome) ? committed : outcome;\n }\n\n const data = shallowRecordEqual(committedDataRef.current, nextData)\n ? committedDataRef.current\n : nextData;\n const outcomes = shallowRecordEqual(committedOutcomesRef.current, nextOutcomes)\n ? committedOutcomesRef.current\n : nextOutcomes;\n\n useEffect(() => {\n committedDataRef.current = data;\n committedOutcomesRef.current = outcomes;\n }, [data, outcomes]);\n\n const refetch = useCallback(async () => {\n if (subscribe || !enabled) return;\n await Promise.all(\n uniqueIds.map((id) =>\n queryClient.refetchQueries({ queryKey: [queryKeyPrefix, id], exact: true }),\n ),\n );\n }, [uniqueIds, subscribe, enabled, queryClient, queryKeyPrefix]);\n\n const isLoading = subscribe ? enabled && anyUnresolved : oneShotLoading;\n\n return {\n data,\n isLoading,\n isError: anyError !== null || anyListenerError !== null,\n error: anyError ?? anyListenerError,\n outcomes,\n failedReadsRunning,\n refetch,\n };\n}\n"]}