@razakalpha/convngx 0.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.
package/README.md ADDED
@@ -0,0 +1,317 @@
1
+ # convNGX
2
+
3
+ Angular-first utilities for Convex with Better Auth:
4
+ - DI-wrapped Convex client with Better Auth token refresh
5
+ - Angular Resources for live queries, mutations, and actions
6
+ - One-call setup provider (no environment.ts in the lib)
7
+ - Resource ergonomics: params-gated queries, keep-last value, reload control, mutation concurrency modes, retries, optimistic updates
8
+
9
+ Demo app: projects/example-chat (Angular + Convex + Better Auth)
10
+
11
+ ## Install peer deps
12
+
13
+ Use your app's package.json; this library provides Angular wrappers and expects Convex + Better Auth to be available.
14
+
15
+ ```bash
16
+ npm i convex @convex-dev/better-auth better-auth
17
+ ```
18
+ ## Assumptions
19
+
20
+ This library assumes your Convex backend uses Better Auth (via `@convex-dev/better-auth`) and exposes the Better Auth HTTP endpoints on your Convex site (e.g. `https://YOUR.convex.site`). The Angular providers wire the Convex client to Better Auth, handle proactive token refresh, and optionally support cross‑domain OTT handoff.
21
+
22
+ ## Quick start (Angular)
23
+
24
+ Register the provider once in your bootstrap:
25
+
26
+ ```ts
27
+ import { bootstrapApplication } from '@angular/platform-browser';
28
+ import { provideConvexAngular } from 'convngx';
29
+ import { AppComponent } from './app';
30
+
31
+ bootstrapApplication(AppComponent, {
32
+ providers: [
33
+ provideConvexAngular({
34
+ convexUrl: 'https://YOUR.convex.cloud',
35
+ authBaseURL: 'https://YOUR.convex.site', // Better Auth base (your Convex site)
36
+ authSkewMs: 45_000, // optional
37
+ keep: 'last', // default keep mode for live resources
38
+ }),
39
+ // Optional cross-domain OTT handoff bootstrap (call separately)
40
+ // provideBetterAuthOttBootstrap(),
41
+ ],
42
+ });
43
+ ```
44
+
45
+ Inject the Convex client anywhere:
46
+
47
+ ```ts
48
+ import { injectConvex } from 'convngx';
49
+
50
+ const convex = injectConvex();
51
+ // convex.query(...), convex.watchQuery(...), convex.mutation(...), convex.action(...)
52
+ ```
53
+
54
+ ## Live queries: convexLiveResource
55
+
56
+ Angular Resource wrapper around Convex watchQuery with smart gating, keep-last, and manual reload.
57
+
58
+ Core usage:
59
+
60
+ ```ts
61
+ import { convexLiveResource } from 'convngx';
62
+ import { api } from '@/convex/_generated/api';
63
+
64
+ // Live updated with angular resource api
65
+ const todosRes = convexLiveResource(api.todos.list);
66
+ const todos = computed(() => this.todoRes.value())
67
+ const todoLoading = computed(() => this.todoRes.isLoading())
68
+
69
+ // With params (resource auto-disables when params() returns undefined)
70
+ const filter = signal('');
71
+
72
+ // Completly reactive! And cached!
73
+ const messagesRes = convexLiveResource(
74
+ api.messages.getFilteredMessagesByContent,
75
+ () => ({ content: filter() || undefined }),
76
+ );
77
+
78
+ // Opt out of keep-last value (immediate undefined on param change)
79
+ const resNoKeep = convexLiveResource(api.todos.list, { keep: 'none' });
80
+
81
+ // Manual refresh (also performs a one-shot .query to seed the latest value)
82
+ messagesRes.reload();
83
+ ```
84
+
85
+ Behavior details
86
+ - Params gating: When you pass a params factory `() => args | undefined`, the resource remains disabled until a non-undefined value is returned. For no-args queries, the resource is always enabled.
87
+ - Keep mode: By default `keep: 'last'`, the last successful value is kept visible while parameters change and the next subscription warms up. Set `keep: 'none'` to clear stale values immediately on change.
88
+ - Live + one-shot fetch: A Convex `watchQuery` subscription is established for live updates. A one-time `query` call runs only when you call `.reload()` (useful for guaranteed freshness).
89
+ - Errors: Any thrown errors during local result access or network updates are surfaced via the resource’s `error()`.
90
+
91
+ Type overloads (for reference)
92
+ ```ts
93
+ function convexLiveResource<Q extends FunctionReference<'query'> & { _args: {} }>(
94
+ query: Q,
95
+ opts?: { keep?: 'none' | 'last' },
96
+ ): ResourceRef<FunctionReturnType<Q> | undefined>;
97
+
98
+ function convexLiveResource<Q extends FunctionReference<'query'> & { _args: {} }>(
99
+ query: Q,
100
+ params: () => {} | undefined,
101
+ opts?: { keep?: 'none' | 'last' },
102
+ ): ResourceRef<FunctionReturnType<Q> | undefined>;
103
+
104
+ function convexLiveResource<Q extends FunctionReference<'query'>>(
105
+ query: Q,
106
+ params: () => Q['_args'] | undefined,
107
+ opts?: { keep?: 'none' | 'last' },
108
+ ): ResourceRef<FunctionReturnType<Q> | undefined>;
109
+ ```
110
+
111
+ Global default for keep mode (optional DI)
112
+ ```ts
113
+ import { provideConvexResourceOptions } from 'convngx';
114
+
115
+ bootstrapApplication(App, {
116
+ providers: [
117
+ provideConvexResourceOptions({ keep: 'none' }),
118
+ ],
119
+ });
120
+ ```
121
+
122
+ Implementation: src/lib/resources/live.resource.ts
123
+
124
+ ## Mutations: convexMutationResource
125
+
126
+ A mutation helper that returns an imperative `run()` plus resource-shaped state and derived signals. Supports optimistic updates, callbacks, basic concurrency controls, and retries.
127
+
128
+ ```ts
129
+ import { convexMutationResource } from 'convngx';
130
+ import { api } from '@/convex/_generated/api';
131
+
132
+ // Minimal
133
+ const createTodo = convexMutationResource(api.todos.create);
134
+
135
+ // With options
136
+ const sendMessage = convexMutationResource(api.messages.sendMessage, {
137
+ // Convex OptimisticUpdate signature: (store, args) => void
138
+ optimisticUpdate: (store, args) => {
139
+ store.setQuery(api.messages.getFilteredMessagesByContent, { content: '' }, prev => [
140
+ { _id: 'tmp', content: args.content, timestamp: Date.now() },
141
+ ...(prev ?? []),
142
+ ]);
143
+ },
144
+ onSuccess: (data) => console.log('created', data),
145
+ onError: (err) => console.error(err),
146
+ mode: 'replace', // 'queue' | 'drop' | 'replace'
147
+ retries: 2, // simple retry count
148
+ retryDelayMs: n => 400 * n,
149
+ });
150
+
151
+ // In a component
152
+ if (!sendMessage.isRunning()) {
153
+ await sendMessage.run({ content: 'Hello' });
154
+ }
155
+
156
+ // Bind in templates if you like
157
+ // sendMessage.state.value(), sendMessage.state.error()
158
+ // sendMessage.data(), sendMessage.error(), sendMessage.isRunning()
159
+ ```
160
+
161
+ Concurrency modes
162
+ - replace: default; a new run supersedes the UI of the previous run
163
+ - drop: ignore new run() calls while a previous run is in flight
164
+ - queue: wait for the current run to finish, then start the next
165
+
166
+ Return shape
167
+ ```ts
168
+ type ConvexMutationResource<M> = {
169
+ run: (args?: ArgsOf<M>) => Promise<ReturnOf<M>>;
170
+ state: ResourceRef<ReturnOf<M> | undefined>;
171
+ data: Signal<ReturnOf<M> | undefined>;
172
+ error: Signal<Error | undefined>;
173
+ isRunning: Signal<boolean>;
174
+ reset(): void; // clears UI state (does not cancel inflight work)
175
+ };
176
+ ```
177
+
178
+ Implementation: src/lib/resources/mutation.resource.ts
179
+
180
+ ## Actions: convexActionResource
181
+
182
+ Identical ergonomics to mutations but calls `convex.action`. Useful for long-running or external API calls.
183
+
184
+ ```ts
185
+ import { convexActionResource } from 'convngx';
186
+ import { api } from '@/convex/_generated/api';
187
+
188
+ const exportData = convexActionResource(api.reports.export, {
189
+ retries: 3,
190
+ mode: 'queue',
191
+ });
192
+
193
+ await exportData.run({ range: 'last30d' });
194
+ ```
195
+
196
+ Implementation: src/lib/resources/action.resource.ts
197
+
198
+ ## Auth integration (Better Auth)
199
+
200
+ The client wires in Better Auth so the Convex browser client always has a fresh token; OTT flow is optionally supported.
201
+
202
+ - Provide Better Auth HTTP client: src/lib/auth/auth-client.provider.ts
203
+ - Wire Convex client to auth: src/lib/auth/convex-better-auth.provider.ts
204
+ - One-call setup provider: src/lib/setup/convex-angular.providers.ts
205
+ - DI token to inject the Convex client: src/lib/core/inject-convex.token.ts
206
+ - Client implementation with token refresh: src/lib/core/convex-angular-client.ts
207
+
208
+ Minimal Convex Better Auth server (lives in your Convex project, not in this library):
209
+
210
+ ```ts
211
+ // convex/auth.ts (in your Convex backend)
212
+ import { betterAuth } from 'better-auth';
213
+ import { convexAdapter } from '@convex-dev/better-auth';
214
+ import { convex, crossDomain } from '@convex-dev/better-auth/plugins';
215
+ import type { GenericCtx } from './_generated/server';
216
+
217
+ export const createAuth = (ctx: GenericCtx) =>
218
+ betterAuth({
219
+ database: convexAdapter(ctx, /* your Better Auth component */ undefined as any),
220
+ emailAndPassword: { enabled: true, requireEmailVerification: false },
221
+ plugins: [
222
+ convex(),
223
+ crossDomain({ siteUrl: 'http://localhost:4200' }), // Your Angular origin
224
+ ],
225
+ ## Auth state (reactive, technical)
226
+
227
+ This library exposes auth snapshots and events on the Convex client so you can build a tiny, reactive auth state that stays in sync across tabs and refreshes tokens in the background.
228
+
229
+ - Snapshot: [ConvexAngularClient.getAuthSnapshot()](src/lib/core/convex-angular-client.ts:177)
230
+ - Updates: [ConvexAngularClient.onAuth()](src/lib/core/convex-angular-client.ts:165)
231
+ - Manual helpers: [ConvexAngularClient.refreshAuth()](src/lib/core/convex-angular-client.ts:186), [ConvexAngularClient.logoutLocal()](src/lib/core/convex-angular-client.ts:171), [ConvexAngularClient.warmAuth()](src/lib/core/convex-angular-client.ts:154)
232
+ - DI: [CONVEX](src/lib/core/inject-convex.token.ts:9) and [injectConvex()](src/lib/core/inject-convex.token.ts:12)
233
+ - Optional OTT bootstrap: [provideBetterAuthOttBootstrap()](src/lib/auth/convex-better-auth.provider.ts:66)
234
+ - Combined provider: [provideConvexAngular()](src/lib/setup/convex-angular.providers.ts:28)
235
+
236
+ Example service (from the chat app) that derives a reactive `isAuthenticated`:
237
+
238
+ ```ts
239
+ // projects/example-chat/src/app/state/convex-auth.state.ts
240
+ import { Injectable, computed, inject, signal } from '@angular/core';
241
+ import { CONVEX, type ConvexAngularClient } from 'convngx';
242
+
243
+ @Injectable({ providedIn: 'root' })
244
+ export class ConvexAuthState {
245
+ private readonly convex = inject<ConvexAngularClient>(CONVEX);
246
+ private readonly _isAuthed = signal(this.convex.getAuthSnapshot().isAuthenticated);
247
+ readonly isAuthenticated = computed(() => this._isAuthed());
248
+
249
+ constructor() {
250
+ this.convex.onAuth((s) => this._isAuthed.set(s.isAuthenticated));
251
+ }
252
+ }
253
+ ```
254
+
255
+ Notes:
256
+ - Tokens are proactively refreshed ahead of expiry (skew/jitter) and synchronized across tabs via BroadcastChannel in the client.
257
+ - `onAuth` emits immediately with the current snapshot, then on any login/logout/token change.
258
+ - The example lives at [convex-auth.state.ts](../../example-chat/src/app/state/convex-auth.state.ts:1).
259
+ });
260
+ ```
261
+
262
+ ## Example app (Chat)
263
+
264
+ The repository contains a small chat app showing live queries + mutations:
265
+ - Component: projects/example-chat/src/app/components/chat/chat.component.ts
266
+ - Template: projects/example-chat/src/app/components/chat/chat.component.html
267
+ - Auth store: projects/example-chat/src/app/state/auth.store.ts
268
+ - Convex functions: convex/messages.ts, convex/users.ts
269
+
270
+ Snippet from the chat component:
271
+
272
+ ```ts
273
+ import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
274
+ import { convexLiveResource, convexMutationResource } from 'convngx';
275
+ import { api } from 'convex/_generated/api';
276
+
277
+ @Component({ /* ... */ })
278
+ export class ChatComponent {
279
+ sendMessageMutation = convexMutationResource(api.messages.sendMessage);
280
+ filter = signal('');
281
+ messages = convexLiveResource(api.messages.getFilteredMessagesByContent, () => ({ content: this.filter() }));
282
+
283
+ async sendMessage() {
284
+ const content = this.newMessage().trim();
285
+ if (!content || this.sendMessageMutation.isRunning()) return;
286
+ await this.sendMessageMutation.run({ content });
287
+ this.newMessage.set('');
288
+ }
289
+ }
290
+ ```
291
+
292
+ ## API surface (map)
293
+
294
+ - Core DI and client:
295
+ - injectConvex(): src/lib/core/inject-convex.token.ts
296
+ - Convex client: src/lib/core/convex-angular-client.ts
297
+ - Auth:
298
+ - Better Auth HTTP client provider: src/lib/auth/auth-client.provider.ts
299
+ - Convex + Better Auth wiring: src/lib/auth/convex-better-auth.provider.ts
300
+ - Resources:
301
+ - Live queries: src/lib/resources/live.resource.ts
302
+ - Mutations: src/lib/resources/mutation.resource.ts
303
+ - Actions: src/lib/resources/action.resource.ts
304
+ - Setup:
305
+ - One-call provider: src/lib/setup/convex-angular.providers.ts
306
+
307
+ ## Build
308
+
309
+ ```bash
310
+ ng build convngx-angular
311
+ ```
312
+
313
+ Outputs to dist/convngx.
314
+
315
+ ## License
316
+
317
+ MIT