@oxy.so/services 9.0.0 → 9.2.0

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 (79) hide show
  1. package/lib/commonjs/index.js +4 -3
  2. package/lib/commonjs/index.js.map +1 -1
  3. package/lib/commonjs/ui/client.js +174 -0
  4. package/lib/commonjs/ui/client.js.map +1 -1
  5. package/lib/commonjs/ui/components/FollowTargetButton.js +11 -101
  6. package/lib/commonjs/ui/components/FollowTargetButton.js.map +1 -1
  7. package/lib/commonjs/ui/components/OxyProvider.js +2 -2
  8. package/lib/commonjs/ui/components/OxyProvider.js.map +1 -1
  9. package/lib/commonjs/ui/components/followRules.js +105 -0
  10. package/lib/commonjs/ui/components/followRules.js.map +1 -0
  11. package/lib/commonjs/ui/context/OxyContext.js +4 -0
  12. package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
  13. package/lib/commonjs/ui/hooks/accountQueryPersistence.js +110 -80
  14. package/lib/commonjs/ui/hooks/accountQueryPersistence.js.map +1 -1
  15. package/lib/commonjs/ui/hooks/persistedQueryCache.js +101 -0
  16. package/lib/commonjs/ui/hooks/persistedQueryCache.js.map +1 -0
  17. package/lib/commonjs/ui/hooks/queryClient.js +43 -80
  18. package/lib/commonjs/ui/hooks/queryClient.js.map +1 -1
  19. package/lib/module/index.js +3 -2
  20. package/lib/module/index.js.map +1 -1
  21. package/lib/module/ui/client.js +17 -4
  22. package/lib/module/ui/client.js.map +1 -1
  23. package/lib/module/ui/components/FollowTargetButton.js +1 -89
  24. package/lib/module/ui/components/FollowTargetButton.js.map +1 -1
  25. package/lib/module/ui/components/OxyProvider.js +2 -2
  26. package/lib/module/ui/components/OxyProvider.js.map +1 -1
  27. package/lib/module/ui/components/followRules.js +99 -0
  28. package/lib/module/ui/components/followRules.js.map +1 -0
  29. package/lib/module/ui/context/OxyContext.js +4 -0
  30. package/lib/module/ui/context/OxyContext.js.map +1 -1
  31. package/lib/module/ui/hooks/accountQueryPersistence.js +109 -80
  32. package/lib/module/ui/hooks/accountQueryPersistence.js.map +1 -1
  33. package/lib/module/ui/hooks/persistedQueryCache.js +94 -0
  34. package/lib/module/ui/hooks/persistedQueryCache.js.map +1 -0
  35. package/lib/module/ui/hooks/queryClient.js +44 -81
  36. package/lib/module/ui/hooks/queryClient.js.map +1 -1
  37. package/lib/typescript/commonjs/index.d.ts +4 -2
  38. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  39. package/lib/typescript/commonjs/ui/client.d.ts +19 -4
  40. package/lib/typescript/commonjs/ui/client.d.ts.map +1 -1
  41. package/lib/typescript/commonjs/ui/components/FollowTargetButton.d.ts +2 -62
  42. package/lib/typescript/commonjs/ui/components/FollowTargetButton.d.ts.map +1 -1
  43. package/lib/typescript/commonjs/ui/components/followRules.d.ts +71 -0
  44. package/lib/typescript/commonjs/ui/components/followRules.d.ts.map +1 -0
  45. package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
  46. package/lib/typescript/commonjs/ui/hooks/accountQueryPersistence.d.ts +31 -13
  47. package/lib/typescript/commonjs/ui/hooks/accountQueryPersistence.d.ts.map +1 -1
  48. package/lib/typescript/commonjs/ui/hooks/persistedQueryCache.d.ts +44 -0
  49. package/lib/typescript/commonjs/ui/hooks/persistedQueryCache.d.ts.map +1 -0
  50. package/lib/typescript/commonjs/ui/hooks/queryClient.d.ts +15 -20
  51. package/lib/typescript/commonjs/ui/hooks/queryClient.d.ts.map +1 -1
  52. package/lib/typescript/commonjs/ui/icons/MaterialCommunityIcons.d.ts +1 -1
  53. package/lib/typescript/module/index.d.ts +4 -2
  54. package/lib/typescript/module/index.d.ts.map +1 -1
  55. package/lib/typescript/module/ui/client.d.ts +19 -4
  56. package/lib/typescript/module/ui/client.d.ts.map +1 -1
  57. package/lib/typescript/module/ui/components/FollowTargetButton.d.ts +2 -62
  58. package/lib/typescript/module/ui/components/FollowTargetButton.d.ts.map +1 -1
  59. package/lib/typescript/module/ui/components/followRules.d.ts +71 -0
  60. package/lib/typescript/module/ui/components/followRules.d.ts.map +1 -0
  61. package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
  62. package/lib/typescript/module/ui/hooks/accountQueryPersistence.d.ts +31 -13
  63. package/lib/typescript/module/ui/hooks/accountQueryPersistence.d.ts.map +1 -1
  64. package/lib/typescript/module/ui/hooks/persistedQueryCache.d.ts +44 -0
  65. package/lib/typescript/module/ui/hooks/persistedQueryCache.d.ts.map +1 -0
  66. package/lib/typescript/module/ui/hooks/queryClient.d.ts +15 -20
  67. package/lib/typescript/module/ui/hooks/queryClient.d.ts.map +1 -1
  68. package/lib/typescript/module/ui/icons/MaterialCommunityIcons.d.ts +1 -1
  69. package/package.json +1 -1
  70. package/src/index.ts +3 -3
  71. package/src/ui/client.ts +55 -4
  72. package/src/ui/components/FollowTargetButton.tsx +8 -112
  73. package/src/ui/components/OxyProvider.tsx +2 -2
  74. package/src/ui/components/__tests__/followTargetButton.test.ts +1 -1
  75. package/src/ui/components/followRules.ts +121 -0
  76. package/src/ui/context/OxyContext.tsx +4 -0
  77. package/src/ui/hooks/accountQueryPersistence.ts +138 -91
  78. package/src/ui/hooks/persistedQueryCache.ts +126 -0
  79. package/src/ui/hooks/queryClient.ts +55 -98
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The storage format and restore rules shared by the SDK's two query caches:
3
+ * the account-agnostic one (`attachQueryPersistence`) and the per-account one
4
+ * (`createAccountQueryPersistence`).
5
+ *
6
+ * A blob is `{ buster, timestamp, clientState }`, TanStack's persisted-client
7
+ * shape. Restoring it treats its two halves differently:
8
+ *
9
+ * - Queries are served before any refetch, so a query written by another
10
+ * build, in whatever shape that build used, is dropped (`getOxyBuildId`).
11
+ * - Paused mutations are the user's queued actions (a star, a send made
12
+ * offline). A deploy must not lose them, so they are restored whatever build
13
+ * wrote them; the current build's `setMutationDefaults` replays them.
14
+ */
15
+
16
+ import {
17
+ dehydrate,
18
+ hydrate,
19
+ type DehydratedState,
20
+ type Mutation,
21
+ type Query,
22
+ type QueryClient,
23
+ } from '@tanstack/react-query';
24
+ import { getOxyBuildId } from '../utils/buildId';
25
+
26
+ /** The SDK's own account-agnostic query roots, persisted by `attachQueryPersistence`. */
27
+ export const PERSISTED_QUERY_PREFIXES: ReadonlyArray<string> = [
28
+ 'accounts',
29
+ 'users',
30
+ 'sessions',
31
+ 'devices',
32
+ 'privacy',
33
+ ];
34
+
35
+ /**
36
+ * SDK queries whose data (or key) carries a signed, expiring URL. Never
37
+ * written to disk: a restored one would serve an expired URL.
38
+ */
39
+ export const SDK_MEMORY_ONLY_ROOTS: ReadonlyArray<string> = [
40
+ 'assetDownloadUrls',
41
+ 'avatarCropSource',
42
+ 'avatarCropMeasure',
43
+ 'justifiedPhotoDimensions',
44
+ ];
45
+
46
+ export interface PersistFilters {
47
+ shouldDehydrateQuery: (query: Query) => boolean;
48
+ shouldDehydrateMutation: (mutation: Mutation) => boolean;
49
+ }
50
+
51
+ interface PersistedBlob {
52
+ buster: string;
53
+ timestamp: number;
54
+ clientState: DehydratedState;
55
+ }
56
+
57
+ export function rootOf(query: Query): string | null {
58
+ const head = query.queryKey[0];
59
+ return typeof head === 'string' ? head : null;
60
+ }
61
+
62
+ /** Serialize what the filters select, stamped with this build. */
63
+ export function snapshot(queryClient: QueryClient, filters: PersistFilters): string {
64
+ const blob: PersistedBlob = {
65
+ buster: getOxyBuildId(),
66
+ timestamp: Date.now(),
67
+ clientState: dehydrate(queryClient, filters),
68
+ };
69
+ return JSON.stringify(blob);
70
+ }
71
+
72
+ /**
73
+ * Hydrate a stored blob into the client, synchronously, so a caller can check
74
+ * it is still wanted immediately before. Returns false when there was nothing
75
+ * usable (absent, unreadable or expired), in which case the caller removes it.
76
+ */
77
+ export function hydrateSnapshot(queryClient: QueryClient, raw: string | null, maxAge: number): boolean {
78
+ if (!raw) return false;
79
+ let blob: PersistedBlob;
80
+ try {
81
+ blob = JSON.parse(raw) as PersistedBlob;
82
+ } catch {
83
+ return false;
84
+ }
85
+ if (!blob?.clientState || typeof blob.timestamp !== 'number' || Date.now() - blob.timestamp > maxAge) {
86
+ return false;
87
+ }
88
+ const sameBuild = blob.buster === getOxyBuildId();
89
+ hydrate(queryClient, {
90
+ queries: sameBuild ? blob.clientState.queries : [],
91
+ mutations: blob.clientState.mutations ?? [],
92
+ });
93
+ return true;
94
+ }
95
+
96
+ /**
97
+ * Write the filtered cache on every change, at most once per `throttleMs`.
98
+ * `write` receives the serialized snapshot; `flush()` writes now.
99
+ */
100
+ export function subscribeSnapshots(
101
+ queryClient: QueryClient,
102
+ filters: PersistFilters,
103
+ throttleMs: number,
104
+ write: (serialized: string) => void,
105
+ ): { flush: () => void; unsubscribe: () => void } {
106
+ let timer: ReturnType<typeof setTimeout> | null = null;
107
+ const flush = () => {
108
+ if (timer) clearTimeout(timer);
109
+ timer = null;
110
+ write(snapshot(queryClient, filters));
111
+ };
112
+ const schedule = () => {
113
+ if (!timer) timer = setTimeout(flush, throttleMs);
114
+ };
115
+ const offQueries = queryClient.getQueryCache().subscribe(schedule);
116
+ const offMutations = queryClient.getMutationCache().subscribe(schedule);
117
+ return {
118
+ flush,
119
+ unsubscribe: () => {
120
+ if (timer) clearTimeout(timer);
121
+ timer = null;
122
+ offQueries();
123
+ offMutations();
124
+ },
125
+ };
126
+ }
@@ -5,34 +5,28 @@
5
5
  * - TanStack Query with `networkMode: 'offlineFirst'` for queries and mutations
6
6
  * so cached data is served immediately and mutations are queued (paused) while
7
7
  * the browser/device reports offline.
8
- * - `persistQueryClient(...)` from `@tanstack/react-query-persist-client` so that
9
- * query results AND paused mutations survive a cold restart (kill-and-relaunch).
8
+ * - `attachQueryPersistence(...)` so that query results AND paused mutations
9
+ * survive a cold restart (kill-and-relaunch); see `persistedQueryCache.ts`.
10
10
  * - `onlineManager` resume hook so paused mutations replay the moment the
11
11
  * network is reported back, even if the host app swapped in a custom
12
12
  * onlineManager implementation.
13
13
  *
14
- * Storage layer:
15
- * - React Native -> AsyncStorage via `createAsyncStoragePersister`.
16
- * - Web -> localStorage via `createSyncStoragePersister` (wrapped in the
17
- * async persister API for a single call site).
18
- * - Both adapters are content-shape compatible with our `StorageInterface`.
14
+ * Storage layer: the platform `StorageInterface` (AsyncStorage on native,
15
+ * localStorage on web).
19
16
  *
20
17
  * Whitelist policy:
21
18
  * - Persist every account/user/session/privacy query and every queued mutation.
22
19
  * - DO NOT persist large list queries (e.g. activity feeds) — they go stale
23
20
  * fast and would balloon storage. Add new keys to `PERSISTED_QUERY_PREFIXES`
24
- * when introducing reads that should survive restart.
21
+ * (`persistedQueryCache.ts`) when introducing reads that should survive restart.
25
22
  */
26
23
 
27
- import { QueryClient, hashKey, onlineManager, type Query, type Mutation, type QueryKey } from '@tanstack/react-query';
28
- import {
29
- persistQueryClient,
30
- type PersistedClient,
31
- } from '@tanstack/react-query-persist-client';
32
- import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister';
24
+ import { QueryClient, onlineManager, type Mutation, type Query } from '@tanstack/react-query';
25
+ import type { PersistedClient } from '@tanstack/react-query-persist-client';
33
26
  import { isDev } from '@oxy.so/core';
34
27
  import type { StorageInterface } from '../utils/storageHelpers';
35
- import { getOxyBuildId } from '../utils/buildId';
28
+ import { accountQueryOwnership, type AccountQueriesConfig } from './accountQueryPersistence';
29
+ import { PERSISTED_QUERY_PREFIXES, hydrateSnapshot, subscribeSnapshots } from './persistedQueryCache';
36
30
 
37
31
  const QUERY_CACHE_KEY = 'oxy_query_cache_v3';
38
32
  const QUERY_CACHE_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days
@@ -55,59 +49,18 @@ export function shouldRetryQuery(failureCount: number, error: unknown): boolean
55
49
  }
56
50
 
57
51
  /**
58
- * Query-key prefixes that should survive cold restart. Anything not listed
59
- * is dropped during dehydration so the persisted blob stays small.
60
- *
61
- * Mutations are persisted independently (always) so the offline write queue
62
- * works regardless of the read whitelist.
63
- */
64
- const PERSISTED_QUERY_PREFIXES: ReadonlyArray<string> = [
65
- 'accounts',
66
- 'users',
67
- 'sessions',
68
- 'devices',
69
- 'privacy',
70
- ];
71
-
72
- /**
73
- * Adapt our `StorageInterface` (which always returns `null` for missing keys)
74
- * to TanStack's `AsyncStorage` shape. The two are structurally identical
75
- * apart from naming; this also gives us a single place to add error
76
- * suppression if a host platform's storage throws.
77
- */
78
- function adaptStorage(storage: StorageInterface): {
79
- getItem: (key: string) => Promise<string | null>;
80
- setItem: (key: string, value: string) => Promise<void>;
81
- removeItem: (key: string) => Promise<void>;
82
- } {
83
- return {
84
- getItem: (key) => storage.getItem(key),
85
- setItem: (key, value) => storage.setItem(key, value),
86
- removeItem: (key) => storage.removeItem(key),
87
- };
88
- }
89
-
90
- /**
91
- * Decide whether a given query should be written to persistent storage.
92
- *
93
- * Two gates:
94
- * 1. The query must be in our prefix whitelist.
95
- * 2. The query must have completed successfully at least once — there's no
96
- * point persisting a `pending`/`error` state, and persisting `error` would
97
- * leak failure objects across restarts.
52
+ * Whether a query belongs in the account-agnostic cache: successful (a
53
+ * `pending`/`error` state is not worth keeping, and an error would leak
54
+ * failure objects across restarts) and under one of the SDK's own prefixes.
98
55
  */
99
- function shouldDehydrateQuery(query: Query): boolean {
56
+ function isSharedQuery(query: Query): boolean {
100
57
  if (query.state.status !== 'success') {
101
58
  return false;
102
59
  }
103
60
  const head = query.queryKey[0];
104
- if (typeof head !== 'string') {
105
- return false;
106
- }
107
- return PERSISTED_QUERY_PREFIXES.includes(head);
61
+ return typeof head === 'string' && PERSISTED_QUERY_PREFIXES.includes(head);
108
62
  }
109
63
 
110
-
111
64
  /**
112
65
  * Create a QueryClient with offline-first defaults.
113
66
  *
@@ -174,10 +127,13 @@ export interface AttachPersistenceResult {
174
127
  }
175
128
 
176
129
  /**
177
- * Wire `persistQueryClient` to the supplied storage adapter.
130
+ * Restore, then keep writing, the account-agnostic cache.
178
131
  *
179
- * Returns once the in-flight restore promise is available so callers can
180
- * `await result.restored` before rendering UI that depends on cached data.
132
+ * Queries written by another build are dropped; queued mutations are kept
133
+ * (`persistedQueryCache.ts`). Whatever the app declared account-scoped
134
+ * (`accountQueries`) is left to `createAccountQueryPersistence`, even under
135
+ * one of the SDK's prefixes, so private rows never land in the shared blob and
136
+ * a paused mutation cannot replay twice or under another account.
181
137
  *
182
138
  * Safe to no-op if `storage` is null/undefined (e.g. server-side render
183
139
  * with no host storage).
@@ -185,12 +141,7 @@ export interface AttachPersistenceResult {
185
141
  export const attachQueryPersistence = (
186
142
  queryClient: QueryClient,
187
143
  storage: StorageInterface | null | undefined,
188
- /**
189
- * Mutation keys the app declared account-scoped (`accountQueries`). Those are
190
- * persisted per account by `createAccountQueryPersistence`, never here, so a
191
- * paused mutation cannot replay twice or under another account.
192
- */
193
- accountMutationKeys: readonly QueryKey[] = [],
144
+ accountQueries?: AccountQueriesConfig,
194
145
  ): AttachPersistenceResult => {
195
146
  if (!storage) {
196
147
  return {
@@ -199,38 +150,44 @@ export const attachQueryPersistence = (
199
150
  };
200
151
  }
201
152
 
202
- const persister = createAsyncStoragePersister({
203
- storage: adaptStorage(storage),
204
- key: QUERY_CACHE_KEY,
205
- throttleTime: QUERY_PERSIST_THROTTLE_MS,
206
- });
207
-
208
- // Persist every other mutation regardless of status: paused mutations are
209
- // exactly the ones that must survive restart to replay when online.
210
- const accountScoped = new Set(accountMutationKeys.map((key) => hashKey(key)));
211
- const shouldDehydrateMutation = (mutation: Mutation): boolean => {
212
- const key = mutation.options.mutationKey;
213
- return key === undefined || !accountScoped.has(hashKey(key));
153
+ const account = accountQueries ? accountQueryOwnership(accountQueries) : null;
154
+ const filters = {
155
+ shouldDehydrateQuery: (query: Query) =>
156
+ isSharedQuery(query) && !(account?.ownsQuery(query) ?? false),
157
+ // Every other mutation, whatever its status: paused ones are exactly the
158
+ // ones that must survive a restart to replay when online.
159
+ shouldDehydrateMutation: (mutation: Mutation) =>
160
+ !(account?.ownsMutation(mutation) ?? false),
214
161
  };
215
162
 
216
- const [unsubscribe, restored] = persistQueryClient({
217
- queryClient,
218
- persister,
219
- maxAge: QUERY_CACHE_MAX_AGE,
220
- buster: getOxyBuildId(),
221
- dehydrateOptions: {
222
- shouldDehydrateQuery,
223
- shouldDehydrateMutation,
224
- },
225
- });
226
-
227
- restored.catch((error) => {
228
- if (isDev()) {
229
- console.warn('[QueryClient] Failed to restore persisted cache', error);
163
+ let stopped = false;
164
+ let writer: ReturnType<typeof subscribeSnapshots> | null = null;
165
+ const restored = (async () => {
166
+ const raw = await storage.getItem(QUERY_CACHE_KEY);
167
+ if (stopped) return;
168
+ if (!hydrateSnapshot(queryClient, raw, QUERY_CACHE_MAX_AGE) && raw) {
169
+ await storage.removeItem(QUERY_CACHE_KEY);
230
170
  }
231
- });
171
+ })()
172
+ .catch((error) => {
173
+ if (isDev()) {
174
+ console.warn('[QueryClient] Failed to restore persisted cache', error);
175
+ }
176
+ })
177
+ .then(() => {
178
+ if (stopped) return;
179
+ writer = subscribeSnapshots(queryClient, filters, QUERY_PERSIST_THROTTLE_MS, (serialized) => {
180
+ void Promise.resolve(storage.setItem(QUERY_CACHE_KEY, serialized)).catch(() => undefined);
181
+ });
182
+ });
232
183
 
233
- return { unsubscribe, restored };
184
+ return {
185
+ restored,
186
+ unsubscribe: () => {
187
+ stopped = true;
188
+ writer?.unsubscribe();
189
+ },
190
+ };
234
191
  };
235
192
 
236
193
  /**