@zuzjs/flare 0.2.13 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,1325 +1,7 @@
1
- import { AuthToken } from '@zuzjs/auth';
1
+ import { F as FlareConfig, a as FlareClient } from './index-DQHYN410.cjs';
2
+ export { A as AggregateFunction, b as AggregateSpec, c as AndFilter, d as AnyFilter, e as AuthConfigListener, f as AuthResult, g as AuthStateListener, h as AuthWithPendingVerificationResult, i as AuthWithTokenResult, B as BaseMessage, j as BrowserPushRegistrationOptions, k as BrowserPushTokenOptions, C as ChangeEvent, l as ChangeOperation, m as CollectionExternalStore, n as CollectionPresetMethods, o as CollectionQuery, p as CollectionReference, q as CollectionStream, r as CollectionStreamListener, s as CollectionStreamMeta, t as CollectionStreamOptions, u as ConnectionState, v as CursorValue, D as DataMapperFn, w as DataMapperRegistry, x as DocAddedCallback, y as DocChangedCallback, z as DocDeletedCallback, E as DocUpdatedCallback, G as DocumentQueryBuilder, H as DocumentReference, I as DocumentSnapshot, J as EmailLinkVerifyResult, K as EmailSendResult, L as FlareAction, M as FlareAuthConfig, N as FlareAuthHydrationInput, O as FlareAuthHydrationOptions, P as FlareAuthProviderId, Q as FlareAuthProviderPublicConfig, R as FlareAuthSession, S as FlareAuthUser, T as FlareEvent, U as FlareRule, V as GroupByClause, W as HavingClause, X as JoinClause, Y as JoinQueryPattern, Z as NestedJoinClause, _ as OfflineOperation, $ as OrFilter, a0 as OrderByClause, a1 as PresenceCallback, a2 as PresenceJoinCallback, a3 as PresenceLeaveCallback, a4 as PresenceMember, a5 as PushSendResult, a6 as QueryConfig, a7 as QueryOperator, a8 as QueryPresetMap, a9 as QueryPresetParams, aa as QueryPresetRow, ab as QueryPresetSpec, ac as QuerySnapshot, ad as RegisterPushTokenInput, ae as RulePermission, af as SecurityRuleEntry, ag as SecurityRulesMap, ah as SendEmailInput, ai as SendPushNotificationInput, aj as SnapshotEvent, ak as StreamFlushReason, al as StructuredJoinClause, am as StructuredQuery, an as SubscribeMessage, ao as SubscribeOptions, ap as SubscriptionCallback, aq as SubscriptionData, ar as SubscriptionError, as as SubscriptionErrorCallback, at as SubscriptionHandle, au as VectorFieldConfig, av as VectorSearchClause, aw as VerifyEmailLinkInput, ax as WhereCondition, ay as flareRulesToSecurityMap, az as parseValue, aA as parseWhereCondition, aB as securityMapToFlareRules } from './index-DQHYN410.cjs';
2
3
  export { Anonymous, Apple, AuthGuard, AuthToken, CreateUserWithEmailAndPasswordInput, Credentials, Dropbox, Facebook, GitHub, Google, NormalizedProfile, OAuthProvider, ProviderId, Providers, SignInAnonymouslyInput, SignInWithEmailAndPasswordInput, Twitter, setupProvider } from '@zuzjs/auth';
3
4
 
4
- /**
5
- * Client Configuration
6
- */
7
- interface FlareConfig {
8
- /** Base URL for the Flare API. */
9
- endpoint: string;
10
- /**
11
- * Optional HTTP base URL for auth API calls.
12
- * When set, all auth HTTP calls go through this base instead of calling
13
- * Flare directly. Use this to route calls through a Next.js proxy so CSRF
14
- * is handled entirely server-side.
15
- * Example: '/api/flare' (relative, browser resolves against current origin)
16
- */
17
- httpBase?: string;
18
- /**
19
- * WebSocket path used for realtime transport.
20
- * Defaults to '/' for backward compatibility.
21
- */
22
- wsPath?: string;
23
- /** Unique identifier for the application. */
24
- appId: string;
25
- /** API key for the application. */
26
- apiKey?: string;
27
- /**
28
- * Request content type for credential auth endpoints (/auth/token, /auth/register).
29
- * Defaults to OAuth-compatible form encoding.
30
- */
31
- authRequestContentType?: "application/x-www-form-urlencoded" | "application/json";
32
- /**
33
- * Controls how onAuthStateChanged initializes auth in browser runtime.
34
- * - `refresh` (default): attempt /auth/refresh once in httpBase mode.
35
- * - `none`: skip automatic refresh bootstrap; listeners receive current in-memory state only.
36
- */
37
- authBootstrapMode?: "refresh" | "none";
38
- /** Public key for the application. */
39
- publicKey?: string;
40
- /** Whether to automatically reconnect on connection loss. */
41
- autoReconnect?: boolean;
42
- /** Delay between reconnection attempts in milliseconds. */
43
- reconnectDelay?: number;
44
- /** Maximum delay between reconnection attempts in milliseconds. */
45
- maxReconnectDelay?: number;
46
- /** Enable or disable debug mode. */
47
- debug?: boolean;
48
- /** Enable or disable request timing. */
49
- requestTiming?: boolean;
50
- /** Connection timeout in milliseconds. */
51
- connectionTimeout?: number;
52
- /** Enable automatic push notification registration on supported platforms. */
53
- pushNotifications?: boolean;
54
- /**
55
- * Optional per-collection mapper registry for shaping inbound data.
56
- *
57
- * Keys can be:
58
- * - base collection names (e.g. "boards")
59
- * - join aliases (`join(..., { as: "team" })` => "team")
60
- */
61
- dataMapper?: DataMapperRegistry;
62
- }
63
- type DataMapperFn<TRow = any, TMapped = any> = (row: TRow) => TMapped;
64
- type DataMapperRegistry = Record<string, DataMapperFn<any, any>>;
65
- type FlareAuthProviderId = "credentials" | "anonymous" | "google" | "facebook" | "github" | "dropbox" | "apple" | "twitter";
66
- interface FlareAuthProviderPublicConfig {
67
- enabled: boolean;
68
- clientId?: string;
69
- scopes?: string[];
70
- }
71
- interface FlareAuthConfig {
72
- appId: string;
73
- enabled: boolean;
74
- needsEmailVerification?: boolean;
75
- autoSendVerificationEmail?: boolean;
76
- redirectUri?: string;
77
- csrfToken?: string;
78
- cookie?: {
79
- accessTokenName?: string;
80
- refreshTokenName?: string;
81
- csrfTokenName?: string;
82
- domain?: string;
83
- path?: string;
84
- secure?: boolean;
85
- sameSite?: "Lax" | "Strict" | "None";
86
- accessTokenMaxAge?: number;
87
- refreshTokenMaxAge?: number;
88
- csrfTokenMaxAge?: number;
89
- };
90
- providers: Record<FlareAuthProviderId, FlareAuthProviderPublicConfig>;
91
- }
92
- interface FlareAuthSession {
93
- uid: string;
94
- accessToken: string;
95
- refreshToken: string | null;
96
- provider?: string;
97
- email?: string | null;
98
- emailVerified?: boolean;
99
- }
100
- interface FlareAuthUser {
101
- uid: string;
102
- email: string;
103
- email_verified: string;
104
- [x: string]: any;
105
- }
106
- interface FlareAuthHydrationInput {
107
- uid?: string | null;
108
- id?: string | null;
109
- accessToken?: string | null;
110
- refreshToken?: string | null;
111
- ticket?: string | null;
112
- provider?: string;
113
- email?: string | null;
114
- emailVerified?: boolean;
115
- email_verified?: boolean;
116
- profile?: Partial<FlareAuthUser> | null;
117
- }
118
- interface FlareAuthHydrationOptions {
119
- source?: string;
120
- markBootstrapAttempted?: boolean;
121
- syncSocket?: boolean;
122
- }
123
- interface RegisterPushTokenInput {
124
- token: string;
125
- platform?: string;
126
- deviceId?: string;
127
- topics?: string[];
128
- authAppId?: string;
129
- }
130
- interface BrowserPushTokenOptions {
131
- /** Service worker registration used for PushManager subscription. */
132
- serviceWorkerRegistration?: ServiceWorkerRegistration;
133
- /** Existing PushSubscription to reuse instead of subscribing again. */
134
- subscription?: PushSubscription;
135
- /** Public VAPID key used when creating a new PushSubscription. */
136
- applicationServerKey?: string;
137
- /** When true, unsubscribe old subscriptions before creating a new one. */
138
- forceResubscribe?: boolean;
139
- }
140
- interface BrowserPushRegistrationOptions extends BrowserPushTokenOptions {
141
- /** Optional explicit platform label. Defaults to "web". */
142
- platform?: string;
143
- deviceId?: string;
144
- topics?: string[];
145
- authAppId?: string;
146
- }
147
- interface SendPushNotificationInput {
148
- title?: string;
149
- body?: string;
150
- image?: string;
151
- data?: Record<string, unknown>;
152
- tokens?: string[];
153
- uid?: string;
154
- topic?: string;
155
- priority?: "normal" | "high";
156
- ttlSeconds?: number;
157
- dryRun?: boolean;
158
- authAppId?: string;
159
- }
160
- interface PushSendResult {
161
- sent: boolean;
162
- appId: string;
163
- targetCount: number;
164
- successCount: number;
165
- failureCount: number;
166
- invalidatedTokenCount: number;
167
- dryRun: boolean;
168
- }
169
- interface SendEmailInput {
170
- to: string | string[];
171
- tag: string;
172
- values?: Record<string, unknown>;
173
- authAppId?: string;
174
- }
175
- interface EmailSendResult {
176
- sent: boolean;
177
- appId: string;
178
- tag: string;
179
- recipientCount: number;
180
- acceptedCount: number;
181
- rejectedCount: number;
182
- includeVerificationLink?: boolean;
183
- linkId?: string;
184
- verifyUrl?: string;
185
- messageId?: string;
186
- }
187
- interface VerifyEmailLinkInput {
188
- token: string;
189
- tag?: string;
190
- email?: string;
191
- authAppId?: string;
192
- }
193
- interface EmailLinkVerifyResult {
194
- verified: boolean;
195
- alreadyVerified: boolean;
196
- appId: string;
197
- linkId: string;
198
- email: string;
199
- tag: string;
200
- verifiedAt?: string;
201
- acceptedByUid?: string;
202
- }
203
- type AuthStateListener = (session: FlareAuthSession & FlareAuthUser | null) => void;
204
- type AuthConfigListener = (conf: FlareAuthConfig) => void;
205
- interface SubscribeOptions {
206
- skipSnapshot?: boolean;
207
- }
208
- type QueryOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any" | "elem-match" | "like" | "not-like" | "contains" | "exists" | "not-exists";
209
- interface QueryConfig {
210
- field: string;
211
- op: QueryOperator;
212
- value: unknown;
213
- }
214
- /** OR group */
215
- interface OrFilter {
216
- or: AnyFilter[];
217
- }
218
- /** AND group */
219
- interface AndFilter {
220
- and: AnyFilter[];
221
- }
222
- type AnyFilter = QueryConfig | OrFilter | AndFilter;
223
- type WhereCondition = Record<string, string | number | boolean | any[]>;
224
- interface OrderByClause {
225
- field: string;
226
- dir?: "asc" | "desc";
227
- }
228
- interface GroupByClause {
229
- fields: string[];
230
- }
231
- interface HavingClause {
232
- field: string;
233
- op: "==" | "!=" | "<" | "<=" | ">" | ">=";
234
- value: number;
235
- }
236
- interface CursorValue {
237
- values: unknown[];
238
- }
239
- type AggregateFunction = "count" | "sum" | "avg" | "min" | "max" | "distinct";
240
- interface AggregateSpec {
241
- fn: AggregateFunction;
242
- field?: string;
243
- alias?: string;
244
- }
245
- /**
246
- * Join definition used by CollectionReference.Join().
247
- *
248
- * Example:
249
- * Join("tasks", { source: "id", target: "boardId", as: "tasks" })
250
- */
251
- interface JoinQueryPattern {
252
- where?: AnyFilter[];
253
- orderBy?: OrderByClause[];
254
- limit?: number;
255
- offset?: number;
256
- startAt?: CursorValue;
257
- startAfter?: CursorValue;
258
- endAt?: CursorValue;
259
- endBefore?: CursorValue;
260
- aggregate?: AggregateSpec[];
261
- groupBy?: GroupByClause;
262
- having?: HavingClause[];
263
- vectorSearch?: VectorSearchClause;
264
- select?: string[];
265
- distinctField?: string;
266
- }
267
- interface NestedJoinClause extends JoinQueryPattern {
268
- /** Joined collection name for this nested join. */
269
- collection: string;
270
- /** Field from the parent join result. */
271
- source: string;
272
- /** Field from this nested collection to match source. */
273
- target: string;
274
- /** Alias where nested rows are attached in each parent join row. */
275
- as: string;
276
- /** If true, expect at most one joined row. */
277
- single?: boolean;
278
- /** Recursive nested joins. */
279
- joins?: NestedJoinClause[];
280
- }
281
- interface JoinClause extends JoinQueryPattern {
282
- /** Field from the base collection (the collection you started the query on). */
283
- source: string;
284
- /** Field from the joined collection that should match source. */
285
- target: string;
286
- /** Alias where joined rows will be attached in each result object. */
287
- as: string;
288
- /** If true, expect at most one joined row (object instead of array on server side). */
289
- single?: boolean;
290
- /** Optional nested joins under this join. */
291
- joins?: NestedJoinClause[];
292
- }
293
- /** Internal wire-ready join shape sent to server query engine. */
294
- interface StructuredJoinClause extends JoinQueryPattern {
295
- from: string;
296
- localField: string;
297
- foreignField: string;
298
- as: string;
299
- single?: boolean;
300
- joins?: StructuredJoinClause[];
301
- }
302
- interface VectorSearchClause {
303
- field: string;
304
- vector: number[];
305
- k: number;
306
- metric?: "cosine" | "euclidean" | "dotProduct";
307
- minScore?: number;
308
- }
309
- /** Full structured query (document query + SQL-style feature set) */
310
- interface StructuredQuery {
311
- where?: AnyFilter[];
312
- orderBy?: OrderByClause[];
313
- limit?: number;
314
- offset?: number;
315
- startAt?: CursorValue;
316
- startAfter?: CursorValue;
317
- endAt?: CursorValue;
318
- endBefore?: CursorValue;
319
- aggregate?: AggregateSpec[];
320
- groupBy?: GroupByClause;
321
- having?: HavingClause[];
322
- joins?: StructuredJoinClause[];
323
- vectorSearch?: VectorSearchClause;
324
- select?: string[];
325
- distinctField?: string;
326
- }
327
- type QueryPresetSpec<Params extends Record<string, unknown> = Record<string, unknown>, Row = any> = {
328
- params: Params;
329
- row: Row;
330
- };
331
- type QueryPresetMap = Record<string, QueryPresetSpec<any, any>>;
332
- type QueryPresetParams<TSpec> = TSpec extends QueryPresetSpec<infer Params, any> ? Params : Record<string, unknown>;
333
- type QueryPresetRow<TSpec> = TSpec extends QueryPresetSpec<any, infer Row> ? Row : any;
334
- type ChangeOperation = 'insert' | 'update' | 'replace' | 'delete';
335
- /**
336
- * Fired once when the subscription is first established.
337
- * `data` is always an array — the full matching collection snapshot.
338
- */
339
- interface SnapshotEvent<T = any> {
340
- type: 'snapshot';
341
- subscriptionId: string;
342
- collection: string;
343
- data: T[];
344
- }
345
- /**
346
- * Fired on every subsequent document mutation that matches the subscription query.
347
- * `data` is the single affected document (null on delete).
348
- */
349
- interface ChangeEvent<T = any> {
350
- type: 'change';
351
- subscriptionId: string;
352
- collection: string;
353
- docId: string;
354
- operation: ChangeOperation;
355
- data: T | null;
356
- }
357
- /** Discriminated union — narrow on `event.type` to get the right shape. */
358
- type SubscriptionData<T = any> = SnapshotEvent<T> | ChangeEvent<T>;
359
- type SubscriptionCallback<T = any> = (data: SubscriptionData<T>) => void;
360
- interface SubscriptionError {
361
- code?: string;
362
- message: string;
363
- permissionDenied: boolean;
364
- raw?: unknown;
365
- }
366
- type SubscriptionErrorCallback = (error: SubscriptionError) => void;
367
- interface SubscriptionHandle {
368
- (): void;
369
- unsubscribe: () => void;
370
- onError: (callback: SubscriptionErrorCallback) => SubscriptionHandle;
371
- onPermissionDenied: (callback: SubscriptionErrorCallback) => SubscriptionHandle;
372
- catch: (callback: SubscriptionErrorCallback) => SubscriptionHandle;
373
- }
374
- type DocAddedCallback<T = any> = (data: T, docId: string) => void;
375
- type DocUpdatedCallback<T = any> = (data: T, docId: string) => void;
376
- type DocDeletedCallback<T = any> = (docId: string) => void;
377
- type DocChangedCallback<T = any> = (data: T | null, docId: string, operation: ChangeOperation) => void;
378
- type StreamFlushReason = 'snapshot' | 'change-batch';
379
- interface CollectionStreamOptions<T = any> {
380
- /** Delay before a queued burst is flushed to listeners. */
381
- flushMs?: number;
382
- /** Flush immediately when queued changes reach this count. */
383
- maxBatchSize?: number;
384
- /** Field used to identify docs inside snapshots when getId is not provided. */
385
- idField?: keyof T & string;
386
- /** Custom identifier extractor for snapshot rows. */
387
- getId?: (doc: T) => string | undefined;
388
- /** Where newly inserted docs should be placed when they were not in snapshot. */
389
- insertAt?: 'start' | 'end';
390
- /** Optional cap to keep only the newest N docs in local stream state. */
391
- maxDocs?: number;
392
- /** Optional local sort run after flush. */
393
- sort?: (a: T, b: T) => number;
394
- }
395
- interface CollectionStreamMeta {
396
- reason: StreamFlushReason;
397
- batchSize: number;
398
- version: number;
399
- ready: boolean;
400
- }
401
- type CollectionStreamListener<T = any> = (rows: readonly T[], meta: CollectionStreamMeta) => void;
402
- interface CollectionStream<T = any> {
403
- /** Subscribe to stream updates (call unsubscribe to stop). */
404
- subscribe: (listener: CollectionStreamListener<T>, emitCurrent?: boolean) => () => void;
405
- /** Returns the latest immutable snapshot of rows. */
406
- getSnapshot: () => readonly T[];
407
- /** Returns true after the initial snapshot has been received. */
408
- isReady: () => boolean;
409
- /** Monotonic version incremented on each flush. */
410
- getVersion: () => number;
411
- /** Stop the underlying realtime subscription and cleanup timers/listeners. */
412
- close: () => void;
413
- /** Attach subscription-level error handler. */
414
- onError: (callback: SubscriptionErrorCallback) => CollectionStream<T>;
415
- /** Attach permission-denied handler. */
416
- onPermissionDenied: (callback: SubscriptionErrorCallback) => CollectionStream<T>;
417
- }
418
- interface CollectionExternalStore<T = any> {
419
- /** Standard external-store subscribe signature used by UI store hooks. */
420
- subscribe: (onStoreChange: () => void) => () => void;
421
- /** Returns current immutable rows snapshot. */
422
- getSnapshot: () => readonly T[];
423
- /** Server snapshot fallback for SSR-safe store hooks. */
424
- getServerSnapshot: () => readonly T[];
425
- /** Access to underlying realtime stream for advanced handlers. */
426
- stream: CollectionStream<T>;
427
- /** Stops realtime stream and detaches listeners. */
428
- destroy: () => void;
429
- }
430
- interface DocumentSnapshot<T = any> {
431
- id: string;
432
- data: T | null;
433
- exists: boolean;
434
- }
435
- interface QuerySnapshot<T = any> {
436
- docs: DocumentSnapshot<T>[];
437
- size: number;
438
- empty: boolean;
439
- }
440
- interface OfflineOperation {
441
- id: string;
442
- type: 'write' | 'delete';
443
- collection: string;
444
- docId: string;
445
- data?: Record<string, unknown>;
446
- merge?: boolean;
447
- clientTs: number;
448
- }
449
- interface AuthResult {
450
- uid: string;
451
- token?: string;
452
- }
453
- type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'error';
454
- interface AuthWithPendingVerificationResult {
455
- verificationRequired: true;
456
- created: true;
457
- emailSent: boolean;
458
- preview?: {
459
- code: string;
460
- link: string;
461
- };
462
- }
463
- interface AuthWithTokenResult extends AuthResult {
464
- accessToken: string;
465
- refreshToken: string | null;
466
- authToken: AuthToken;
467
- created: boolean;
468
- }
469
- interface PresenceMember {
470
- uid: string;
471
- socketId: string;
472
- room: string;
473
- meta?: Record<string, unknown>;
474
- joinedAt: number;
475
- lastSeen: number;
476
- }
477
- type PresenceCallback = (members: PresenceMember[]) => void;
478
- type PresenceJoinCallback = (member: PresenceMember) => void;
479
- type PresenceLeaveCallback = (uid: string) => void;
480
- /** Fields marked as vector will be auto-embedded before write */
481
- type VectorFieldConfig = {
482
- /** Dimensions of the vector (e.g. 1536 for OpenAI ada-002) */
483
- dimensions: number;
484
- /** Optional custom embedding function; defaults to client-configured embedder */
485
- embed?: (text: string) => Promise<number[]>;
486
- };
487
- type RulePermission = "create" | "read" | "update" | "delete";
488
- interface FlareRule {
489
- id: string;
490
- name: string;
491
- auth: "any" | "guest" | "auth";
492
- collection: string;
493
- document?: string;
494
- condition?: string;
495
- permissions: RulePermission[];
496
- }
497
- interface SecurityRuleEntry {
498
- ".read"?: string;
499
- ".write"?: string;
500
- ".create"?: string;
501
- ".update"?: string;
502
- ".delete"?: string;
503
- }
504
- type SecurityRulesMap = Record<string, SecurityRuleEntry>;
505
- declare const flareRulesToSecurityMap: (rules: FlareRule[]) => SecurityRulesMap;
506
- declare const securityMapToFlareRules: (rules: SecurityRulesMap) => FlareRule[];
507
-
508
- /**
509
- * Parse ORM-style where condition: { age: ">= 25", role: "admin" }
510
- * Returns array of QueryConfig objects
511
- */
512
- declare function parseWhereCondition(condition: WhereCondition): QueryConfig[];
513
- /**
514
- * Parse string value to appropriate type
515
- */
516
- declare function parseValue(val: string): any;
517
- /**
518
- * Query builder for document operations (ORM-style)
519
- * Supports: doc('users').update({...}).where({ id: 'alice' })
520
- *
521
- * This class is thenable - you can await it directly without .execute() or .get()
522
- * @example
523
- * await doc('users').where({ id: 'alice' })
524
- * await doc('users').update({ name: 'Alice' }).where({ id: 'alice' })
525
- */
526
- declare class DocumentQueryBuilder<T = any> implements PromiseLike<T | null | void> {
527
- private client;
528
- private collection;
529
- private docIdFromRef?;
530
- private whereCondition?;
531
- private updateData?;
532
- private setData?;
533
- private deleteOp;
534
- private promise?;
535
- constructor(client: FlareClient<any>, collection: string, docIdFromRef?: string | undefined);
536
- /**
537
- * Set where condition
538
- */
539
- where(condition: WhereCondition): this;
540
- /**
541
- * Set update data (for update operations)
542
- */
543
- update(data: Partial<T>): this;
544
- /**
545
- * Set data (for set operations)
546
- */
547
- set(data: Partial<T>): this;
548
- /**
549
- * Mark for deletion
550
- */
551
- delete(): this;
552
- /**
553
- * Get the document ID from doc() reference or where condition.
554
- */
555
- private getDocId;
556
- /**
557
- * Execute the query
558
- * @deprecated Use await directly instead of .execute()
559
- */
560
- execute(): Promise<T | null | void>;
561
- /**
562
- * Internal execute method
563
- */
564
- private _execute;
565
- /**
566
- * Make this class thenable so it can be awaited directly
567
- */
568
- then<TResult1 = T | null | void, TResult2 = never>(onfulfilled?: ((value: T | null | void) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): PromiseLike<TResult1 | TResult2>;
569
- /**
570
- * Get the document data once
571
- */
572
- get(): Promise<T | null>;
573
- /**
574
- * Subscribe to real-time updates
575
- */
576
- onSnapshot(callback: SubscriptionCallback<T>): () => void;
577
- }
578
-
579
- /** Document reference */
580
- declare class DocumentReference<T = any> {
581
- private client;
582
- readonly collection: string;
583
- readonly id: string;
584
- constructor(client: FlareClient<any>, collection: string, id: string);
585
- get(): Promise<T | null>;
586
- set(data: Partial<T>): Promise<void>;
587
- update(data: Partial<T>): Promise<void>;
588
- delete(): Promise<void>;
589
- onSnapshot(callback: SubscriptionCallback<T>): () => void;
590
- /**
591
- * Fires when this document is updated / replaced.
592
- */
593
- onDocUpdated(callback: DocUpdatedCallback<T>): () => void;
594
- /**
595
- * Fires when this document is deleted.
596
- */
597
- onDocDeleted(callback: DocDeletedCallback<T>): () => void;
598
- /**
599
- * Fires on any change to this document (update / delete).
600
- * `data` is null on deletes.
601
- */
602
- onDocChanged(callback: DocChangedCallback<T>): () => void;
603
- }
604
-
605
- type CollectionPresetMethods<TPresetMap extends QueryPresetMap> = {
606
- [K in keyof TPresetMap & string]: (params: QueryPresetParams<TPresetMap[K]>) => CollectionQuery<QueryPresetRow<TPresetMap[K]>, TPresetMap>;
607
- };
608
- type CollectionQuery<T = any, TPresetMap extends QueryPresetMap = {}> = CollectionReference<T, TPresetMap> & CollectionPresetMethods<TPresetMap>;
609
- declare class CollectionReference<T = any, TPresetMap extends QueryPresetMap = {}> implements PromiseLike<T[]> {
610
- private client;
611
- readonly collection: string;
612
- private sq;
613
- private promise?;
614
- constructor(client: FlareClient<TPresetMap>, collection: string);
615
- doc(id: string): DocumentReference<T>;
616
- private clone;
617
- private normalizeFilterValue;
618
- private normalizeFilter;
619
- private toQueryFilters;
620
- private appendOperatorFilter;
621
- private appendAndFilters;
622
- private toOrNode;
623
- private toAndNode;
624
- private isLeafFilter;
625
- private isIdentityGuard;
626
- private splitIdentityGuards;
627
- private appendOrFilters;
628
- private appendFilters;
629
- with<Name extends keyof TPresetMap & string>(name: Name, params: QueryPresetParams<TPresetMap[Name]>): CollectionQuery<QueryPresetRow<TPresetMap[Name]>, TPresetMap>;
630
- with(name: string, params?: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
631
- /** ORM shorthand: .where({ age: ">= 25", role: "admin" }) */
632
- where(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
633
- and(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
634
- or(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
635
- in(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
636
- andIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
637
- orIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
638
- notIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
639
- andNotIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
640
- orNotIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
641
- arrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
642
- andArrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
643
- orArrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
644
- arrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
645
- andArrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
646
- orArrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
647
- some(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
648
- andSome(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
649
- orSome(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
650
- like(field: string, value: string): CollectionQuery<T, TPresetMap>;
651
- andLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
652
- orLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
653
- notLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
654
- andNotLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
655
- orNotLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
656
- exists(field: string): CollectionQuery<T, TPresetMap>;
657
- andExists(field: string): CollectionQuery<T, TPresetMap>;
658
- orExists(field: string): CollectionQuery<T, TPresetMap>;
659
- notExists(field: string): CollectionQuery<T, TPresetMap>;
660
- andNotExists(field: string): CollectionQuery<T, TPresetMap>;
661
- orNotExists(field: string): CollectionQuery<T, TPresetMap>;
662
- /** Get items starting from the most recently created (descending sequence) */
663
- latest(): CollectionQuery<T, TPresetMap>;
664
- /** Get items starting from the most recently created (descending sequence) */
665
- newest(): CollectionQuery<T, TPresetMap>;
666
- /** Get items starting from the first ever created (ascending sequence) */
667
- oldest(): CollectionQuery<T, TPresetMap>;
668
- orderBy(field: string, dir?: "asc" | "desc"): CollectionQuery<T, TPresetMap>;
669
- limit(n: number): CollectionQuery<T, TPresetMap>;
670
- offset(n: number): CollectionQuery<T, TPresetMap>;
671
- startAt(...values: unknown[]): CollectionQuery<T, TPresetMap>;
672
- startAfter(...values: unknown[]): CollectionQuery<T, TPresetMap>;
673
- endAt(...values: unknown[]): CollectionQuery<T, TPresetMap>;
674
- endBefore(...values: unknown[]): CollectionQuery<T, TPresetMap>;
675
- aggregate(...specs: AggregateSpec[]): CollectionQuery<T, TPresetMap>;
676
- count(alias?: string): CollectionQuery<T, TPresetMap>;
677
- sum(field: string, alias?: string): CollectionQuery<T, TPresetMap>;
678
- avg(field: string, alias?: string): CollectionQuery<T, TPresetMap>;
679
- min(field: string, alias?: string): CollectionQuery<T, TPresetMap>;
680
- max(field: string, alias?: string): CollectionQuery<T, TPresetMap>;
681
- distinct(field: string, alias?: string): CollectionQuery<T, TPresetMap>;
682
- groupBy(...fields: string[]): CollectionQuery<T, TPresetMap>;
683
- having(field: string, op: HavingClause['op'], value: number): CollectionQuery<T, TPresetMap>;
684
- private buildStructuredJoin;
685
- private cloneStructuredJoin;
686
- private appendNestedJoinByAlias;
687
- private parseRelationRef;
688
- /**
689
- * Join another collection into this query.
690
- *
691
- * @param collectionName Joined collection name.
692
- * @param j Join mapping clause.
693
- * @example
694
- * flare.collection("boards")
695
- * .join("tasks", { source: "id", target: "boardId", as: "tasks" })
696
- * .get();
697
- */
698
- join(collectionName: string, j: JoinClause): CollectionQuery<T, TPresetMap>;
699
- /**
700
- * Append a nested join under an existing join alias.
701
- * Example:
702
- * .join("lists", { source: "id", target: "boardId", as: "lists" })
703
- * .joinNested("lists", "cards", { source: "id", target: "listId", as: "cards" })
704
- */
705
- joinNested(parentAlias: string, collectionName: string, j: JoinClause): CollectionQuery<T, TPresetMap>;
706
- Join(collectionName: string, j: JoinClause): CollectionQuery<T, TPresetMap>;
707
- JoinNested(parentAlias: string, collectionName: string, j: JoinClause): CollectionQuery<T, TPresetMap>;
708
- /**
709
- * SQL-like relation shorthand.
710
- * Example: .withRelation("team.uid->users.id", { as: "teamMembers" })
711
- */
712
- withRelation(relation: string, options?: (Omit<JoinClause, 'source' | 'target' | 'as'> & {
713
- as?: string;
714
- })): CollectionQuery<T, TPresetMap>;
715
- select(...fields: string[]): CollectionQuery<T, TPresetMap>;
716
- /** Returns unique values for a single field */
717
- distinctField(field: string): CollectionQuery<T, TPresetMap>;
718
- /**
719
- * KNN nearest-neighbour search (requires Atlas vector index).
720
- * @example
721
- * col.vectorSearch({ field: "embedding", vector: [...1536 numbers...], k: 10 })
722
- */
723
- vectorSearch(opts: VectorSearchClause): CollectionQuery<T, TPresetMap>;
724
- getRawQuery(): {
725
- collection: string;
726
- query: StructuredQuery;
727
- };
728
- get(): Promise<T[]>;
729
- first(): Promise<T | null>;
730
- last(): Promise<T | null>;
731
- private _isStructured;
732
- private _execute;
733
- private _executeQuery;
734
- private _executeSubscribe;
735
- then<TResult1 = T[], TResult2 = never>(onfulfilled?: ((value: T[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): PromiseLike<TResult1 | TResult2>;
736
- /**
737
- * Subscribe to real-time updates.
738
- * The full StructuredQuery (including orderBy, where, limit, offset) is sent
739
- * to the server so the initial snapshot respects all constraints.
740
- * Individual change events are then sorted / filtered client-side to keep
741
- * the live result consistent.
742
- */
743
- onSnapshot(callback: SubscriptionCallback<T[]>): SubscriptionHandle;
744
- /**
745
- * High-throughput stream wrapper for bursty collections (chat, feeds, logs).
746
- * It keeps local state and flushes change bursts in batches to reduce UI churn.
747
- */
748
- stream(options?: CollectionStreamOptions<T>): CollectionStream<T>;
749
- /**
750
- * Framework-agnostic external-store bridge.
751
- * Compatible with UI hooks expecting subscribe/getSnapshot signatures.
752
- */
753
- asStore(options?: CollectionStreamOptions<T>): CollectionExternalStore<T>;
754
- onDocAdded(callback: DocAddedCallback<T>): () => void;
755
- onDocUpdated(callback: DocUpdatedCallback<T>): () => void;
756
- onDocDeleted(callback: DocDeletedCallback<T>): () => void;
757
- onDocChanged(callback: DocChangedCallback<T>): () => void;
758
- add(data: Partial<T>): Promise<DocumentReference<T>>;
759
- update(data: Partial<T>): DocumentQueryBuilder<T>;
760
- delete(): DocumentQueryBuilder<T>;
761
- }
762
-
763
- /** Client Request */
764
- declare enum FlareAction {
765
- SUBSCRIBE = "subscribe",
766
- UNSUBSCRIBE = "unsubscribe",
767
- WRITE = "write",
768
- DELETE = "delete",
769
- AUTH = "auth",
770
- PING = "ping",
771
- OFFLINE_SYNC = "offline_sync",
772
- CALL = "call",
773
- /** One-shot rich query (no real-time subscription) */
774
- QUERY = "query",
775
- /** Presence */
776
- PRESENCE_JOIN = "presence_join",
777
- PRESENCE_LEAVE = "presence_leave",
778
- PRESENCE_HEARTBEAT = "presence_heartbeat"
779
- }
780
- /** Server Response */
781
- declare enum FlareEvent {
782
- SNAPSHOT = "snapshot",
783
- CHANGE = "change",
784
- ERROR = "error",
785
- ACK = "ack",
786
- PONG = "pong",
787
- AUTH_OK = "auth_ok",
788
- OFFLINE_ACK = "offline_ack",
789
- CALL_RESPONSE = "call_response",
790
- QUERY_RESULT = "query_result",
791
- PRESENCE_STATE = "presence_state",
792
- PRESENCE_JOIN = "presence_join",
793
- PRESENCE_LEAVE = "presence_leave"
794
- }
795
- interface BaseMessage {
796
- id: string;
797
- type: FlareAction | FlareEvent;
798
- ts: number;
799
- }
800
- interface SubscribeMessage extends BaseMessage {
801
- type: FlareAction.SUBSCRIBE;
802
- collection: string;
803
- docId?: string;
804
- query?: Record<string, unknown>;
805
- skipSnapshot?: boolean;
806
- resumeToken?: string;
807
- }
808
-
809
- type TransportOptions = {
810
- url: string;
811
- onMessage: (data: any) => void;
812
- onOpen?: () => void;
813
- onClose?: () => void;
814
- onError?: (error: Error) => void;
815
- autoReconnect?: boolean;
816
- reconnectDelay?: number;
817
- maxReconnectDelay?: number;
818
- debug?: boolean;
819
- /** RSA public key (PEM). When set, all outgoing messages are RSA-OAEP encrypted. */
820
- publicKey?: string;
821
- };
822
-
823
- declare class FlareTransport {
824
- private socket;
825
- private reconnectInterval;
826
- private maxReconnectDelay;
827
- private isConnected;
828
- private shouldReconnect;
829
- private options;
830
- private messageQueue;
831
- private heartbeatInterval;
832
- private connectionTimeout;
833
- constructor(options: TransportOptions);
834
- connect(): void;
835
- private handleReconnect;
836
- private startHeartbeat;
837
- private stopHeartbeat;
838
- private flushQueue;
839
- send(message: object): void;
840
- disconnect(): void;
841
- get connected(): boolean;
842
- private log;
843
- }
844
-
845
- type ConnectionListener = (state: ConnectionState) => void;
846
- type ErrorListener = (error: Error) => void;
847
- type HttpResponseSnapshot = {
848
- status: number;
849
- headers: Record<string, string>;
850
- data: any;
851
- };
852
- type ActiveSubscription = {
853
- baseId: string;
854
- liveId: string;
855
- collection: string;
856
- docId?: string;
857
- query?: StructuredQuery;
858
- callback: SubscriptionCallback;
859
- options: SubscribeOptions;
860
- };
861
- type QueryPresetHandler<Params extends Record<string, unknown> = Record<string, unknown>, Row = any> = (ref: CollectionQuery<any, any>, params: Params) => CollectionQuery<Row, any>;
862
- /** Embedder function registered by the user */
863
- type EmbedFn = (text: string) => Promise<number[]>;
864
- declare class FlareBase<TPresetMap extends QueryPresetMap = {}> {
865
- protected transport: FlareTransport;
866
- protected readonly config: FlareConfig;
867
- protected readonly pendingAcks: Map<string, (value: any) => void>;
868
- protected readonly subscriptions: Map<string, SubscriptionCallback>;
869
- protected readonly activeSubscriptions: Map<string, ActiveSubscription>;
870
- protected readonly queryPresets: Map<string, QueryPresetHandler<any, any>>;
871
- protected readonly subscriptionErrorHandlers: Map<string, Set<SubscriptionErrorCallback>>;
872
- protected readonly subscriptionPermissionHandlers: Map<string, Set<SubscriptionErrorCallback>>;
873
- protected readonly subscriptionLastErrors: Map<string, SubscriptionError>;
874
- protected readonly offlineQueue: any[];
875
- protected currentState: ConnectionState;
876
- protected connectionListeners: ConnectionListener[];
877
- protected errorListeners: ErrorListener[];
878
- protected isDebug: boolean;
879
- protected socketAuthUid: string;
880
- protected pendingSubscriptionReplay: boolean;
881
- protected subscriptionReplayPromise: Promise<void>;
882
- protected requestTraceSeq: number;
883
- protected requestTimingEnabled: boolean;
884
- protected httpInFlight: Map<string, Promise<HttpResponseSnapshot>>;
885
- protected httpResponseCache: Map<string, HttpResponseSnapshot>;
886
- protected readonly maxHttpCacheEntries = 200;
887
- protected presenceCallbacks: Map<string, PresenceCallback[]>;
888
- protected presenceJoinCbs: Map<string, PresenceJoinCallback[]>;
889
- protected presenceLeaveCbs: Map<string, PresenceLeaveCallback[]>;
890
- protected presenceHeartbeatTimer?: ReturnType<typeof setInterval>;
891
- protected embedder?: EmbedFn;
892
- protected vectorSchema: Map<string, Map<string, VectorFieldConfig>>;
893
- protected throwFetchFlareError(payload: unknown, fallbackMessage: string, fallbackCode: string): never;
894
- protected nowMs(): number;
895
- protected normalizeHeaders(headers?: HeadersInit): Record<string, string>;
896
- protected redactHeaders(headers: Record<string, string>): Record<string, string>;
897
- protected stableStringify(value: unknown): string;
898
- protected buildHttpCacheKey(method: string, url: string, headers: Record<string, string>, body: unknown, credentials?: RequestCredentials): string;
899
- protected shouldCacheResponse(method: string, url: string): boolean;
900
- protected rememberHttpResponse(key: string, value: HttpResponseSnapshot): void;
901
- protected createTimedFetchTrace(snapshot: HttpResponseSnapshot, requestId: number, startedAtMs: number, method: string, url: string, networkMs: number): {
902
- response: {
903
- status: number;
904
- ok: boolean;
905
- headers: {
906
- get: (name: string) => string | null;
907
- };
908
- json: () => Promise<any>;
909
- };
910
- requestId: number;
911
- startedAtMs: number;
912
- networkMs: number;
913
- method: string;
914
- url: string;
915
- };
916
- protected logHttpTiming(...args: any[]): void;
917
- protected mergeHeaders(base: HeadersInit | undefined, extra: Record<string, string>): HeadersInit;
918
- protected toWireField(field: string): string;
919
- protected fromWireField(field: string): string;
920
- protected normalizeOutboundData(value: unknown): unknown;
921
- protected normalizeInboundData(value: unknown): unknown;
922
- private getDataMapper;
923
- private runMapper;
924
- private applyJoinAliasMappers;
925
- mapInboundResult(collection: string, payload: unknown, query?: StructuredQuery): unknown;
926
- protected normalizeOutboundAnyFilter(filter: Record<string, unknown>): Record<string, unknown>;
927
- protected normalizeOutboundQuery(query: unknown): unknown;
928
- protected timedFetch(label: string, input: string, init?: RequestInit): Promise<{
929
- response: {
930
- status: number;
931
- ok: boolean;
932
- headers: {
933
- get: (name: string) => string | null;
934
- };
935
- json: () => Promise<any>;
936
- };
937
- requestId: number;
938
- startedAtMs: number;
939
- networkMs: number;
940
- method: string;
941
- url: string;
942
- }>;
943
- protected parseJsonWithTiming(label: string, trace: {
944
- requestId: number;
945
- startedAtMs: number;
946
- response: {
947
- status: number;
948
- ok: boolean;
949
- headers: {
950
- get: (name: string) => string | null;
951
- };
952
- json: () => Promise<any>;
953
- };
954
- networkMs: number;
955
- method: string;
956
- url: string;
957
- }): Promise<any>;
958
- protected getHttpBase(): string;
959
- protected log(...args: any[]): void;
960
- constructor(config: FlareConfig);
961
- connect(): void;
962
- disconnect(): void;
963
- get connectionState(): ConnectionState;
964
- get isConnected(): boolean;
965
- onConnectionStateChange(listener: ConnectionListener): () => void;
966
- onError(callback: ErrorListener): () => void;
967
- collection<T = any>(name: string): CollectionQuery<T, TPresetMap>;
968
- registerQueryPreset<Name extends string, Params extends Record<string, unknown>, Row = any>(name: Name, handler: QueryPresetHandler<Params, Row>): this & FlareBase<TPresetMap & Record<Name, QueryPresetSpec<Params, Row>>>;
969
- registerQueryPresets<TRegistry extends Record<string, QueryPresetHandler<any, any>>>(presets: TRegistry): this & FlareBase<TPresetMap & {
970
- [K in keyof TRegistry]: TRegistry[K] extends QueryPresetHandler<infer Params, infer Row> ? QueryPresetSpec<Params, Row> : QueryPresetSpec<Record<string, unknown>, any>;
971
- }>;
972
- hasQueryPreset(name: string): boolean;
973
- applyQueryPreset<Name extends keyof TPresetMap & string>(ref: CollectionReference<any, TPresetMap>, name: Name, params: QueryPresetParams<TPresetMap[Name]>): CollectionQuery<QueryPresetRow<TPresetMap[Name]>, TPresetMap>;
974
- applyQueryPreset<T = any>(ref: CollectionQuery<T, TPresetMap>, name: string, params?: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
975
- doc<T = any>(collection: string): DocumentQueryBuilder<T>;
976
- doc<T = any>(collection: string, id: string): DocumentReference<T>;
977
- ping(): Promise<number>;
978
- call<T = Record<string, unknown>>(topic: string, payload?: Record<string, unknown>): Promise<T>;
979
- query<T = Record<string, unknown>>(collection: string, q?: StructuredQuery): Promise<T[]>;
980
- setEmbedder(fn: EmbedFn): void;
981
- markVectorField(collection: string, field: string, config?: VectorFieldConfig): void;
982
- embedVectorFields(collection: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
983
- joinPresence(room: string, meta?: Record<string, unknown>): Promise<() => void>;
984
- leavePresence(room: string): Promise<void>;
985
- onPresenceState(room: string, cb: PresenceCallback): () => void;
986
- onPresenceJoin(room: string, cb: PresenceJoinCallback): () => void;
987
- onPresenceLeave(room: string, cb: PresenceLeaveCallback): () => void;
988
- private _startPresenceHeartbeat;
989
- private _stopPresenceHeartbeat;
990
- syncOffline(): Promise<void>;
991
- protected beforeActivateSubscription(_entry: ActiveSubscription): Promise<void>;
992
- protected activateSubscription(entry: ActiveSubscription): Promise<void>;
993
- protected toSubscriptionError(err: unknown): SubscriptionError;
994
- protected emitSubscriptionError(baseId: string, error: SubscriptionError): void;
995
- protected replayActiveSubscriptions(): Promise<void>;
996
- subscribe(subId: string, collection: string, docId: string | undefined, query: StructuredQuery | undefined, callback: SubscriptionCallback, options?: SubscribeOptions): SubscriptionHandle;
997
- send(type: FlareAction, payload: any): Promise<any>;
998
- private handleTransportError;
999
- protected onConnected(): void;
1000
- protected onDisconnected(): void;
1001
- protected setState(state: ConnectionState): void;
1002
- protected handleIncoming(msg: any): void;
1003
- }
1004
-
1005
- declare class FlareAuth<TPresetMap extends QueryPresetMap = {}> extends FlareBase<TPresetMap> {
1006
- static AUTH_TRACE_STORAGE_KEY: string;
1007
- protected pushServiceWorkerInitPromise?: Promise<ServiceWorkerRegistration | null>;
1008
- /** Current authentication configuration */
1009
- protected userId?: string;
1010
- protected authToken?: string;
1011
- protected authTicket?: string;
1012
- protected authConfig?: FlareAuthConfig;
1013
- protected authStateListeners: AuthStateListener[];
1014
- protected authConfigListeners: AuthConfigListener[];
1015
- protected authSession: FlareAuthSession | null;
1016
- protected currentProfile: FlareAuthUser | undefined;
1017
- protected authBootstrapAttempted: boolean;
1018
- protected authBootstrapPromise?: Promise<void>;
1019
- protected socketAuthSyncPromise?: Promise<void>;
1020
- /** In-memory CSRF token extracted from the `x-flare-csrf` response header */
1021
- protected csrfToken?: string;
1022
- protected csrfBootstrapAttempted: boolean;
1023
- protected csrfInitPromise?: Promise<void>;
1024
- protected isAuthTraceEnabled(): boolean;
1025
- protected traceAuth(event: string, details?: Record<string, unknown>): void;
1026
- setAuthTrace(enabled: boolean, persist?: boolean): void;
1027
- protected fetchAuthMe(token?: string): Promise<{
1028
- id?: string;
1029
- email?: string | null;
1030
- email_verified?: boolean;
1031
- }>;
1032
- isBootstrapAttempted(): boolean;
1033
- hydrateAuthState(input: FlareAuthHydrationInput | null, options?: FlareAuthHydrationOptions): Promise<void>;
1034
- loadAuthConfig(): Promise<FlareAuthConfig>;
1035
- onAuthConfigLoaded(listener: AuthConfigListener): () => void;
1036
- onAuthStateChanged(listener: AuthStateListener): () => void;
1037
- getCurrentUser(): FlareAuthUser | undefined;
1038
- getAuthTicket(): string | undefined;
1039
- consumeAuthTicket(): string | undefined;
1040
- private getDefaultCsrfCookieName;
1041
- /**
1042
- * Extract CSRF token from a server response.
1043
- * The server now sends it ONLY as the `x-flare-csrf` response header
1044
- * (not in the JSON body). We still support the body field as a fallback
1045
- * for older server versions.
1046
- */
1047
- protected extractCsrfToken(json: unknown, response?: {
1048
- headers: {
1049
- get: (name: string) => string | null;
1050
- };
1051
- }): string | undefined;
1052
- getCsrfHeaders(): Record<string, string>;
1053
- getCsrfCookieName(): string;
1054
- /**
1055
- * Read the CSRF token from a browser-readable cookie (set by the server as
1056
- * a non-HttpOnly fallback) or fall back to the in-memory value captured
1057
- * from the response header.
1058
- *
1059
- * Priority:
1060
- * 1. Non-HttpOnly cookie on the current domain (browser only)
1061
- * 2. In-memory value from `x-flare-csrf` response header
1062
- */
1063
- getCsrfToken(): string | null;
1064
- ensureCsrfProtection(): Promise<void>;
1065
- protected setAuthSession(session: FlareAuthSession | null, source?: string): void;
1066
- protected emitAuthState(): void;
1067
- protected setProfile(profile: FlareAuthUser): void;
1068
- protected ensureSessionForSocketAuth(reason: string): Promise<boolean>;
1069
- refreshAuthSession(refresh_token?: string): Promise<FlareAuthSession | null>;
1070
- protected updateSocketIdentity(uid?: string, forceReplay?: boolean): Promise<void>;
1071
- protected waitUntilConnected(): Promise<void>;
1072
- protected syncSocketAuth(accessToken?: string | null): Promise<void>;
1073
- protected beforeActivateSubscription(_entry: any): Promise<void>;
1074
- /**
1075
- * Fetch a fresh one-time WebSocket ticket from the server.
1076
- * Called on reconnect when neither an access token nor a cached ticket exists.
1077
- * Requires `config.ticketRefreshUrl` to be configured.
1078
- */
1079
- protected fetchFreshTicket(): Promise<string | null>;
1080
- protected onConnected(): void;
1081
- private toUint8ArrayFromBase64Url;
1082
- private encodePushTokenFromSubscription;
1083
- private fetchPushSetupConfig;
1084
- setupPushServiceWorker(): Promise<ServiceWorkerRegistration | null>;
1085
- requestPushPermission(): Promise<NotificationPermission>;
1086
- acquireBrowserPushToken(options?: BrowserPushTokenOptions): Promise<{
1087
- token: string;
1088
- subscription: PushSubscription;
1089
- }>;
1090
- enableBrowserPush(options?: BrowserPushRegistrationOptions): Promise<{
1091
- registered: boolean;
1092
- appId: string;
1093
- uid: string;
1094
- token: string;
1095
- platform?: string;
1096
- subscription: PushSubscription;
1097
- }>;
1098
- registerPushToken(input: RegisterPushTokenInput): Promise<{
1099
- registered: boolean;
1100
- appId: string;
1101
- uid: string;
1102
- token: string;
1103
- platform?: string;
1104
- }>;
1105
- unregisterPushToken(token: string, authAppId?: string): Promise<{
1106
- unregistered: boolean;
1107
- appId: string;
1108
- token: string;
1109
- removed: boolean;
1110
- }>;
1111
- sendPushNotification(input: SendPushNotificationInput): Promise<PushSendResult>;
1112
- auth(token: string): Promise<AuthResult>;
1113
- private getAuthRequestContentType;
1114
- private buildAuthRequestBody;
1115
- protected requestEmailPasswordToken(email: string, password: string, scope?: string[]): Promise<AuthToken & {
1116
- kind: string;
1117
- }>;
1118
- signInWithEmailAndPassword(email: string, password: string, options?: {
1119
- scope?: string[];
1120
- createIfMissing?: boolean;
1121
- }): Promise<AuthResult & {
1122
- kind?: string;
1123
- accessToken: string;
1124
- refreshToken: string | null;
1125
- authToken: AuthToken;
1126
- created?: boolean;
1127
- }>;
1128
- signInWithEmail(email: string, password: string, options?: {
1129
- scope?: string[];
1130
- createIfMissing?: boolean;
1131
- }): Promise<AuthResult & {
1132
- kind?: string;
1133
- accessToken: string;
1134
- refreshToken: string | null;
1135
- authToken: AuthToken;
1136
- created?: boolean;
1137
- }>;
1138
- createUserWithEmail(email: string, password: string, options?: {
1139
- scope?: string[];
1140
- additionalParams?: Record<string, string>;
1141
- signInIfAllowed?: boolean;
1142
- }): Promise<{
1143
- kind?: string;
1144
- verificationRequired: true;
1145
- verification_required: true;
1146
- emailSent: boolean;
1147
- email_sent: boolean;
1148
- message?: string;
1149
- preview?: {
1150
- code: string;
1151
- link: string;
1152
- };
1153
- } | (AuthResult & {
1154
- kind?: string;
1155
- accessToken: string;
1156
- access_token: string;
1157
- token_type: string;
1158
- expires_in: number;
1159
- refreshToken: string | null;
1160
- refresh_token: string | null;
1161
- scope: string;
1162
- expires_at: string | number;
1163
- sid: string;
1164
- authToken: AuthToken;
1165
- auth_token: AuthToken;
1166
- verificationRequired: false;
1167
- verification_required: false;
1168
- emailSent: boolean;
1169
- email_sent: boolean;
1170
- preview?: {
1171
- code: string;
1172
- link: string;
1173
- };
1174
- })>;
1175
- createUserWithEmailAndPassword(email: string, password: string, options?: {
1176
- scope?: string[];
1177
- additionalParams?: Record<string, string>;
1178
- signInIfAllowed?: boolean;
1179
- }): Promise<{
1180
- kind?: string;
1181
- verificationRequired: true;
1182
- verification_required: true;
1183
- emailSent: boolean;
1184
- email_sent: boolean;
1185
- message?: string;
1186
- preview?: {
1187
- code: string;
1188
- link: string;
1189
- };
1190
- } | (AuthResult & {
1191
- kind?: string;
1192
- accessToken: string;
1193
- access_token: string;
1194
- token_type: string;
1195
- expires_in: number;
1196
- refreshToken: string | null;
1197
- refresh_token: string | null;
1198
- scope: string;
1199
- expires_at: string | number;
1200
- sid: string;
1201
- authToken: AuthToken;
1202
- auth_token: AuthToken;
1203
- verificationRequired: false;
1204
- verification_required: false;
1205
- emailSent: boolean;
1206
- email_sent: boolean;
1207
- preview?: {
1208
- code: string;
1209
- link: string;
1210
- };
1211
- })>;
1212
- signInOrCreateWithEmail(email: string, password: string, options?: {
1213
- scope?: string[];
1214
- additionalParams?: Record<string, string>;
1215
- }): Promise<{
1216
- kind?: string;
1217
- verificationRequired: true;
1218
- created: true;
1219
- emailSent: boolean;
1220
- preview?: {
1221
- code: string;
1222
- link: string;
1223
- };
1224
- } | (AuthResult & {
1225
- accessToken: string;
1226
- refreshToken: string | null;
1227
- authToken: AuthToken;
1228
- created: boolean;
1229
- })>;
1230
- signInOrCreateWithEmailAndPassword(email: string, password: string, options?: {
1231
- scope?: string[];
1232
- additionalParams?: Record<string, string>;
1233
- }): Promise<{
1234
- kind?: string;
1235
- verificationRequired: true;
1236
- created: true;
1237
- emailSent: boolean;
1238
- preview?: {
1239
- code: string;
1240
- link: string;
1241
- };
1242
- } | (AuthResult & {
1243
- accessToken: string;
1244
- refreshToken: string | null;
1245
- authToken: AuthToken;
1246
- created: boolean;
1247
- })>;
1248
- sendEmailVerification(email: string): Promise<{
1249
- sent: boolean;
1250
- emailSent: boolean;
1251
- preview?: {
1252
- code: string;
1253
- link: string;
1254
- };
1255
- }>;
1256
- verifyEmailWithCode(email: string, code: string): Promise<{
1257
- verified: boolean;
1258
- email: string;
1259
- }>;
1260
- confirmEmailLink(token: string, email: string): Promise<{
1261
- verified: boolean;
1262
- email: string;
1263
- }>;
1264
- sendAccountRecovery(email: string): Promise<{
1265
- kind?: string;
1266
- sent: boolean;
1267
- emailSent?: boolean;
1268
- preview?: {
1269
- code: string;
1270
- token: string;
1271
- };
1272
- }>;
1273
- recoverAccountWithCode(email: string, code: string, newPassword: string): Promise<{
1274
- recovered: boolean;
1275
- email: string;
1276
- sessionsRevoked?: number;
1277
- }>;
1278
- recoverAccountWithToken(token: string, newPassword: string): Promise<{
1279
- recovered: boolean;
1280
- email: string;
1281
- sessionsRevoked?: number;
1282
- }>;
1283
- signOut(): Promise<void>;
1284
- protected registerWithEmail(email: string, password: string, options?: {
1285
- scope?: string[];
1286
- additionalParams?: Record<string, string>;
1287
- signInIfAllowed?: boolean;
1288
- }): Promise<Record<string, any>>;
1289
- }
1290
-
1291
- /**
1292
- * Client/index.ts ─ entry point
1293
- *
1294
- * FlareClient is the public-facing class. All logic lives in:
1295
- * - Client/base.ts → transport, subscriptions, presence, vector, offline
1296
- * - Client/auth.ts → CSRF capture, all auth & session methods
1297
- *
1298
- * CSRF Protection (SSR-Only by Default)
1299
- * ────────────────────────────────────
1300
- * FlareClient does NOT automatically fetch CSRF on construction. Instead:
1301
- *
1302
- * 1. SSR (Next.js): Middleware fetches /auth/config once, sets CSRF as HttpOnly
1303
- * cookie on response. Methods automatically use this cookie (no extra calls).
1304
- *
1305
- * 2. Browser-only (SPA): Explicitly call client.ensureCsrfProtection() before
1306
- * mutations to fetch /auth/config and cache CSRF token in memory.
1307
- *
1308
- * Why? Eliminates redundant /auth/config calls in SSR, where every method used
1309
- * to fetch it again internally. Now CSRF bootstrapping happens once (in middleware),
1310
- * and auth methods just use getCsrfHeaders() which returns the cached token
1311
- * (if available) or empty object (relying on HttpOnly cookie validation).
1312
- *
1313
- * This file wires FlareAuth together and leaves CSRF bootstrapping to the user.
1314
- */
1315
-
1316
- declare class FlareClient<TPresetMap extends QueryPresetMap = {}> extends FlareAuth<TPresetMap> {
1317
- private autoPushRegisteredIdentity?;
1318
- constructor(config: FlareConfig);
1319
- private enableAutoPushNotificationsAfterAuth;
1320
- autoEnablePushNotifications(): Promise<void>;
1321
- }
1322
-
1323
5
  /**
1324
6
  * Client/proxy.ts ─ Next.js SSR CSRF proxy helper
1325
7
  *
@@ -1508,4 +190,4 @@ declare const getFlare: () => FlareClient | null;
1508
190
  */
1509
191
  declare const disconnectFlare: () => void;
1510
192
 
1511
- export { type AggregateFunction, type AggregateSpec, type AndFilter, type AnyFilter, type AuthConfigListener, type AuthConfigResponse, type AuthResult, type AuthStateListener, type AuthWithPendingVerificationResult, type AuthWithTokenResult, type BaseMessage, type BrowserPushRegistrationOptions, type BrowserPushTokenOptions, type ChangeEvent, type ChangeOperation, type CollectionExternalStore, type CollectionPresetMethods, type CollectionQuery, CollectionReference, type CollectionStream, type CollectionStreamListener, type CollectionStreamMeta, type CollectionStreamOptions, type ConnectionState, type CsrfProxyConfig, type CursorValue, type DataMapperFn, type DataMapperRegistry, type DocAddedCallback, type DocChangedCallback, type DocDeletedCallback, type DocUpdatedCallback, DocumentQueryBuilder, DocumentReference, type DocumentSnapshot, type EmailLinkVerifyResult, type EmailSendResult, FlareAction, type FlareAuthConfig, type FlareAuthHydrationInput, type FlareAuthHydrationOptions, type FlareAuthProviderId, type FlareAuthProviderPublicConfig, type FlareAuthSession, type FlareAuthUser, FlareClient, type FlareConfig, FlareError, FlareErrors, FlareEvent, FlareResponseCodes, type FlareRule, type GroupByClause, type HavingClause, type JoinClause, type JoinQueryPattern, type NestedJoinClause, type OfflineOperation, type OrFilter, type OrderByClause, type PresenceCallback, type PresenceJoinCallback, type PresenceLeaveCallback, type PresenceMember, type PushSendResult, type QueryConfig, type QueryOperator, type QueryPresetMap, type QueryPresetParams, type QueryPresetRow, type QueryPresetSpec, type QuerySnapshot, type RegisterPushTokenInput, type RulePermission, type SecurityRuleEntry, type SecurityRulesMap, type SendEmailInput, type SendPushNotificationInput, type SnapshotEvent, type StreamFlushReason, type StructuredJoinClause, type StructuredQuery, type SubscribeMessage, type SubscribeOptions, type SubscriptionCallback, type SubscriptionData, type SubscriptionError, type SubscriptionErrorCallback, type SubscriptionHandle, type VectorFieldConfig, type VectorSearchClause, type VerifyEmailLinkInput, type WhereCondition, buildFlareHeaders, connectApp, createCsrfProxy, createCsrfProxyHandler, disconnectFlare, extractCsrfFromRequest, flareRulesToSecurityMap, getFlare, parseValue, parseWhereCondition, securityMapToFlareRules };
193
+ export { type AuthConfigResponse, type CsrfProxyConfig, FlareClient, FlareConfig, FlareError, FlareErrors, FlareResponseCodes, buildFlareHeaders, connectApp, createCsrfProxy, createCsrfProxyHandler, disconnectFlare, extractCsrfFromRequest, getFlare };