@zuzjs/flare 0.2.6 → 0.2.7

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 CHANGED
@@ -158,6 +158,198 @@ await app.sendPushNotification({
158
158
  await app.unregisterPushToken(token);
159
159
  ```
160
160
 
161
+ ### Burst Stream API (Chat, Group Chat, Activity Feeds)
162
+
163
+ Use `stream()` to keep a live in-memory list with batched updates.
164
+ This avoids one render per incoming change during message bursts.
165
+
166
+ ```ts
167
+ const messageStream = app
168
+ .collection('messages')
169
+ .where({ roomId: 'room-1' })
170
+ .latest()
171
+ .limit(200)
172
+ .stream({
173
+ flushMs: 24, // collapse burst updates into short windows
174
+ maxBatchSize: 200, // force flush when queue gets large
175
+ insertAt: 'start', // keep latest-first lists stable for chat UIs
176
+ maxDocs: 200,
177
+ });
178
+
179
+ const stop = messageStream.subscribe((rows, meta) => {
180
+ console.log('rows', rows.length, 'ready', meta.ready, 'reason', meta.reason);
181
+ });
182
+
183
+ // Read current snapshot any time (works well with external-store patterns)
184
+ const currentRows = messageStream.getSnapshot();
185
+
186
+ // Optional subscription-level error hooks
187
+ messageStream
188
+ .onError((err) => console.error('stream error', err))
189
+ .onPermissionDenied((err) => console.error('permission denied', err));
190
+
191
+ // Cleanup
192
+ stop();
193
+ messageStream.close();
194
+ ```
195
+
196
+ #### React.js Example
197
+
198
+ ```tsx
199
+ import { useEffect, useMemo, useState } from 'react';
200
+ import { connectApp } from '@zuzjs/flare';
201
+
202
+ type Message = {
203
+ id: string;
204
+ roomId: string;
205
+ text: string;
206
+ createdAt: number;
207
+ };
208
+
209
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
210
+
211
+ export function RoomMessages({ roomId }: { roomId: string }) {
212
+ const [rows, setRows] = useState<readonly Message[]>([]);
213
+ const [ready, setReady] = useState(false);
214
+
215
+ const stream = useMemo(() => {
216
+ return app
217
+ .collection<Message>('messages')
218
+ .where({ roomId })
219
+ .latest()
220
+ .limit(200)
221
+ .stream({ flushMs: 20, maxBatchSize: 250, insertAt: 'start', maxDocs: 200 });
222
+ }, [roomId]);
223
+
224
+ useEffect(() => {
225
+ const stop = stream.subscribe((nextRows, meta) => {
226
+ setRows(nextRows);
227
+ setReady(meta.ready);
228
+ });
229
+
230
+ return () => {
231
+ stop();
232
+ stream.close();
233
+ };
234
+ }, [stream]);
235
+
236
+ if (!ready) return <p>Loading messages...</p>;
237
+
238
+ return (
239
+ <ul>
240
+ {rows.map((m) => (
241
+ <li key={m.id}>{m.text}</li>
242
+ ))}
243
+ </ul>
244
+ );
245
+ }
246
+ ```
247
+
248
+ #### Next.js Example (Client Component)
249
+
250
+ ```tsx
251
+ 'use client';
252
+
253
+ import { useSyncExternalStore } from 'react';
254
+ import { connectApp } from '@zuzjs/flare';
255
+
256
+ type Message = { id: string; roomId: string; text: string; createdAt: number };
257
+
258
+ const app = connectApp({
259
+ endpoint: process.env.NEXT_PUBLIC_FLARE_ENDPOINT!,
260
+ appId: process.env.NEXT_PUBLIC_FLARE_APP_ID!,
261
+ apiKey: process.env.NEXT_PUBLIC_FLARE_API_KEY,
262
+ });
263
+
264
+ export default function RoomStream({ roomId }: { roomId: string }) {
265
+ const store = app
266
+ .collection<Message>('messages')
267
+ .where({ roomId })
268
+ .latest()
269
+ .limit(200)
270
+ .asStore({ flushMs: 20, maxBatchSize: 250, insertAt: 'start', maxDocs: 200 });
271
+
272
+ const rows = useSyncExternalStore(
273
+ store.subscribe,
274
+ store.getSnapshot,
275
+ store.getServerSnapshot,
276
+ );
277
+
278
+ return (
279
+ <section>
280
+ {rows.map((m) => (
281
+ <p key={m.id}>{m.text}</p>
282
+ ))}
283
+ </section>
284
+ );
285
+ }
286
+ ```
287
+
288
+ #### Redux Example
289
+
290
+ ```ts
291
+ import { createSlice, PayloadAction, configureStore } from '@reduxjs/toolkit';
292
+ import { connectApp } from '@zuzjs/flare';
293
+
294
+ type Message = { id: string; roomId: string; text: string; createdAt: number };
295
+
296
+ const app = connectApp({ endpoint: 'https://flare.zuzcdn.net', appId: 'my-app', apiKey: 'ak' });
297
+
298
+ const messagesSlice = createSlice({
299
+ name: 'messages',
300
+ initialState: [] as Message[],
301
+ reducers: {
302
+ replaceMessages: (_state, action: PayloadAction<readonly Message[]>) => [...action.payload],
303
+ },
304
+ });
305
+
306
+ export const { replaceMessages } = messagesSlice.actions;
307
+ export const store = configureStore({ reducer: { messages: messagesSlice.reducer } });
308
+
309
+ export function startRoomMessageStream(roomId: string): () => void {
310
+ const stream = app
311
+ .collection<Message>('messages')
312
+ .where({ roomId })
313
+ .latest()
314
+ .limit(200)
315
+ .stream({ flushMs: 20, maxBatchSize: 250, insertAt: 'start', maxDocs: 200 });
316
+
317
+ const stop = stream.subscribe((rows) => {
318
+ store.dispatch(replaceMessages(rows));
319
+ });
320
+
321
+ return () => {
322
+ stop();
323
+ stream.close();
324
+ };
325
+ }
326
+ ```
327
+
328
+ ### External Store Bridge (No Framework Dependency)
329
+
330
+ The client also exposes `asStore()` so app code can plug into external-store hooks
331
+ while keeping this package free of framework dependencies.
332
+
333
+ ```ts
334
+ const messageStore = app
335
+ .collection('messages')
336
+ .where({ roomId: 'room-1' })
337
+ .latest()
338
+ .limit(200)
339
+ .asStore({ flushMs: 24, maxBatchSize: 200, insertAt: 'start' });
340
+
341
+ // In app code, pass these to your UI store hook:
342
+ messageStore.subscribe; // (onStoreChange) => unsubscribe
343
+ messageStore.getSnapshot; // () => readonly rows
344
+ messageStore.getServerSnapshot; // () => []
345
+
346
+ // Optional advanced access
347
+ messageStore.stream.onError((err) => console.error(err));
348
+
349
+ // Cleanup
350
+ messageStore.destroy();
351
+ ```
352
+
161
353
  ### Direct Query Helpers (Knex-Style)
162
354
 
163
355
  `collection()` query chaining uses object-based logical steps and dedicated operator families:
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  'use strict';Object.defineProperty(exports,'__esModule',{value:true});var auth=require('@zuzjs/auth'),core=require('@zuzjs/core');/* ZuzFlare Client */
2
- var h=class extends Error{constructor(t,r,i){super(t);this.code=r;this.cause=i;this.name="ZuzFlareError";}};var Z={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},c=Z;var X=(d=>(d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.WRITE="write",d.DELETE="delete",d.AUTH="auth",d.PING="ping",d.OFFLINE_SYNC="offline_sync",d.CALL="call",d.QUERY="query",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d.PRESENCE_HEARTBEAT="presence_heartbeat",d))(X||{}),ee=(d=>(d.SNAPSHOT="snapshot",d.CHANGE="change",d.ERROR="error",d.ACK="ack",d.PONG="pong",d.AUTH_OK="auth_ok",d.OFFLINE_ACK="offline_ack",d.CALL_RESPONSE="call_response",d.QUERY_RESULT="query_result",d.PRESENCE_STATE="presence_state",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d))(ee||{});function M(a){let e=[];for(let[t,r]of Object.entries(a))if(typeof r=="string"){let i=r.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(i){let[,n,s]=i;e.push({field:t,op:n,value:K(s.trim())});}else e.push({field:t,op:"==",value:r});}else Array.isArray(r)?e.push({field:t,op:"in",value:r}):e.push({field:t,op:"==",value:r});return e}function K(a){if(!isNaN(Number(a)))return Number(a);if(a==="true")return true;if(a==="false")return false;if(a==="null")return null;if(a!=="undefined")return a}var k=class{constructor(e,t,r){this.client=e;this.collection=t;this.legacyId=r;}whereCondition;updateData;setData;deleteOp=false;promise;where(e){return this.whereCondition=e,this}update(e){return this.updateData=e,this}set(e){return this.setData=e,this}delete(){return this.deleteOp=true,this}getDocId(){if(this.legacyId)return this.legacyId;if(this.whereCondition&&(this.whereCondition.id||this.whereCondition._id)){let e=this.whereCondition.id??this.whereCondition._id;if(typeof e=="string")return e}throw new h('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',c.QueryFailed)}async execute(){return this._execute()}async _execute(){let e=this.getDocId();if(this.deleteOp){await this.client.send("delete",{collection:this.collection,docId:e});return}if(this.updateData){await this.client.send("write",{collection:this.collection,docId:e,data:this.updateData,merge:true});return}if(this.setData){await this.client.send("write",{collection:this.collection,docId:e,data:this.setData,merge:false});return}return this.get()}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}async get(){let e=this.getDocId(),t=core.uuid2(18);return new Promise((r,i)=>{let n=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(n(),r(s.data));});setTimeout(()=>{n(),i(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),r=core.uuid2(18);return this.client.subscribe(r,this.collection,t,void 0,e)}};var O=class{constructor(e,t,r){this.client=e;this.collection=t;this.id=r;}async get(){return new k(this.client,this.collection,this.id).get()}async set(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:false});}async update(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:true});}async delete(){await this.client.send("delete",{collection:this.collection,docId:this.id});}onSnapshot(e){let t=core.uuid2(18),r=()=>{};return r=this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="snapshot"&&(e(i),r());}),r}onDocUpdated(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data&&e(r.data,r.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&r.operation==="delete"&&e(r.docId);},{skipSnapshot:true})}onDocChanged(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&e(r.data??null,r.docId,r.operation);},{skipSnapshot:true})}},S=O;var _=class a{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(r,i,n)=>{if(typeof i=="string"&&!(i in r)&&this.client.hasQueryPreset(i))return (o={})=>r.with(i,o);let s=Reflect.get(r,i,n);return typeof s=="function"?s.bind(r):s}})}sq={};promise;doc(e){return new S(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}normalizeFilterValue(e,t){return e==="in"||e==="not-in"||e==="array-contains-any"?Array.isArray(t)?t:[t]:t}normalizeFilter(e){return {...e,value:this.normalizeFilterValue(e.op,e.value)}}toQueryFilters(e){return M(e).map(t=>this.normalizeFilter(t))}appendOperatorFilter(e,t,r,i){return this.appendFilters([this.normalizeFilter({field:e,op:t,value:r})],i)}appendAndFilters(e){return this.clone({where:[...this.sq.where??[],...e]})}toOrNode(e){return {or:e}}toAndNode(e){return {and:e}}appendOrFilters(e){let t=[...this.sq.where??[]];if(t.length===0)return this.clone({where:[this.toOrNode(e)]});let r=t[0];if(t.length===1&&typeof r=="object"&&r!=null&&"or"in r){let s=r;return this.clone({where:[{or:[...s.or,...e]}]})}let n=t.length===1?t[0]:{and:t};return this.clone({where:[{or:[n,...e]}]})}appendFilters(e,t){return t==="or"?this.appendOrFilters(e):this.appendAndFilters(e)}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e){return this.appendFilters(this.toQueryFilters(e),"and")}and(e){return this.appendFilters(this.toQueryFilters(e),"and")}or(e){return this.appendFilters(this.toQueryFilters(e),"or")}in(e,t){return this.appendOperatorFilter(e,"in",t,"and")}andIn(e,t){return this.appendOperatorFilter(e,"in",t,"and")}orIn(e,t){return this.appendOperatorFilter(e,"in",t,"or")}notIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}andNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}orNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"or")}arrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}andArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}orArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"or")}arrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}andArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}orArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"or")}some(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}andSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}orSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"or")}like(e,t){return this.appendOperatorFilter(e,"like",t,"and")}andLike(e,t){return this.appendOperatorFilter(e,"like",t,"and")}orLike(e,t){return this.appendOperatorFilter(e,"like",t,"or")}notLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}andNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}orNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"or")}exists(e){return this.appendOperatorFilter(e,"exists",true,"and")}andExists(e){return this.appendOperatorFilter(e,"exists",true,"and")}orExists(e){return this.appendOperatorFilter(e,"exists",true,"or")}notExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}andNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}orNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"or")}latest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"desc"}]})}oldest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"asc"}]})}orderBy(e,t="asc"){return this.clone({orderBy:[...this.sq.orderBy??[],{field:e,dir:t}]})}limit(e){return this.clone({limit:e})}offset(e){return this.clone({offset:e})}startAt(...e){return this.clone({startAt:{values:e}})}startAfter(...e){return this.clone({startAfter:{values:e}})}endAt(...e){return this.clone({endAt:{values:e}})}endBefore(...e){return this.clone({endBefore:{values:e}})}aggregate(...e){return this.clone({aggregate:[...this.sq.aggregate??[],...e]})}count(e="count"){return this.aggregate({fn:"count",alias:e})}sum(e,t){return this.aggregate({fn:"sum",field:e,alias:t??`sum_${e}`})}avg(e,t){return this.aggregate({fn:"avg",field:e,alias:t??`avg_${e}`})}min(e,t){return this.aggregate({fn:"min",field:e,alias:t??`min_${e}`})}max(e,t){return this.aggregate({fn:"max",field:e,alias:t??`max_${e}`})}distinct(e,t){return this.aggregate({fn:"distinct",field:e,alias:t??`distinct_${e}`})}groupBy(...e){return this.clone({groupBy:{fields:e}})}having(e,t,r){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:r}]})}buildStructuredJoin(e,t){let i={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(i.where=t.where),Array.isArray(t?.orderBy)&&(i.orderBy=t.orderBy),typeof t?.limit=="number"&&(i.limit=t.limit),typeof t?.offset=="number"&&(i.offset=t.offset),t?.startAt&&(i.startAt=t.startAt),t?.startAfter&&(i.startAfter=t.startAfter),t?.endAt&&(i.endAt=t.endAt),t?.endBefore&&(i.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(i.aggregate=t.aggregate),t?.groupBy&&(i.groupBy=t.groupBy),Array.isArray(t?.having)&&(i.having=t.having),t?.vectorSearch&&(i.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(i.select=t.select),typeof t?.distinctField=="string"&&(i.distinctField=t.distinctField),Array.isArray(t?.joins)&&(i.joins=t.joins.map(n=>this.buildStructuredJoin(String(n?.collection??""),n))),i}Join(e,t){let r=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],r]})}join(e,t){if(typeof e=="string")return this.Join(e,t);let r=String(e.collection??e.from??""),i=this.buildStructuredJoin(r,e);return this.clone({joins:[...this.sq.joins??[],i]})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}async get(){return this._execute()}_isStructured(){return !!(this.sq.orderBy?.length||this.sq.aggregate?.length||this.sq.groupBy||this.sq.having?.length||this.sq.joins?.length||this.sq.vectorSearch||this.sq.distinctField||this.sq.offset||this.sq.startAt||this.sq.startAfter||this.sq.endAt||this.sq.endBefore||this.sq.select?.length)}async _execute(){return this._isStructured()?this._executeQuery():this._executeSubscribe()}async _executeQuery(){return (await this.client.send("query",{collection:this.collection,query:this.sq})).data??[]}async _executeSubscribe(){let e=core.uuid2(18);return new Promise((t,r)=>{let i=Object.keys(this.sq).length>0?this.sq:void 0,n=this.client.subscribe(e,this.collection,void 0,i,s=>{s.type==="snapshot"&&(n(),t(s.data));});setTimeout(()=>{n(),r(new Error("Collection fetch timeout"));},1e4);})}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}onSnapshot(e){let t=core.uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0,i=(()=>{});return i=this.client.subscribe(t,this.collection,void 0,r,n=>{n.type==="snapshot"&&(e(n),i());}),i}onDocAdded(e){let t=core.uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&i.operation==="insert"&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=core.uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&(i.operation==="update"||i.operation==="replace")&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=core.uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&i.operation==="delete"&&e(i.docId);},{skipSnapshot:true})}onDocChanged(e){let t=core.uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&e(i.data??null,i.docId,i.operation);},{skipSnapshot:true})}async add(e){let t=core.uuid2(18),r=this.doc(t);return await r.set(e),r}update(e){return new k(this.client,this.collection).update(e)}delete(){return new k(this.client,this.collection).delete()}},N=_;async function te(a){let e=a.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,""),t=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary"),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",r.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function ie(a,e){let t=await te(e),r=new TextEncoder().encode(JSON.stringify(a)),n=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,r),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(n))):Buffer.from(n).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var v=class{socket=null;reconnectInterval;maxReconnectDelay;isConnected=false;shouldReconnect=true;options;messageQueue=[];heartbeatInterval=null;connectionTimeout=null;constructor(e){this.options=e,this.reconnectInterval=e.reconnectDelay||2,this.maxReconnectDelay=e.maxReconnectDelay||60,this.log("Transport initialized",e.url);}connect(){if(this.socket){this.log("Socket already exists, skipping connection");return}this.log("Connecting to",this.options.url),this.socket=new WebSocket(this.options.url),this.connectionTimeout=setTimeout(()=>{this.isConnected||(this.log("Connection timeout"),this.socket?.close(),this.handleReconnect());},1e4),this.socket.onopen=()=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=true,this.reconnectInterval=this.options.reconnectDelay||2,this.log("Connected to server"),this.options.onOpen?.(),this.startHeartbeat(),this.flushQueue();},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data);this.options.onMessage(t);}catch(t){this.log("Parse error",t),this.options.onError?.(t);}},this.socket.onerror=e=>{this.log("WebSocket error",e),this.options.onError?.(new Error("WebSocket error"));},this.socket.onclose=e=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=false,this.socket=null,this.stopHeartbeat(),this.log("Connection closed",e.code,e.reason),this.options.onClose?.(),e.code!==1e3&&this.shouldReconnect&&this.options.autoReconnect&&this.handleReconnect();};}handleReconnect(){let e=this.reconnectInterval*1e3;this.log(`Reconnecting in ${this.reconnectInterval}s...`),setTimeout(()=>{this.reconnectInterval=Math.min(this.reconnectInterval*2,this.maxReconnectDelay),this.connect();},e);}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send({type:"ping",id:Date.now().toString(),ts:Date.now()});},3e4);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}flushQueue(){for(this.log("Flushing message queue",this.messageQueue.length);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}send(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){let t=r=>{try{this.socket.send(r),this.log("Sent message",e);}catch(i){this.log("Send error",i),this.messageQueue.push(e);}};this.options.publicKey?ie(e,this.options.publicKey).then(t).catch(r=>{this.log("RSA encrypt error \u2014 sending plaintext",r),t(JSON.stringify(e));}):t(JSON.stringify(e));}else this.log("Socket not ready, queueing message"),this.messageQueue.push(e);}disconnect(){this.shouldReconnect=false,this.stopHeartbeat(),this.socket&&(this.socket.close(1e3,"Client disconnect"),this.socket=null),this.isConnected=false,this.log("Disconnected");}get connected(){return this.isConnected}log(...e){this.options.debug&&console.log("[FlareTransport]",...e);}};var ce={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},q={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},R=class{transport;config;pendingAcks=new Map;subscriptions=new Map;activeSubscriptions=new Map;queryPresets=new Map;subscriptionErrorHandlers=new Map;subscriptionPermissionHandlers=new Map;subscriptionLastErrors=new Map;offlineQueue=[];currentState="disconnected";connectionListeners=[];errorListeners=[];isDebug=false;socketAuthUid="anon";pendingSubscriptionReplay=false;subscriptionReplayPromise=Promise.resolve();requestTraceSeq=0;requestTimingEnabled=true;httpInFlight=new Map;httpResponseCache=new Map;maxHttpCacheEntries=200;presenceCallbacks=new Map;presenceJoinCbs=new Map;presenceLeaveCbs=new Map;presenceHeartbeatTimer;embedder;vectorSchema=new Map;throwFetchFlareError(e,t,r){let i=e,n=typeof i?.error=="string"&&i.error.length>0?i.error:r,s=typeof i?.message=="string"&&i.message.length>0?i.message:t;throw new h(s,n,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((r,i)=>{t[i]=r;});else if(Array.isArray(e))for(let[r,i]of e)t[String(r)]=String(i);else for(let[r,i]of Object.entries(e))t[String(r)]=String(i);return t}redactHeaders(e){let t={...e};for(let r of Object.keys(t)){let i=r.toLowerCase();(i==="authorization"||i==="x-flare-csrf"||i==="x-csrf-token")&&(t[r]="[redacted]");}return t}stableStringify(e){if(e==null)return "";if(typeof e=="string")return e;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return e.toString();if(typeof e!="object")return String(e);if(Array.isArray(e))return `[${e.map(i=>this.stableStringify(i)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(i=>`${i}:${this.stableStringify(t[i])}`).join(",")}}`}buildHttpCacheKey(e,t,r,i,n){let o=Object.entries(r).map(([l,g])=>[l.toLowerCase(),g]).sort(([l],[g])=>l.localeCompare(g)).map(([l,g])=>`${l}:${g}`).join("|"),u=this.stableStringify(i);return `${e}|${t}|${n??""}|${o}|${u}`}shouldCacheResponse(e,t){return !!(e==="GET"||e==="POST"&&/\/auth\/refresh(?:\?|$)/.test(t))}rememberHttpResponse(e,t){if(this.httpResponseCache.set(e,t),this.httpResponseCache.size<=this.maxHttpCacheEntries)return;let r=this.httpResponseCache.keys().next().value;r&&this.httpResponseCache.delete(r);}createTimedFetchTrace(e,t,r,i,n,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:o=>{let u=o.toLowerCase();for(let[l,g]of Object.entries(e.headers))if(l.toLowerCase()===u)return String(g);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:r,networkMs:s,method:i,url:n}}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let r=new Headers(e);for(let[i,n]of Object.entries(t))r.set(i,n);return r}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(ce[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(q[t]?q[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(i=>this.normalizeOutboundData(i));if(!e||typeof e!="object")return e;let t=e,r={};for(let[i,n]of Object.entries(t))r[this.toWireField(i)]=this.normalizeOutboundData(n);return r}normalizeInboundData(e){if(Array.isArray(e))return e.map(i=>this.normalizeInboundData(i));if(!e||typeof e!="object")return e;let t=e,r={};for(let[i,n]of Object.entries(t))r[this.fromWireField(i)]=this.normalizeInboundData(n);return r}normalizeOutboundAnyFilter(e){return Array.isArray(e.or)?{...e,or:e.or.map(t=>this.normalizeOutboundAnyFilter(t))}:Array.isArray(e.and)?{...e,and:e.and.map(t=>this.normalizeOutboundAnyFilter(t))}:typeof e.field=="string"?{...e,field:this.toWireField(e.field)}:{...e}}normalizeOutboundQuery(e){if(!e)return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.field=="string")return this.normalizeOutboundAnyFilter(e);if(Array.isArray(e))return e.map(n=>this.normalizeOutboundAnyFilter(n));if(typeof e!="object")return e;let t=e,r={...t},i=n=>{let s={...n};return s.localField=this.toWireField(String(n?.localField??"")),s.foreignField=this.toWireField(String(n?.foreignField??"")),Array.isArray(n.where)&&(s.where=n.where.map(o=>this.normalizeOutboundAnyFilter(o))),Array.isArray(n.orderBy)&&(s.orderBy=n.orderBy.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),n.groupBy&&typeof n.groupBy=="object"&&Array.isArray(n.groupBy.fields)&&(s.groupBy={...n.groupBy,fields:n.groupBy.fields.map(o=>this.toWireField(String(o??"")))}),Array.isArray(n.having)&&(s.having=n.having.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),Array.isArray(n.select)&&(s.select=n.select.map(o=>this.toWireField(String(o??"")))),typeof n.distinctField=="string"&&(s.distinctField=this.toWireField(n.distinctField)),n.vectorSearch&&typeof n.vectorSearch=="object"&&(s.vectorSearch={...n.vectorSearch,field:this.toWireField(String(n.vectorSearch.field??""))}),Array.isArray(n.joins)&&(s.joins=n.joins.map(o=>i(o))),s};return Array.isArray(t.where)&&(r.where=t.where.map(n=>this.normalizeOutboundAnyFilter(n))),Array.isArray(t.orderBy)&&(r.orderBy=t.orderBy.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(r.groupBy={...t.groupBy,fields:t.groupBy.fields.map(n=>this.toWireField(String(n??"")))}),Array.isArray(t.having)&&(r.having=t.having.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),Array.isArray(t.select)&&(r.select=t.select.map(n=>this.toWireField(String(n??"")))),typeof t.distinctField=="string"&&(r.distinctField=this.toWireField(t.distinctField)),t.vectorSearch&&typeof t.vectorSearch=="object"&&(r.vectorSearch={...t.vectorSearch,field:this.toWireField(String(t.vectorSearch.field??""))}),Array.isArray(t.joins)&&(r.joins=t.joins.map(n=>i(n))),r}async timedFetch(e,t,r){let i=++this.requestTraceSeq,n=this.nowMs(),s=String(r?.method??"GET").toUpperCase(),o=this.normalizeHeaders(r?.headers),u=this.redactHeaders(o),l=r?.body,g=this.buildHttpCacheKey(s,t,o,l,r?.credentials),f=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${i} ${e} start`,{method:s,url:t,headers:u,hasBody:!!r?.body});try{if(f){let b=this.httpResponseCache.get(g);if(b)return this.logHttpTiming(`#${i} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(b,i,n,s,t,0)}let d=this.httpInFlight.get(g);if(d){let b=await d,p=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} deduped`,{method:s,url:t,networkMs:Number(p.toFixed(2))}),this.createTimedFetchTrace(b,i,n,s,t,p)}let w=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(i)}),C=this.normalizeHeaders(w),z=this.redactHeaders(C),A={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:C,withCredentials:r?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${i} ${e} request`,{method:s,url:t,headers:z,hasBody:!!r?.body});let Q=s.toUpperCase(),U=(async()=>{let b=Q==="GET"?await core.withGet(t,A):Q==="PUT"?await core.withPut(t,l,A):Q==="PATCH"?await core.withPatch(t,l,A):await core.withPost(t,l,A),p={status:Number(b?.status??0),headers:Object.fromEntries(Object.entries(b?.headers??{}).map(([G,Y])=>[G,String(Y)])),data:b?.data??{}};return f&&this.rememberHttpResponse(g,p),p})();this.httpInFlight.set(g,U);let W=await U.finally(()=>{this.httpInFlight.delete(g);}),L=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} response`,{status:W.status,networkMs:Number(L.toFixed(2))}),this.createTimedFetchTrace(W,i,n,s,t,L)}catch(d){let w=this.nowMs()-n;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(w.toFixed(2)),message:d?.message??String(d)}),d}}async parseJsonWithTiming(e,t){let r=this.nowMs(),i=await t.response.json().catch(()=>({})),n=this.nowMs()-r,s=this.nowMs()-t.startedAtMs;return this.logHttpTiming(`#${t.requestId} ${e} complete`,{method:t.method,url:t.url,status:t.response.status,networkMs:Number(t.networkMs.toFixed(2)),parseMs:Number(n.toFixed(2)),totalMs:Number(s.toFixed(2))}),i}getHttpBase(){if(this.config.httpBase)return this.config.httpBase.replace(/\/$/,"");let e=new URL(this.config.endpoint);return `${e.protocol}//${e.host}`}log(...e){this.isDebug&&console.log("[FlareClient]",...e);}constructor(e){this.config={autoReconnect:true,reconnectDelay:2,maxReconnectDelay:60,debug:false,connectionTimeout:1e4,...e},this.isDebug=this.config.debug||false,this.requestTimingEnabled=this.config.requestTiming??true;let{hostname:t,port:r,protocol:i}=new URL(this.config.endpoint),n=i==="https:",u=`${n?"wss":"ws"}://${t}:${r||(n?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new v({url:u,publicKey:this.config.publicKey,autoReconnect:this.config.autoReconnect,reconnectDelay:this.config.reconnectDelay,maxReconnectDelay:this.config.maxReconnectDelay,onMessage:l=>this.handleIncoming(l),onOpen:()=>this.onConnected(),onClose:()=>this.onDisconnected(),onError:l=>this.handleTransportError(l),debug:this.isDebug});}connect(){this.setState("connecting"),this.transport.connect();}disconnect(){this.transport.disconnect(),this.setState("disconnected");}get connectionState(){return this.currentState}get isConnected(){return this.currentState==="connected"}onConnectionStateChange(e){return this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e);}}collection(e){return new N(this,e)}registerQueryPreset(e,t){let r=String(e??"").trim();if(!r)throw new h("Preset name is required",c.QueryFailed);if(typeof t!="function")throw new h(`Query preset "${r}" handler must be a function`,c.QueryFailed);return this.queryPresets.set(r,t),this}registerQueryPresets(e){for(let[t,r]of Object.entries(e??{}))this.registerQueryPreset(t,r);return this}hasQueryPreset(e){return this.queryPresets.has(String(e??"").trim())}applyQueryPreset(e,t,r={}){let i=String(t??"").trim(),n=this.queryPresets.get(i);if(!n)throw new h(`Unknown query preset "${i}"`,c.QueryFailed);let s=n(e,r??{});if(!s||typeof s.get!="function")throw new h(`Query preset "${i}" must return a CollectionReference`,c.QueryFailed);return s}doc(e,t){return t!==void 0?new S(this,e,t):new k(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let r=await this.send("call",{topic:e,payload:t});if(!r.success)throw new h(r.error??`CALL "${e}" failed`,c.QueryFailed);return r.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,r={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,r);}async embedVectorFields(e,t){let r=this.vectorSchema.get(e);if(!r)return t;let i={...t};for(let[n,s]of r){let o=i[n];if(typeof o=="string"){let u=s.embed??this.embedder;if(!u){this.log(`[vector] No embedder for field "${n}" \u2014 storing raw text`);continue}i[n]=await u(o);}}return i}async joinPresence(e,t){return await this.send("presence_join",{room:e,meta:t}),this._startPresenceHeartbeat(e,t),()=>this.leavePresence(e)}async leavePresence(e){await this.send("presence_leave",{room:e}),this._stopPresenceHeartbeat();}onPresenceState(e,t){return this.presenceCallbacks.has(e)||this.presenceCallbacks.set(e,[]),this.presenceCallbacks.get(e).push(t),()=>{let r=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,r.filter(i=>i!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let r=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,r.filter(i=>i!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let r=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,r.filter(i=>i!==t));}}_startPresenceHeartbeat(e,t){this.presenceHeartbeatTimer||(this.presenceHeartbeatTimer=setInterval(()=>{this.isConnected&&this.send("presence_heartbeat",{meta:t}).catch(()=>{});},2e4));}_stopPresenceHeartbeat(){this.presenceHeartbeatTimer&&(clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=void 0);}async syncOffline(){if(this.offlineQueue.length===0)return;this.log("Syncing offline operations",this.offlineQueue.length);let e=[...this.offlineQueue];this.offlineQueue.length=0;let t=await this.send("offline_sync",{operations:e});t.conflicts&&t.conflicts.length>0&&(this.log("Offline sync conflicts",t.conflicts),t.conflicts.forEach(r=>{let i=e.find(n=>n.id===r.operationId);i&&this.offlineQueue.push(i);}));}async beforeActivateSubscription(e){}async activateSubscription(e){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}await this.beforeActivateSubscription(e),this.subscriptions.set(e.liveId,e.callback);try{let t=await this.send("subscribe",{collection:e.collection,docId:e.docId,query:e.query,skipSnapshot:e.options.skipSnapshot});if(!this.activeSubscriptions.has(e.baseId)){this.subscriptions.delete(e.liveId);return}t.subscriptionId&&t.subscriptionId!==e.liveId&&(this.subscriptions.delete(e.liveId),e.liveId=t.subscriptionId,this.subscriptions.set(e.liveId,e.callback),this.log("Subscription remapped",e.baseId,"\u2192",e.liveId));}catch(t){this.subscriptions.delete(e.liveId),this.pendingSubscriptionReplay=true;let r=this.toSubscriptionError(t);this.emitSubscriptionError(e.baseId,r),this.log("Subscription failed",t);}}toSubscriptionError(e){let t=e instanceof Error?e.message:String(e??"Unknown subscription error"),r=t.match(/^\[([^\]]+)\]\s*(.*)$/),i=r?.[1],n=(r?.[2]??t).trim()||t,s=i===c.PermissionDenied||t.includes(c.PermissionDenied);return {code:i,message:n,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let r=this.subscriptionErrorHandlers.get(e);if(r)for(let i of r)try{i(t);}catch(n){this.log("Subscription error callback failed",n);}if(t.permissionDenied){let i=this.subscriptionPermissionHandlers.get(e);if(i)for(let n of i)try{n(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let r=t.liveId;this.subscriptions.delete(r),t.liveId=t.baseId,r&&await this.send("unsubscribe",{subscriptionId:r}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,r,i,n,s={}){this.log("Creating subscription",e,t,r);let o={baseId:e,liveId:e,collection:t,docId:r,query:i,callback:n,options:s};this.activeSubscriptions.set(e,o),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(o).catch(g=>{this.log("Subscription activation failed",g);});let u=()=>{let f=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",f),this.activeSubscriptions.delete(e),this.subscriptions.delete(f),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:f}).catch(d=>this.log("Unsubscribe failed",d));},l=u;return l.unsubscribe=u,l.onError=g=>{this.subscriptionErrorHandlers.get(e)?.add(g);let f=this.subscriptionLastErrors.get(e);if(f)try{g(f);}catch(d){this.log("Subscription error callback failed",d);}return l},l.onPermissionDenied=g=>{this.subscriptionPermissionHandlers.get(e)?.add(g);let f=this.subscriptionLastErrors.get(e);if(f?.permissionDenied)try{g(f);}catch(d){this.log("Subscription permission callback failed",d);}return l},l.catch=g=>l.onError(g),l}async send(e,t){if(e==="write"&&t.collection&&t.data){let r=await this.embedVectorFields(t.collection,t.data);t={...t,data:this.normalizeOutboundData(r)};}return (e==="subscribe"||e==="query")&&t?.query&&(t={...t,query:this.normalizeOutboundQuery(t.query)}),new Promise((r,i)=>{let n=core.uuid2(18),s={id:n,type:e,ts:Date.now(),...t};this.pendingAcks.set(n,o=>{o.type==="error"?i(new Error(`[${o.code}] ${o.message}`)):r(o);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),i(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(n)&&(this.pendingAcks.delete(n),i(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(r){this.log("Error listener error",r);}});}onConnected(){this.setState("connected"),this.log("Connected to FlareServer"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.offlineQueue.length>0&&this.syncOffline().catch(e=>{this.log("Offline sync failed",e);});}onDisconnected(){this.currentState!=="disconnected"&&this.setState("reconnecting"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.log("Disconnected from FlareServer");}setState(e){this.currentState!==e&&(this.currentState=e,this.log("Connection state changed",e),this.connectionListeners.forEach(t=>{try{t(e);}catch(r){this.log("Connection listener error",r);}}));}handleIncoming(e){if(this.log("Received message",e.type,e),e.type==="query_result"&&Array.isArray(e.data)&&(e={...e,data:this.normalizeInboundData(e.data)}),e.type==="ack"||e.type==="pong"||e.type==="auth_ok"||e.type==="call_response"||e.type==="query_result"){let t=this.pendingAcks.get(e.correlationId||e.id);t&&(t(e),this.pendingAcks.delete(e.correlationId||e.id));return}if(e.type==="error"){this.log("Server error",e.code,e.message);let t=new Error(`[${e.code}] ${e.message}`);this.errorListeners.forEach(i=>{try{i(t);}catch(n){this.log("Error listener error",n);}});let r=Array.from(this.activeSubscriptions.values()).find(i=>i.liveId===e.correlationId||i.baseId===e.correlationId);if(r&&this.emitSubscriptionError(r.baseId,{code:typeof e.code=="string"?e.code:void 0,message:String(e.message??"Subscription error"),permissionDenied:e.code===c.PermissionDenied,raw:e}),e.correlationId){let i=this.pendingAcks.get(e.correlationId);i&&(i(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(r=>{try{r(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(r=>{try{r(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(r=>{try{r(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),i={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(r)?r:[]};try{t(i);}catch(n){this.log("Subscription callback error",n);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:e.operation==="delete"?null:this.normalizeInboundData(e.data)};try{t(r);}catch(i){this.log("Subscription callback error",i);}}}}};var F=class extends R{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;socketAuthSyncPromise;pushServiceWorkerInitPromise;authSession=null;authStateListeners=[];authConfigListeners=[];currentProfile=void 0;getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return this.getCookieValue(this.getCsrfCookieName())??this.csrfToken??null}getCookieValue(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`)||i.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let r=t.indexOf("=");return r>=0?decodeURIComponent(t.slice(r+1)):null}extractCsrfToken(e,t){let r=e,i=typeof r?.csrfToken=="string"?String(r.csrfToken):typeof r?.csrf_token=="string"?String(r.csrf_token):void 0;if(i)return i;if(!t)return;let n=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof n=="string"&&n.length>0?n:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}setCsrfToken(e){this.csrfToken=e,this.csrfBootstrapAttempted=true,this.log("CSRF token injected",{length:e.length});}async ensureCsrfProtection(){if(this.getCsrfToken()){this.csrfBootstrapAttempted=true;return}if(this.config.httpBase){this.csrfBootstrapAttempted=true;return}this.csrfBootstrapAttempted||(this.csrfInitPromise||(this.csrfBootstrapAttempted=true,this.csrfInitPromise=this.loadAuthConfig().then(()=>{}).finally(()=>{this.csrfInitPromise=void 0;})),await this.csrfInitPromise,this.getCsrfToken()||this.log("CSRF token unavailable after auth config load",{hasAuthConfig:!!this.authConfig,csrfCookieName:this.getCsrfCookieName()}));}async loadAuthConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/auth/config?${t.toString()}`,i=await this.timedFetch("loadAuthConfig",r,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("loadAuthConfig",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to load auth config",c.QueryFailed),this.authConfig=n,this.csrfToken=this.extractCsrfToken(n,i.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(o){this.log("Auth config listener error",o);}}),this.authConfig}async fetchAuthConfig(){return this.authConfig?this.authConfig:this.loadAuthConfig()}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}setProfile(e){this.currentProfile=e;}setAuthSession(e){this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid):(this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear());let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;this.authStateListeners.forEach(r=>{try{r(t);}catch(i){this.log("Auth state listener error",i);}});}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;try{e(t);}catch(r){this.log("Auth state listener error during initialization",r);}return ()=>{this.authStateListeners=this.authStateListeners.filter(r=>r!==e);}}onAuthStateChange(e){return this.onAuthStateChanged(e)}get currentUser(){return this.currentProfile}getCurrentUser(){return this.currentUser}async syncSocketAuth(e){if(!this.isConnected)return;let t=await this.send("auth",e?{token:e}:{});if(t.type!=="auth_ok")throw new h("Socket auth sync failed",c.AuthenticationFailed);if(!e||t.uid==="anon"){this.authToken=void 0,this.userId=void 0,await this.updateSocketIdentity("anon");return}this.authToken=typeof t.token=="string"?t.token:e,this.userId=typeof t.uid=="string"?t.uid:this.userId,await this.updateSocketIdentity(typeof t.uid=="string"?t.uid:this.userId);}async updateSocketIdentity(e,t=false){let r=typeof e=="string"&&e.length>0?e:"anon",i=r!==this.socketAuthUid;this.socketAuthUid=r,(i||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async beforeActivateSubscription(e){if(!this.isConnected)return;let t=this.authSession;!t?.accessToken||!t.uid||this.socketAuthUid!==t.uid&&(this.socketAuthSyncPromise||(this.socketAuthSyncPromise=this.syncSocketAuth(t.accessToken).catch(r=>{throw this.log("Socket auth sync failed before subscribe",r),r}).finally(()=>{this.socketAuthSyncPromise=void 0;})),await this.socketAuthSyncPromise);}onConnected(){super.onConnected(),this.authSession?.accessToken&&this.syncSocketAuth(this.authSession.accessToken).catch(e=>{this.log("Socket auth sync failed after connect",e);});}handleIncoming(e){if(e.type==="auth_ok"&&!e.correlationId){let t=typeof e.token=="string"?e.token:void 0,r=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(r,this.pendingSubscriptionReplay).catch(i=>{this.log("Socket identity update failed",i);}),t&&r&&r!=="anon"&&r!=="__admin__"?this.fetchAuthMe(t).then(i=>{this.setAuthSession({uid:r,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified});}).catch(()=>{this.setAuthSession({uid:r,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):r==="anon"&&this.authSession&&this.setAuthSession(null);}super.handleIncoming(e);}async auth(e){let t=await this.send("auth",{token:e});if(t.type==="auth_ok"){let r=t.token??e;this.authToken=r,this.userId=t.uid;let i=await this.fetchAuthMe(r).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:r,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new h("Authentication failed",c.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,r){try{let i=await this.requestEmailPasswordToken(e,t,r?.scope),n=await this.auth(i.access_token),s=await this.fetchAuthMe(i.access_token).catch(()=>null);return this.setAuthSession({uid:n.uid,accessToken:i.access_token,refreshToken:i.refresh_token,provider:i.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",n.uid),{...n,kind:i.kind,accessToken:i.access_token,refreshToken:i.refresh_token,authToken:i}}catch(i){let n=/invalid_email|user.not.found|no user/i.test(i?.message??"");if(r?.createIfMissing&&n){let s=await this.createUserWithEmail(e,t,{scope:r.scope,signInIfAllowed:true});if("verificationRequired"in s&&s.verificationRequired)throw new h("Email verification required before sign-in",c.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw i instanceof h?i:new h(i instanceof Error?i.message:"Sign-in with email/password failed",i.error??i.code??c.AuthenticationFailed,i)}}async signInWithEmail(e,t,r){return this.signInWithEmailAndPassword(e,t,r)}async createUserWithEmail(e,t,r){let i=await this.registerWithEmail(e,t,r);if(i.verification_required)return {kind:i.kind,verificationRequired:true,emailSent:!!i.email_sent,preview:i.preview};let n=String(i.access_token??"");if(!n)throw new h("User created but no access token returned",c.AuthenticationFailed);let s={access_token:n,refresh_token:i.refresh_token?String(i.refresh_token):null,expires_in:i.expires_in?Number(i.expires_in):null,token_type:String(i.token_type??"Bearer"),scope:i.scope?String(i.scope):null,profile:null,provider:"credentials"},o=await this.auth(n),u=await this.fetchAuthMe(n).catch(()=>null);return this.setAuthSession({uid:o.uid,accessToken:n,refreshToken:s.refresh_token,provider:"credentials",email:u?.email??e,emailVerified:u?.email_verified}),{...o,accessToken:n,refreshToken:s.refresh_token,authToken:s,verificationRequired:false,emailSent:!!i.email_sent,preview:i.preview}}async createUserWithEmailAndPassword(e,t,r){return this.createUserWithEmail(e,t,r)}async signInOrCreateWithEmail(e,t,r){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:r?.scope}),created:!1}}catch(i){if(!/invalid_email|user.not.found|no user/i.test(i?.message??""))throw i;let s=await this.createUserWithEmail(e,t,{scope:r?.scope,additionalParams:r?.additionalParams,signInIfAllowed:true});return "verificationRequired"in s&&s.verificationRequired?{...s,created:true}:{...s,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,r){return this.signInOrCreateWithEmail(e,t,r)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendEmailVerification",`${t}/auth/verify/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendEmailVerification",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send verification email",c.AuthenticationFailed),i}async verifyEmailWithCode(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("verifyEmailWithCode",`${r}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("verifyEmailWithCode",i);return i.response.ok||this.throwFetchFlareError(n,"Email verification failed",c.AuthenticationFailed),n}async confirmEmailLink(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("confirmEmailLink",`${r}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,email:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("confirmEmailLink",i);return i.response.ok||this.throwFetchFlareError(n,"Email link verification failed",c.AuthenticationFailed),n}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendAccountRecovery",`${t}/auth/recover/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendAccountRecovery",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send recovery email",c.AuthenticationFailed),i}async recoverAccountWithCode(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("recoverAccountWithCode",`${i}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:r,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",n);return n.response.ok||this.throwFetchFlareError(s,"Account recovery failed",c.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithToken",`${r}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("recoverAccountWithToken",i);return i.response.ok||this.throwFetchFlareError(n,"Account recovery failed",c.AuthenticationFailed),n}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4),i=t+r,n=atob(i),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),r=String(t.endpoint??"").trim(),i=String(t.keys?.p256dh??"").trim(),n=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:r,p256dh:i,auth:n});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/push/config?${t.toString()}`,i=await this.timedFetch("fetchPushSetupConfig",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("fetchPushSetupConfig",i);i.response.ok||this.throwFetchFlareError(n,"Failed to fetch push setup config",c.QueryFailed);let s=String(n.vapidPublicKey??"").trim(),o=String(n.serviceWorkerPath??"").trim();if(o.startsWith("/"))try{let l=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");l&&l!=="/"&&!o.startsWith(`${l}/`)&&(o=`${l}${o}`);}catch{}if(!s||!o)throw new h("Push setup response is missing vapidPublicKey or serviceWorkerPath",c.ParseError,n);return {vapidPublicKey:s,serviceWorkerPath:o}}async setupPushServiceWorker(){return typeof window>"u"||typeof navigator>"u"||!("serviceWorker"in navigator)?null:(this.pushServiceWorkerInitPromise||(this.pushServiceWorkerInitPromise=(async()=>{let e=await this.fetchPushSetupConfig(),t=new URL(e.serviceWorkerPath,window.location.origin);if(t.origin!==window.location.origin)throw new h("Service worker URL must be same-origin with the app",c.WriteFailed);return await navigator.serviceWorker.register(t.pathname+t.search,{scope:"/"})})().catch(e=>{throw this.log("Push service worker setup failed",e),e})),this.pushServiceWorkerInitPromise)}async requestPushPermission(){if(typeof window>"u"||typeof Notification>"u")throw new h("Push permission can only be requested in browser runtime",c.WriteFailed);let e=await Notification.requestPermission();if(e!=="granted")throw new h(`Push permission is ${e}`,c.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new h("Push token acquisition can only run in browser runtime",c.WriteFailed);if(!("serviceWorker"in navigator))throw new h("Service worker is not supported in this browser",c.WriteFailed);if(!("PushManager"in window))throw new h("Push manager is not supported in this browser",c.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),r=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,i=e.subscription??await r.pushManager.getSubscription();if(e.forceResubscribe&&i&&(await i.unsubscribe().catch(()=>{}),i=null),!i){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new h("No VAPID public key available for push subscription",c.WriteFailed);i=await r.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(i),subscription:i}}async enableBrowserPush(e={}){let{token:t,subscription:r}=await this.acquireBrowserPushToken(e);return {...await this.registerPushToken({token:t,platform:e.platform??"web",deviceId:e.deviceId,topics:e.topics,authAppId:e.authAppId}),subscription:r}}async registerPushToken(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=String(e.token??"").trim();if(!r)throw new h("Push token is required",c.WriteFailed);let i=await this.timedFetch("registerPushToken",`${t}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:r,platform:e.platform,deviceId:e.deviceId,topics:e.topics,...e.authAppId?{authAppId:e.authAppId}:{}})}),n=await this.parseJsonWithTiming("registerPushToken",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to register push token",c.WriteFailed),{registered:!!n.registered,appId:String(n.appId??this.config.appId),uid:String(n.uid??this.authSession?.uid??""),token:String(n.token??r),...typeof n.platform=="string"?{platform:n.platform}:{}}}async unregisterPushToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=String(e??"").trim();if(!i)throw new h("Push token is required",c.WriteFailed);let n=await this.timedFetch("unregisterPushToken",`${r}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"DELETE",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:i,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",n);return n.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",c.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??i),removed:!!s.removed}}async sendPushNotification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendPushNotification",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/notifications/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),i=await this.parseJsonWithTiming("sendPushNotification",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send push notification",c.WriteFailed),{sent:!!i.sent,appId:String(i.appId??this.config.appId),targetCount:Number(i.targetCount??0),successCount:Number(i.successCount??0),failureCount:Number(i.failureCount??0),invalidatedTokenCount:Number(i.invalidatedTokenCount??0),dryRun:!!i.dryRun}}async sendEmail(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendEmail",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/email/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),i=await this.parseJsonWithTiming("sendEmail",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send template email",c.WriteFailed),{sent:!!i.sent,appId:String(i.appId??this.config.appId),tag:String(i.tag??e.tag??""),recipientCount:Number(i.recipientCount??0),acceptedCount:Number(i.acceptedCount??0),rejectedCount:Number(i.rejectedCount??0),...typeof i.includeVerificationLink=="boolean"?{includeVerificationLink:i.includeVerificationLink}:{},...typeof i.linkId=="string"?{linkId:i.linkId}:{},...typeof i.verifyUrl=="string"?{verifyUrl:i.verifyUrl}:{},...typeof i.messageId=="string"?{messageId:i.messageId}:{}}}async verifyEmailLink(e){let t=this.getHttpBase(),r=String(e.token??"").trim();if(!r)throw new h("Verification token is required",c.WriteFailed);let i=await this.timedFetch("verifyEmailLink",`${t}/email/link/verify?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,token:r,...e.tag?{tag:e.tag}:{},...e.email?{email:e.email}:{},...e.authAppId?{authAppId:e.authAppId}:{}})}),n=await this.parseJsonWithTiming("verifyEmailLink",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to verify email link",c.WriteFailed),{verified:!!(n.verified??n.accepted),alreadyVerified:!!(n.alreadyVerified??n.alreadyAccepted),appId:String(n.appId??this.config.appId),linkId:String(n.linkId??""),email:String(n.email??""),tag:String(n.tag??e.tag??""),...typeof n.verifiedAt=="string"?{verifiedAt:n.verifiedAt}:{},...typeof n.acceptedByUid=="string"?{acceptedByUid:n.acceptedByUid}:{}}}async signIn(e,t,r){let i=typeof e?.signIn=="function",n=i?e:await this.getAuthGuard(),s=i?t:e,o=i?r:t;return n.signIn(s,o)}async signInWithGoogle(e){return this.signIn("google",e)}async signInWithGitHub(e){return this.signIn("github",e)}async signInWithFacebook(e){return this.signIn("facebook",e)}async signInWithDropbox(e){return this.signIn("dropbox",e)}async handleSignInRedirect(e,t=false){let r=typeof e?.handleRedirect=="function",i=r?e:await this.getAuthGuard(),n=r?t:typeof e=="boolean"?e:false,s=await i.handleRedirect(n);if(!s||!s.access_token||!s.provider)return null;let o=await this.exchangeProviderToken(s.provider,s.access_token),u=await this.auth(o.token),l=await this.fetchAuthMe(o.token).catch(()=>null);return this.setAuthSession({uid:u.uid,accessToken:o.token,refreshToken:s.refresh_token,provider:s.provider,email:l?.email??null,emailVerified:l?.email_verified}),{...u,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let r=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let i=await this.timedFetch("exchangeProviderToken",r,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders()},body:JSON.stringify({appId:this.config.appId,client_id:this.config.apiKey,provider:e,access_token:t})}),n=await this.parseJsonWithTiming("exchangeProviderToken",i);if(i.response.ok||this.throwFetchFlareError(n,"OAuth token exchange failed",c.AuthenticationFailed),!n?.token)throw new h("OAuth token exchange failed",c.ParseError,n);return {token:String(n.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.fetchAuthConfig();if(!e.enabled)throw new h("Authentication is disabled for this app",c.AuthenticationFailed);let t=this.getHttpBase(),r=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,i=[],n=(s,o)=>({...o,token_url:r,tokenParams:{...o.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&i.push({...auth.Credentials({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,createUserUrl:`${t}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,createUserGrantType:"create_user"}),e.providers.anonymous?.enabled&&i.push({...auth.Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&i.push(n("google",auth.Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&i.push(n("github",auth.GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&i.push(n("facebook",auth.Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&i.push(n("dropbox",auth.Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&i.push(n("apple",auth.Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&i.push(n("twitter",auth.Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),i.length===0)throw new h("No authentication providers are enabled for this app",c.AuthenticationFailed);return this.authGuard=new auth.AuthGuard({providers:i,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("refreshAuthSession",`${t}/auth/refresh?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,...e?{refresh_token:e}:{}})}),i=await this.parseJsonWithTiming("refreshAuthSession",r);if(!r.response.ok){if(r.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(i,"Failed to refresh auth session",c.AuthenticationFailed);}let n=String(i.access_token??"");if(!n)throw new h("Refresh succeeded but no access token was returned",c.ParseError);let s=await this.fetchAuthMe(n).catch(()=>null),o={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:n,refreshToken:i.refresh_token?String(i.refresh_token):this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:s?.email??this.authSession?.email??null,emailVerified:s?.email_verified};if(s){try{delete s.kind,s.uid=s.id??s.uid,delete s.id;}catch{}this.setProfile(s);}return this.setAuthSession(o),await this.syncSocketAuth(n).catch(()=>{}),o}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("issueSsrToken",`${t}/auth/ssr/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,ttlSeconds:e})}),i=await this.parseJsonWithTiming("issueSsrToken",r);r.response.ok||this.throwFetchFlareError(i,"Failed to mint SSR token",c.AuthenticationFailed);let n=String(i.token??"");if(!n)throw new h("SSR token response is missing token",c.ParseError,i);return {token:n,token_type:String(i.token_type??"Bearer"),expires_in:Number(i.expires_in??0),uid:String(i.uid??""),role:String(i.role??"user"),...typeof i.email=="string"?{email:i.email}:{}}}async signOut(){try{if(this.authSession?.accessToken||this.authSession?.refreshToken||this.config.httpBase){let t=this.getHttpBase();await this.ensureCsrfProtection(),await this.timedFetch("signOut",`${t}/auth/logout?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,refresh_token:this.authSession?.refreshToken})}).catch(()=>{});}}finally{this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=new URLSearchParams;n.set("appId",this.config.appId),n.set("client_id",this.config.apiKey??""),n.set("grant_type","create_user"),n.set("email",e),n.set("password",t),r?.scope?.length&&n.set("scope",r.scope.join(" ")),r?.additionalParams&&n.set("additional_params",JSON.stringify(r.additionalParams));let s=await this.timedFetch("registerWithEmail",`${i}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:n.toString()}),o=await this.parseJsonWithTiming("registerWithEmail",s);return !s.response.ok&&s.response.status!==202&&this.throwFetchFlareError(o,"User creation failed",c.WriteFailed),o}async requestEmailPasswordToken(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=new URLSearchParams;n.set("appId",this.config.appId),n.set("client_id",this.config.apiKey??""),n.set("grant_type","password"),n.set("email",e),n.set("password",t),r?.length&&n.set("scope",r.join(" "));let s=await this.timedFetch("requestEmailPasswordToken",`${i}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:n.toString()}),o=await this.parseJsonWithTiming("requestEmailPasswordToken",s);return s.response.ok||this.throwFetchFlareError(o,"Sign-in with email/password failed",c.AuthenticationFailed),{kind:String(o.kind),access_token:String(o.access_token??""),refresh_token:o.refresh_token?String(o.refresh_token):null,expires_in:o.expires_in?Number(o.expires_in):null,token_type:String(o.token_type??"Bearer"),scope:o.scope?String(o.scope):null,profile:null,provider:"credentials"}}async fetchAuthMe(e){let t=this.getHttpBase(),r=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&r.set("apiKey",this.config.apiKey);let i=`${t}/auth/me?${r.toString()}`,n=await this.timedFetch("fetchAuthMe",i,{credentials:"include",headers:{Authorization:`Bearer ${e}`,...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",n);return n.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",c.QueryFailed),s}};var B=class extends F{autoPushRegisteredIdentity;constructor(e){super(e),this.log("FlareClient initialized",e),e.pushNotifications===true&&this.enableAutoPushNotificationsAfterAuth();}enableAutoPushNotificationsAfterAuth(){let e=async()=>{let t=this.authSession,r=String(t?.uid??"").trim()||"anon",i=String(t?.accessToken??"").trim(),n=r!=="anon"&&i?r:"anon";if(this.autoPushRegisteredIdentity!==n)try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=n;}catch(s){this.log("Auto push enable failed",s);}};this.onAuthStateChanged(()=>{e().catch(()=>{});}),e().catch(()=>{});}async autoEnablePushNotifications(){await this.setupPushServiceWorker().catch(()=>{}),await this.requestPushPermission();let{token:e}=await this.acquireBrowserPushToken();await this.registerPushToken({token:e,platform:"web",topics:[this.config.appId]});}},H=B;function D(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function be(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function E(a,e){let t=e.toLowerCase();for(let[r,i]of Object.entries(a??{}))if(r.toLowerCase()===t&&typeof i=="string")return i}function Te(a){let e=E(a,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,r]of Object.entries(a??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(r))return r.filter(i=>typeof i=="string");return []}function Ce(a,e){for(let t of a){let r=t.split(";").map(u=>u.trim()),[i]=r;if(!i)continue;let n=i.indexOf("=");if(n<=0)continue;let s=decodeURIComponent(i.slice(0,n)),o=i.slice(n+1);if(s===e)return decodeURIComponent(o)}}async function Se(a){let e=new URL("/auth/config",a.endpoint);return e.searchParams.set("appId",a.appId),a.apiKey&&e.searchParams.set("apiKey",a.apiKey),await core.withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:a.apiKey?{"x-flare-api-key":a.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function j(a){let e=await Se(a),t=e?.data,r=e?.headers??{},i=E(r,"x-flare-csrf")??E(r,"x-csrf-token")??E(r,"csrf-token");if(typeof i=="string"&&i.length>0)return {csrfToken:i,...t};let n=t?.cookie?.csrfTokenName,s=n&&n.length>0?n:be(a.appId),o=Te(r),u=Ce(o,s);if(typeof u=="string"&&u.length>0)return {csrfToken:u,...t}}function J(a,e,t){return `${encodeURIComponent(a)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function Pe(a){let e=a.proxyCookieName??D(a.appId),t=a.proxyCookieMaxAge??3600;return async function(i){let n=await j(a),s=n?.csrfToken,o=new Headers({"Content-Type":"application/json"});return s&&o.set("Set-Cookie",J(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...n}),{status:200,headers:o})}}function we(a){let e=a.proxyCookieName??D(a.appId),t=a.proxyCookieMaxAge??3600;return async function(i,n){if(i.method!=="GET"&&i.method!=="HEAD"){n.status(405).json({error:"Method not allowed"});return}let o=(await j(a))?.csrfToken;o&&n.setHeader("Set-Cookie",J(e,o,t)),n.status(200).json({csrfToken:o??null});}}function Ae(a,e,t){let r=t??D(e);if(a instanceof Request){let s=(a.headers.get("cookie")??"").split(";").map(u=>u.trim()).find(u=>u.startsWith(`${encodeURIComponent(r)}=`)||u.startsWith(`${r}=`));if(!s)return null;let o=s.indexOf("=");return o>=0?decodeURIComponent(s.slice(o+1)):null}let{cookies:i}=a;return typeof i?.get=="function"?i.get(r)?.value??null:i&&typeof i=="object"?i[r]??null:null}function Ie(a,e){let t={};return a&&(t["x-flare-csrf"]=a),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var ve=a=>a==="guest"?"auth == null":a==="auth"?"auth != null":"true",Re=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},Fe=a=>{let e=String(a??"").trim();if(!e||e==="false")return {auth:"any"};if(e==="auth != null")return {auth:"auth"};if(e==="auth == null")return {auth:"guest"};if(e==="true")return {auth:"any"};let t=e.match(/^\((auth != null|auth == null|true)\)\s*&&\s*\((.+)\)$/);if(t)return {auth:V(t[1]),condition:t[2].trim()};let r=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return r?{auth:V(r[1]),condition:r[2].trim()}:{auth:"any",condition:e}},V=a=>{let e=String(a??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},vt=a=>{let e={};for(let t of a){let r=String(t.collection||"").trim();if(!r)continue;let i=r==="any"?"*":r,n=Re(ve(t.auth),t.condition);e[i]={".read":t.permissions.includes("read")?n:"false",".create":t.permissions.includes("create")?n:"false",".update":t.permissions.includes("update")?n:"false",".delete":t.permissions.includes("delete")?n:"false"};}return e},Rt=a=>Object.entries(a).map(([e,t],r)=>{let i=t?.[".read"],n=t?.[".create"],s=t?.[".update"],o=t?.[".delete"],u=t?.[".write"],l=[];typeof i=="string"&&i.trim()!=="false"&&l.push("read");let g=typeof n=="string"&&n.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",f=typeof s=="string"&&s.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",d=typeof o=="string"&&o.trim()!=="false"||typeof u=="string"&&u.trim()!=="false";g&&l.push("create"),f&&l.push("update"),d&&l.push("delete");let C=Fe(i||n||s||o||u);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:C.auth,collection:e==="*"?"any":e,condition:C.condition,permissions:l}});var Ee=(f=>(f.authEmailNotVerified="auth/email-not-verified",f.authEmailAlreadyVerified="auth/email-already-verified",f.authInvalidToken="auth/invalid-token",f.authUserDisabled="auth/user-disabled",f.authUserNotFound="auth/user-not-found",f.authWrongPassword="auth/wrong-password",f.authEmailAlreadyInUse="auth/email-already-in-use",f.authInvalidEmail="auth/invalid-email",f.authWeakPassword="auth/weak-password",f.authTooManyRequests="auth/too-many-requests",f.authInternalError="auth/internal-error",f))(Ee||{});var xe=(p=>(p.health="health",p.authConfig="auth_config",p.authRegistration="auth/registration",p.authRegistrationVerificationRequired="auth/registration-verification-required",p.authSession="auth/session",p.authExchange="auth/exchange",p.authLogout="auth/logout",p.authSsrBridge="auth/ssr_bridge",p.authSsrVerify="auth/ssr_verify",p.accountRecovery="account/recovery",p.emailVerification="email/verification",p.verificationDispatch="verification/dispatch",p.authProfile="auth/profile",p.adminToken="admin/token",p.documentDelete="document/delete",p.documentsDelete="documents/delete",p.documents="documents",p.document="document",p.documentCreate="document/create",p.documentUpdate="document/update",p.oauthProviderResponse="oauth_provider_response",p.success="success",p.response="response",p))(xe||{});var m=null,P=null,x=null,Qe=a=>JSON.stringify({endpoint:a.endpoint,appId:a.appId,apiKey:a.apiKey,publicKey:a.publicKey,autoReconnect:a.autoReconnect,reconnectDelay:a.reconnectDelay,maxReconnectDelay:a.maxReconnectDelay}),Nt=a=>{let e=Qe(a);if(m&&x!==e&&(m.disconnect(),m=null,P=null,x=null),!m){m=new H(a),x=e;let t=typeof window<"u"&&typeof document<"u",r=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!r)&&m.connect(),t&&m.setupPushServiceWorker().catch(()=>{}),P=new Proxy(m,{get(i,n,s){if(n==="onAuthStateChange")return i.onAuthStateChanged.bind(i);if(n==="onAuthConfigLoaded")return i.onAuthConfigLoaded.bind(i);let o=Reflect.get(i,n,s);return typeof o=="function"?o.bind(i):o}});}return P??m},Bt=()=>P??m,Ht=()=>{m&&(m.disconnect(),m=null,P=null,x=null);},Dt=H;
3
- Object.defineProperty(exports,"Anonymous",{enumerable:true,get:function(){return auth.Anonymous}});Object.defineProperty(exports,"Apple",{enumerable:true,get:function(){return auth.Apple}});Object.defineProperty(exports,"AuthGuard",{enumerable:true,get:function(){return auth.AuthGuard}});Object.defineProperty(exports,"Credentials",{enumerable:true,get:function(){return auth.Credentials}});Object.defineProperty(exports,"Dropbox",{enumerable:true,get:function(){return auth.Dropbox}});Object.defineProperty(exports,"Facebook",{enumerable:true,get:function(){return auth.Facebook}});Object.defineProperty(exports,"GitHub",{enumerable:true,get:function(){return auth.GitHub}});Object.defineProperty(exports,"Google",{enumerable:true,get:function(){return auth.Google}});Object.defineProperty(exports,"Providers",{enumerable:true,get:function(){return auth.Providers}});Object.defineProperty(exports,"Twitter",{enumerable:true,get:function(){return auth.Twitter}});Object.defineProperty(exports,"setupProvider",{enumerable:true,get:function(){return auth.setupProvider}});exports.CollectionReference=N;exports.DocumentQueryBuilder=k;exports.DocumentReference=S;exports.FlareAction=X;exports.FlareError=h;exports.FlareErrors=Ee;exports.FlareEvent=ee;exports.FlareResponseCodes=xe;exports.buildFlareHeaders=Ie;exports.connectApp=Nt;exports.createCsrfProxy=Pe;exports.createCsrfProxyHandler=we;exports.default=Dt;exports.disconnectFlare=Ht;exports.extractCsrfFromRequest=Ae;exports.flareRulesToSecurityMap=vt;exports.getFlare=Bt;exports.parseValue=K;exports.parseWhereCondition=M;exports.securityMapToFlareRules=Rt;
2
+ var h=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="ZuzFlareError";}};var oe={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},u=oe;var ae=(c=>(c.SUBSCRIBE="subscribe",c.UNSUBSCRIBE="unsubscribe",c.WRITE="write",c.DELETE="delete",c.AUTH="auth",c.PING="ping",c.OFFLINE_SYNC="offline_sync",c.CALL="call",c.QUERY="query",c.PRESENCE_JOIN="presence_join",c.PRESENCE_LEAVE="presence_leave",c.PRESENCE_HEARTBEAT="presence_heartbeat",c))(ae||{}),ce=(c=>(c.SNAPSHOT="snapshot",c.CHANGE="change",c.ERROR="error",c.ACK="ack",c.PONG="pong",c.AUTH_OK="auth_ok",c.OFFLINE_ACK="offline_ack",c.CALL_RESPONSE="call_response",c.QUERY_RESULT="query_result",c.PRESENCE_STATE="presence_state",c.PRESENCE_JOIN="presence_join",c.PRESENCE_LEAVE="presence_leave",c))(ce||{});function J(a){let e=[];for(let[t,n]of Object.entries(a))if(typeof n=="string"){let r=n.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(r){let[,i,s]=r;e.push({field:t,op:i,value:te(s.trim())});}else e.push({field:t,op:"==",value:n});}else Array.isArray(n)?e.push({field:t,op:"in",value:n}):e.push({field:t,op:"==",value:n});return e}function te(a){if(!isNaN(Number(a)))return Number(a);if(a==="true")return true;if(a==="false")return false;if(a==="null")return null;if(a!=="undefined")return a}var A=class{constructor(e,t,n){this.client=e;this.collection=t;this.legacyId=n;}whereCondition;updateData;setData;deleteOp=false;promise;where(e){return this.whereCondition=e,this}update(e){return this.updateData=e,this}set(e){return this.setData=e,this}delete(){return this.deleteOp=true,this}getDocId(){if(this.legacyId)return this.legacyId;if(this.whereCondition&&(this.whereCondition.id||this.whereCondition._id)){let e=this.whereCondition.id??this.whereCondition._id;if(typeof e=="string")return e}throw new h('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',u.QueryFailed)}async execute(){return this._execute()}async _execute(){let e=this.getDocId();if(this.deleteOp){await this.client.send("delete",{collection:this.collection,docId:e});return}if(this.updateData){await this.client.send("write",{collection:this.collection,docId:e,data:this.updateData,merge:true});return}if(this.setData){await this.client.send("write",{collection:this.collection,docId:e,data:this.setData,merge:false});return}return this.get()}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}async get(){let e=this.getDocId(),t=core.uuid2(18);return new Promise((n,r)=>{let i=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(i(),n(s.data));});setTimeout(()=>{i(),r(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),n=core.uuid2(18);return this.client.subscribe(n,this.collection,t,void 0,e)}};var V=class{constructor(e,t,n){this.client=e;this.collection=t;this.id=n;}async get(){return new A(this.client,this.collection,this.id).get()}async set(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:false});}async update(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:true});}async delete(){await this.client.send("delete",{collection:this.collection,docId:this.id});}onSnapshot(e){let t=core.uuid2(18),n=()=>{};return n=this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="snapshot"&&(e(r),n());}),n}onDocUpdated(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&(n.operation==="update"||n.operation==="replace")&&n.data&&e(n.data,n.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&n.operation==="delete"&&e(n.docId);},{skipSnapshot:true})}onDocChanged(e){let t=core.uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&e(n.data??null,n.docId,n.operation);},{skipSnapshot:true})}},Q=V;var z=class a{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(n,r,i)=>{if(typeof r=="string"&&!(r in n)&&this.client.hasQueryPreset(r))return (o={})=>n.with(r,o);let s=Reflect.get(n,r,i);return typeof s=="function"?s.bind(n):s}})}sq={};promise;doc(e){return new Q(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}normalizeFilterValue(e,t){return e==="in"||e==="not-in"||e==="array-contains-any"?Array.isArray(t)?t:[t]:t}normalizeFilter(e){return {...e,value:this.normalizeFilterValue(e.op,e.value)}}toQueryFilters(e){return J(e).map(t=>this.normalizeFilter(t))}appendOperatorFilter(e,t,n,r){return this.appendFilters([this.normalizeFilter({field:e,op:t,value:n})],r)}appendAndFilters(e){return this.clone({where:[...this.sq.where??[],...e]})}toOrNode(e){return {or:e}}toAndNode(e){return {and:e}}appendOrFilters(e){let t=[...this.sq.where??[]];if(t.length===0)return this.clone({where:[this.toOrNode(e)]});let n=t[0];if(t.length===1&&typeof n=="object"&&n!=null&&"or"in n){let s=n;return this.clone({where:[{or:[...s.or,...e]}]})}let i=t.length===1?t[0]:{and:t};return this.clone({where:[{or:[i,...e]}]})}appendFilters(e,t){return t==="or"?this.appendOrFilters(e):this.appendAndFilters(e)}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e){return this.appendFilters(this.toQueryFilters(e),"and")}and(e){return this.appendFilters(this.toQueryFilters(e),"and")}or(e){return this.appendFilters(this.toQueryFilters(e),"or")}in(e,t){return this.appendOperatorFilter(e,"in",t,"and")}andIn(e,t){return this.appendOperatorFilter(e,"in",t,"and")}orIn(e,t){return this.appendOperatorFilter(e,"in",t,"or")}notIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}andNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}orNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"or")}arrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}andArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}orArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"or")}arrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}andArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}orArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"or")}some(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}andSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}orSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"or")}like(e,t){return this.appendOperatorFilter(e,"like",t,"and")}andLike(e,t){return this.appendOperatorFilter(e,"like",t,"and")}orLike(e,t){return this.appendOperatorFilter(e,"like",t,"or")}notLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}andNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}orNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"or")}exists(e){return this.appendOperatorFilter(e,"exists",true,"and")}andExists(e){return this.appendOperatorFilter(e,"exists",true,"and")}orExists(e){return this.appendOperatorFilter(e,"exists",true,"or")}notExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}andNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}orNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"or")}latest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"desc"}]})}oldest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"asc"}]})}orderBy(e,t="asc"){return this.clone({orderBy:[...this.sq.orderBy??[],{field:e,dir:t}]})}limit(e){return this.clone({limit:e})}offset(e){return this.clone({offset:e})}startAt(...e){return this.clone({startAt:{values:e}})}startAfter(...e){return this.clone({startAfter:{values:e}})}endAt(...e){return this.clone({endAt:{values:e}})}endBefore(...e){return this.clone({endBefore:{values:e}})}aggregate(...e){return this.clone({aggregate:[...this.sq.aggregate??[],...e]})}count(e="count"){return this.aggregate({fn:"count",alias:e})}sum(e,t){return this.aggregate({fn:"sum",field:e,alias:t??`sum_${e}`})}avg(e,t){return this.aggregate({fn:"avg",field:e,alias:t??`avg_${e}`})}min(e,t){return this.aggregate({fn:"min",field:e,alias:t??`min_${e}`})}max(e,t){return this.aggregate({fn:"max",field:e,alias:t??`max_${e}`})}distinct(e,t){return this.aggregate({fn:"distinct",field:e,alias:t??`distinct_${e}`})}groupBy(...e){return this.clone({groupBy:{fields:e}})}having(e,t,n){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:n}]})}buildStructuredJoin(e,t){let r={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(r.where=t.where),Array.isArray(t?.orderBy)&&(r.orderBy=t.orderBy),typeof t?.limit=="number"&&(r.limit=t.limit),typeof t?.offset=="number"&&(r.offset=t.offset),t?.startAt&&(r.startAt=t.startAt),t?.startAfter&&(r.startAfter=t.startAfter),t?.endAt&&(r.endAt=t.endAt),t?.endBefore&&(r.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(r.aggregate=t.aggregate),t?.groupBy&&(r.groupBy=t.groupBy),Array.isArray(t?.having)&&(r.having=t.having),t?.vectorSearch&&(r.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(r.select=t.select),typeof t?.distinctField=="string"&&(r.distinctField=t.distinctField),Array.isArray(t?.joins)&&(r.joins=t.joins.map(i=>this.buildStructuredJoin(String(i?.collection??""),i))),r}Join(e,t){let n=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],n]})}join(e,t){if(typeof e=="string")return this.Join(e,t);let n=String(e.collection??e.from??""),r=this.buildStructuredJoin(n,e);return this.clone({joins:[...this.sq.joins??[],r]})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}async get(){return this._execute()}_isStructured(){return !!(this.sq.orderBy?.length||this.sq.aggregate?.length||this.sq.groupBy||this.sq.having?.length||this.sq.joins?.length||this.sq.vectorSearch||this.sq.distinctField||this.sq.offset||this.sq.startAt||this.sq.startAfter||this.sq.endAt||this.sq.endBefore||this.sq.select?.length)}async _execute(){return this._isStructured()?this._executeQuery():this._executeSubscribe()}async _executeQuery(){return (await this.client.send("query",{collection:this.collection,query:this.sq})).data??[]}async _executeSubscribe(){let e=core.uuid2(18);return new Promise((t,n)=>{let r=Object.keys(this.sq).length>0?this.sq:void 0,i=this.client.subscribe(e,this.collection,void 0,r,s=>{s.type==="snapshot"&&(i(),t(s.data));});setTimeout(()=>{i(),n(new Error("Collection fetch timeout"));},1e4);})}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}onSnapshot(e){let t=core.uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0,r=(()=>{});return r=this.client.subscribe(t,this.collection,void 0,n,i=>{i.type==="snapshot"&&(e(i),r());}),r}stream(e={}){let t=core.uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0,r=new Set,i=[],s=new Map,o=Math.max(0,Number(e.flushMs??24)),d=Math.max(1,Number(e.maxBatchSize??200)),l=e.insertAt??"end",f=typeof e.maxDocs=="number"&&e.maxDocs>0?Math.floor(e.maxDocs):void 0,y=String(e.idField??"id"),c=[],S=false,C=false,x=0,P,I=()=>{s.clear();for(let p=0;p<c.length;p+=1){let m=$(c[p]);m&&s.set(m,p);}},$=(p,m)=>{if(m)return m;if(p==null)return;if(typeof e.getId=="function"){let v=e.getId(p);if(typeof v=="string"&&v.length>0)return v}let w=p?.[y]??p?._id??p?.docId;if(typeof w=="string"&&w.length>0)return w},E=()=>{f==null||c.length<=f||(c=c.slice(0,f));},F=()=>{typeof e.sort=="function"&&(c=c.slice().sort(e.sort));},M=(p,m)=>{x+=1;let w=c.slice(),v={reason:p,batchSize:m,version:x,ready:C};for(let N of Array.from(r))try{N(w,v);}catch{}},T=()=>{P!=null&&(clearTimeout(P),P=void 0);},g=p=>{if(p.operation==="delete"){let N=s.get(p.docId);if(N==null)return;c.splice(N,1),I();return}let m=p.data;if(m==null)return;let w=$(m,p.docId);if(!w)return;let v=s.get(w);if(typeof v=="number"){c[v]=m;return}l==="start"?c.unshift(m):c.push(m),E(),I();},_=()=>{if(S||i.length===0)return;T();let p=i.splice(0,i.length);for(let m of p)g(m);F(),I(),M("change-batch",p.length);},K=()=>{S||P!=null||(P=setTimeout(_,o));},q=this.client.subscribe(t,this.collection,void 0,n,p=>{if(!S){if(p.type==="snapshot"){c=Array.isArray(p.data)?[...p.data]:[],C=true,T(),i.length=0,F(),E(),I(),M("snapshot",0);return}if(i.push(p),i.length>=d){_();return}K();}}),j={subscribe(p,m=true){if(r.add(p),m){let w={reason:C?"change-batch":"snapshot",batchSize:0,version:x,ready:C};try{p(c.slice(),w);}catch{}}return ()=>{r.delete(p);}},getSnapshot(){return c.slice()},isReady(){return C},getVersion(){return x},close:()=>{S||(S=true,T(),i.length=0,r.clear(),q());},onError(p){return q.onError(p),j},onPermissionDenied(p){return q.onPermissionDenied(p),j}};return j}asStore(e={}){let t=this.stream(e);return {subscribe:n=>t.subscribe(()=>{n();},false),getSnapshot:()=>t.getSnapshot(),getServerSnapshot:()=>[],stream:t,destroy:()=>{t.close();}}}onDocAdded(e){let t=core.uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&r.operation==="insert"&&r.data!=null&&e(r.data,r.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=core.uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data!=null&&e(r.data,r.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=core.uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&r.operation==="delete"&&e(r.docId);},{skipSnapshot:true})}onDocChanged(e){let t=core.uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&e(r.data??null,r.docId,r.operation);},{skipSnapshot:true})}async add(e){let t=core.uuid2(18),n=this.doc(t);return await n.set(e),n}update(e){return new A(this.client,this.collection).update(e)}delete(){return new A(this.client,this.collection).delete()}},G=z;async function ue(a){let e=a.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,""),t=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary"),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",n.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function de(a,e){let t=await ue(e),n=new TextEncoder().encode(JSON.stringify(a)),i=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,n),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(i))):Buffer.from(i).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var D=class{socket=null;reconnectInterval;maxReconnectDelay;isConnected=false;shouldReconnect=true;options;messageQueue=[];heartbeatInterval=null;connectionTimeout=null;constructor(e){this.options=e,this.reconnectInterval=e.reconnectDelay||2,this.maxReconnectDelay=e.maxReconnectDelay||60,this.log("Transport initialized",e.url);}connect(){if(this.socket){this.log("Socket already exists, skipping connection");return}this.log("Connecting to",this.options.url),this.socket=new WebSocket(this.options.url),this.connectionTimeout=setTimeout(()=>{this.isConnected||(this.log("Connection timeout"),this.socket?.close(),this.handleReconnect());},1e4),this.socket.onopen=()=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=true,this.reconnectInterval=this.options.reconnectDelay||2,this.log("Connected to server"),this.options.onOpen?.(),this.startHeartbeat(),this.flushQueue();},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data);this.options.onMessage(t);}catch(t){this.log("Parse error",t),this.options.onError?.(t);}},this.socket.onerror=e=>{this.log("WebSocket error",e),this.options.onError?.(new Error("WebSocket error"));},this.socket.onclose=e=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=false,this.socket=null,this.stopHeartbeat(),this.log("Connection closed",e.code,e.reason),this.options.onClose?.(),e.code!==1e3&&this.shouldReconnect&&this.options.autoReconnect&&this.handleReconnect();};}handleReconnect(){let e=this.reconnectInterval*1e3;this.log(`Reconnecting in ${this.reconnectInterval}s...`),setTimeout(()=>{this.reconnectInterval=Math.min(this.reconnectInterval*2,this.maxReconnectDelay),this.connect();},e);}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send({type:"ping",id:Date.now().toString(),ts:Date.now()});},3e4);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}flushQueue(){for(this.log("Flushing message queue",this.messageQueue.length);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}send(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){let t=n=>{try{this.socket.send(n),this.log("Sent message",e);}catch(r){this.log("Send error",r),this.messageQueue.push(e);}};this.options.publicKey?de(e,this.options.publicKey).then(t).catch(n=>{this.log("RSA encrypt error \u2014 sending plaintext",n),t(JSON.stringify(e));}):t(JSON.stringify(e));}else this.log("Socket not ready, queueing message"),this.messageQueue.push(e);}disconnect(){this.shouldReconnect=false,this.stopHeartbeat(),this.socket&&(this.socket.close(1e3,"Client disconnect"),this.socket=null),this.isConnected=false,this.log("Disconnected");}get connected(){return this.isConnected}log(...e){this.options.debug&&console.log("[FlareTransport]",...e);}};var ye={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},re={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},H=class{transport;config;pendingAcks=new Map;subscriptions=new Map;activeSubscriptions=new Map;queryPresets=new Map;subscriptionErrorHandlers=new Map;subscriptionPermissionHandlers=new Map;subscriptionLastErrors=new Map;offlineQueue=[];currentState="disconnected";connectionListeners=[];errorListeners=[];isDebug=false;socketAuthUid="anon";pendingSubscriptionReplay=false;subscriptionReplayPromise=Promise.resolve();requestTraceSeq=0;requestTimingEnabled=true;httpInFlight=new Map;httpResponseCache=new Map;maxHttpCacheEntries=200;presenceCallbacks=new Map;presenceJoinCbs=new Map;presenceLeaveCbs=new Map;presenceHeartbeatTimer;embedder;vectorSchema=new Map;throwFetchFlareError(e,t,n){let r=e,i=typeof r?.error=="string"&&r.error.length>0?r.error:n,s=typeof r?.message=="string"&&r.message.length>0?r.message:t;throw new h(s,i,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r]=n;});else if(Array.isArray(e))for(let[n,r]of e)t[String(n)]=String(r);else for(let[n,r]of Object.entries(e))t[String(n)]=String(r);return t}redactHeaders(e){let t={...e};for(let n of Object.keys(t)){let r=n.toLowerCase();(r==="authorization"||r==="x-flare-csrf"||r==="x-csrf-token")&&(t[n]="[redacted]");}return t}stableStringify(e){if(e==null)return "";if(typeof e=="string")return e;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return e.toString();if(typeof e!="object")return String(e);if(Array.isArray(e))return `[${e.map(r=>this.stableStringify(r)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(r=>`${r}:${this.stableStringify(t[r])}`).join(",")}}`}buildHttpCacheKey(e,t,n,r,i){let o=Object.entries(n).map(([l,f])=>[l.toLowerCase(),f]).sort(([l],[f])=>l.localeCompare(f)).map(([l,f])=>`${l}:${f}`).join("|"),d=this.stableStringify(r);return `${e}|${t}|${i??""}|${o}|${d}`}shouldCacheResponse(e,t){return !!(e==="GET"||e==="POST"&&/\/auth\/refresh(?:\?|$)/.test(t))}rememberHttpResponse(e,t){if(this.httpResponseCache.set(e,t),this.httpResponseCache.size<=this.maxHttpCacheEntries)return;let n=this.httpResponseCache.keys().next().value;n&&this.httpResponseCache.delete(n);}createTimedFetchTrace(e,t,n,r,i,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:o=>{let d=o.toLowerCase();for(let[l,f]of Object.entries(e.headers))if(l.toLowerCase()===d)return String(f);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:n,networkMs:s,method:r,url:i}}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let n=new Headers(e);for(let[r,i]of Object.entries(t))n.set(r,i);return n}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(ye[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(re[t]?re[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(r=>this.normalizeOutboundData(r));if(!e||typeof e!="object")return e;let t=e,n={};for(let[r,i]of Object.entries(t))n[this.toWireField(r)]=this.normalizeOutboundData(i);return n}normalizeInboundData(e){if(Array.isArray(e))return e.map(r=>this.normalizeInboundData(r));if(!e||typeof e!="object")return e;let t=e,n={};for(let[r,i]of Object.entries(t))n[this.fromWireField(r)]=this.normalizeInboundData(i);return n}normalizeOutboundAnyFilter(e){return Array.isArray(e.or)?{...e,or:e.or.map(t=>this.normalizeOutboundAnyFilter(t))}:Array.isArray(e.and)?{...e,and:e.and.map(t=>this.normalizeOutboundAnyFilter(t))}:typeof e.field=="string"?{...e,field:this.toWireField(e.field)}:{...e}}normalizeOutboundQuery(e){if(!e)return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.field=="string")return this.normalizeOutboundAnyFilter(e);if(Array.isArray(e))return e.map(i=>this.normalizeOutboundAnyFilter(i));if(typeof e!="object")return e;let t=e,n={...t},r=i=>{let s={...i};return s.localField=this.toWireField(String(i?.localField??"")),s.foreignField=this.toWireField(String(i?.foreignField??"")),Array.isArray(i.where)&&(s.where=i.where.map(o=>this.normalizeOutboundAnyFilter(o))),Array.isArray(i.orderBy)&&(s.orderBy=i.orderBy.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),i.groupBy&&typeof i.groupBy=="object"&&Array.isArray(i.groupBy.fields)&&(s.groupBy={...i.groupBy,fields:i.groupBy.fields.map(o=>this.toWireField(String(o??"")))}),Array.isArray(i.having)&&(s.having=i.having.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),Array.isArray(i.select)&&(s.select=i.select.map(o=>this.toWireField(String(o??"")))),typeof i.distinctField=="string"&&(s.distinctField=this.toWireField(i.distinctField)),i.vectorSearch&&typeof i.vectorSearch=="object"&&(s.vectorSearch={...i.vectorSearch,field:this.toWireField(String(i.vectorSearch.field??""))}),Array.isArray(i.joins)&&(s.joins=i.joins.map(o=>r(o))),s};return Array.isArray(t.where)&&(n.where=t.where.map(i=>this.normalizeOutboundAnyFilter(i))),Array.isArray(t.orderBy)&&(n.orderBy=t.orderBy.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(n.groupBy={...t.groupBy,fields:t.groupBy.fields.map(i=>this.toWireField(String(i??"")))}),Array.isArray(t.having)&&(n.having=t.having.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),Array.isArray(t.select)&&(n.select=t.select.map(i=>this.toWireField(String(i??"")))),typeof t.distinctField=="string"&&(n.distinctField=this.toWireField(t.distinctField)),t.vectorSearch&&typeof t.vectorSearch=="object"&&(n.vectorSearch={...t.vectorSearch,field:this.toWireField(String(t.vectorSearch.field??""))}),Array.isArray(t.joins)&&(n.joins=t.joins.map(i=>r(i))),n}async timedFetch(e,t,n){let r=++this.requestTraceSeq,i=this.nowMs(),s=String(n?.method??"GET").toUpperCase(),o=this.normalizeHeaders(n?.headers),d=this.redactHeaders(o),l=n?.body,f=this.buildHttpCacheKey(s,t,o,l,n?.credentials),y=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${r} ${e} start`,{method:s,url:t,headers:d,hasBody:!!n?.body});try{if(y){let T=this.httpResponseCache.get(f);if(T)return this.logHttpTiming(`#${r} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(T,r,i,s,t,0)}let c=this.httpInFlight.get(f);if(c){let T=await c,g=this.nowMs()-i;return this.logHttpTiming(`#${r} ${e} deduped`,{method:s,url:t,networkMs:Number(g.toFixed(2))}),this.createTimedFetchTrace(T,r,i,s,t,g)}let S=this.mergeHeaders(n?.headers,{"x-flare-request-id":String(r)}),C=this.normalizeHeaders(S),x=this.redactHeaders(C),P={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:C,withCredentials:n?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${r} ${e} request`,{method:s,url:t,headers:x,hasBody:!!n?.body});let I=s.toUpperCase(),E=(async()=>{let T=I==="GET"?await core.withGet(t,P):I==="PUT"?await core.withPut(t,l,P):I==="PATCH"?await core.withPatch(t,l,P):await core.withPost(t,l,P),g={status:Number(T?.status??0),headers:Object.fromEntries(Object.entries(T?.headers??{}).map(([_,K])=>[_,String(K)])),data:T?.data??{}};return y&&this.rememberHttpResponse(f,g),g})();this.httpInFlight.set(f,E);let F=await E.finally(()=>{this.httpInFlight.delete(f);}),M=this.nowMs()-i;return this.logHttpTiming(`#${r} ${e} response`,{status:F.status,networkMs:Number(M.toFixed(2))}),this.createTimedFetchTrace(F,r,i,s,t,M)}catch(c){let S=this.nowMs()-i;throw this.logHttpTiming(`#${r} ${e} failed`,{networkMs:Number(S.toFixed(2)),message:c?.message??String(c)}),c}}async parseJsonWithTiming(e,t){let n=this.nowMs(),r=await t.response.json().catch(()=>({})),i=this.nowMs()-n,s=this.nowMs()-t.startedAtMs;return this.logHttpTiming(`#${t.requestId} ${e} complete`,{method:t.method,url:t.url,status:t.response.status,networkMs:Number(t.networkMs.toFixed(2)),parseMs:Number(i.toFixed(2)),totalMs:Number(s.toFixed(2))}),r}getHttpBase(){if(this.config.httpBase)return this.config.httpBase.replace(/\/$/,"");let e=new URL(this.config.endpoint);return `${e.protocol}//${e.host}`}log(...e){this.isDebug&&console.log("[FlareClient]",...e);}constructor(e){this.config={autoReconnect:true,reconnectDelay:2,maxReconnectDelay:60,debug:false,connectionTimeout:1e4,...e},this.isDebug=this.config.debug||false,this.requestTimingEnabled=this.config.requestTiming??true;let{hostname:t,port:n,protocol:r}=new URL(this.config.endpoint),i=r==="https:",d=`${i?"wss":"ws"}://${t}:${n||(i?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new D({url:d,publicKey:this.config.publicKey,autoReconnect:this.config.autoReconnect,reconnectDelay:this.config.reconnectDelay,maxReconnectDelay:this.config.maxReconnectDelay,onMessage:l=>this.handleIncoming(l),onOpen:()=>this.onConnected(),onClose:()=>this.onDisconnected(),onError:l=>this.handleTransportError(l),debug:this.isDebug});}connect(){this.setState("connecting"),this.transport.connect();}disconnect(){this.transport.disconnect(),this.setState("disconnected");}get connectionState(){return this.currentState}get isConnected(){return this.currentState==="connected"}onConnectionStateChange(e){return this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e);}}collection(e){return new G(this,e)}registerQueryPreset(e,t){let n=String(e??"").trim();if(!n)throw new h("Preset name is required",u.QueryFailed);if(typeof t!="function")throw new h(`Query preset "${n}" handler must be a function`,u.QueryFailed);return this.queryPresets.set(n,t),this}registerQueryPresets(e){for(let[t,n]of Object.entries(e??{}))this.registerQueryPreset(t,n);return this}hasQueryPreset(e){return this.queryPresets.has(String(e??"").trim())}applyQueryPreset(e,t,n={}){let r=String(t??"").trim(),i=this.queryPresets.get(r);if(!i)throw new h(`Unknown query preset "${r}"`,u.QueryFailed);let s=i(e,n??{});if(!s||typeof s.get!="function")throw new h(`Query preset "${r}" must return a CollectionReference`,u.QueryFailed);return s}doc(e,t){return t!==void 0?new Q(this,e,t):new A(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let n=await this.send("call",{topic:e,payload:t});if(!n.success)throw new h(n.error??`CALL "${e}" failed`,u.QueryFailed);return n.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,n={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,n);}async embedVectorFields(e,t){let n=this.vectorSchema.get(e);if(!n)return t;let r={...t};for(let[i,s]of n){let o=r[i];if(typeof o=="string"){let d=s.embed??this.embedder;if(!d){this.log(`[vector] No embedder for field "${i}" \u2014 storing raw text`);continue}r[i]=await d(o);}}return r}async joinPresence(e,t){return await this.send("presence_join",{room:e,meta:t}),this._startPresenceHeartbeat(e,t),()=>this.leavePresence(e)}async leavePresence(e){await this.send("presence_leave",{room:e}),this._stopPresenceHeartbeat();}onPresenceState(e,t){return this.presenceCallbacks.has(e)||this.presenceCallbacks.set(e,[]),this.presenceCallbacks.get(e).push(t),()=>{let n=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,n.filter(r=>r!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let n=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,n.filter(r=>r!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let n=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,n.filter(r=>r!==t));}}_startPresenceHeartbeat(e,t){this.presenceHeartbeatTimer||(this.presenceHeartbeatTimer=setInterval(()=>{this.isConnected&&this.send("presence_heartbeat",{meta:t}).catch(()=>{});},2e4));}_stopPresenceHeartbeat(){this.presenceHeartbeatTimer&&(clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=void 0);}async syncOffline(){if(this.offlineQueue.length===0)return;this.log("Syncing offline operations",this.offlineQueue.length);let e=[...this.offlineQueue];this.offlineQueue.length=0;let t=await this.send("offline_sync",{operations:e});t.conflicts&&t.conflicts.length>0&&(this.log("Offline sync conflicts",t.conflicts),t.conflicts.forEach(n=>{let r=e.find(i=>i.id===n.operationId);r&&this.offlineQueue.push(r);}));}async beforeActivateSubscription(e){}async activateSubscription(e){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}await this.beforeActivateSubscription(e),this.subscriptions.set(e.liveId,e.callback);try{let t=await this.send("subscribe",{collection:e.collection,docId:e.docId,query:e.query,skipSnapshot:e.options.skipSnapshot});if(!this.activeSubscriptions.has(e.baseId)){this.subscriptions.delete(e.liveId);return}t.subscriptionId&&t.subscriptionId!==e.liveId&&(this.subscriptions.delete(e.liveId),e.liveId=t.subscriptionId,this.subscriptions.set(e.liveId,e.callback),this.log("Subscription remapped",e.baseId,"\u2192",e.liveId));}catch(t){this.subscriptions.delete(e.liveId),this.pendingSubscriptionReplay=true;let n=this.toSubscriptionError(t);this.emitSubscriptionError(e.baseId,n),this.log("Subscription failed",t);}}toSubscriptionError(e){let t=e instanceof Error?e.message:String(e??"Unknown subscription error"),n=t.match(/^\[([^\]]+)\]\s*(.*)$/),r=n?.[1],i=(n?.[2]??t).trim()||t,s=r===u.PermissionDenied||t.includes(u.PermissionDenied);return {code:r,message:i,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let n=this.subscriptionErrorHandlers.get(e);if(n)for(let r of n)try{r(t);}catch(i){this.log("Subscription error callback failed",i);}if(t.permissionDenied){let r=this.subscriptionPermissionHandlers.get(e);if(r)for(let i of r)try{i(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let n=t.liveId;this.subscriptions.delete(n),t.liveId=t.baseId,n&&await this.send("unsubscribe",{subscriptionId:n}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,n,r,i,s={}){this.log("Creating subscription",e,t,n);let o={baseId:e,liveId:e,collection:t,docId:n,query:r,callback:i,options:s};this.activeSubscriptions.set(e,o),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(o).catch(f=>{this.log("Subscription activation failed",f);});let d=()=>{let y=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",y),this.activeSubscriptions.delete(e),this.subscriptions.delete(y),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:y}).catch(c=>this.log("Unsubscribe failed",c));},l=d;return l.unsubscribe=d,l.onError=f=>{this.subscriptionErrorHandlers.get(e)?.add(f);let y=this.subscriptionLastErrors.get(e);if(y)try{f(y);}catch(c){this.log("Subscription error callback failed",c);}return l},l.onPermissionDenied=f=>{this.subscriptionPermissionHandlers.get(e)?.add(f);let y=this.subscriptionLastErrors.get(e);if(y?.permissionDenied)try{f(y);}catch(c){this.log("Subscription permission callback failed",c);}return l},l.catch=f=>l.onError(f),l}async send(e,t){if(e==="write"&&t.collection&&t.data){let n=await this.embedVectorFields(t.collection,t.data);t={...t,data:this.normalizeOutboundData(n)};}return (e==="subscribe"||e==="query")&&t?.query&&(t={...t,query:this.normalizeOutboundQuery(t.query)}),new Promise((n,r)=>{let i=core.uuid2(18),s={id:i,type:e,ts:Date.now(),...t};this.pendingAcks.set(i,o=>{o.type==="error"?r(new Error(`[${o.code}] ${o.message}`)):n(o);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),r(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(i)&&(this.pendingAcks.delete(i),r(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(n){this.log("Error listener error",n);}});}onConnected(){this.setState("connected"),this.log("Connected to FlareServer"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.offlineQueue.length>0&&this.syncOffline().catch(e=>{this.log("Offline sync failed",e);});}onDisconnected(){this.currentState!=="disconnected"&&this.setState("reconnecting"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.log("Disconnected from FlareServer");}setState(e){this.currentState!==e&&(this.currentState=e,this.log("Connection state changed",e),this.connectionListeners.forEach(t=>{try{t(e);}catch(n){this.log("Connection listener error",n);}}));}handleIncoming(e){if(this.log("Received message",e.type,e),e.type==="query_result"&&Array.isArray(e.data)&&(e={...e,data:this.normalizeInboundData(e.data)}),e.type==="ack"||e.type==="pong"||e.type==="auth_ok"||e.type==="call_response"||e.type==="query_result"){let t=this.pendingAcks.get(e.correlationId||e.id);t&&(t(e),this.pendingAcks.delete(e.correlationId||e.id));return}if(e.type==="error"){this.log("Server error",e.code,e.message);let t=new Error(`[${e.code}] ${e.message}`);this.errorListeners.forEach(r=>{try{r(t);}catch(i){this.log("Error listener error",i);}});let n=Array.from(this.activeSubscriptions.values()).find(r=>r.liveId===e.correlationId||r.baseId===e.correlationId);if(n&&this.emitSubscriptionError(n.baseId,{code:typeof e.code=="string"?e.code:void 0,message:String(e.message??"Subscription error"),permissionDenied:e.code===u.PermissionDenied,raw:e}),e.correlationId){let r=this.pendingAcks.get(e.correlationId);r&&(r(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(n=>{try{n(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(n=>{try{n(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(n=>{try{n(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let n=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),r={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(n)?n:[]};try{t(r);}catch(i){this.log("Subscription callback error",i);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let n={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:e.operation==="delete"?null:this.normalizeInboundData(e.data)};try{t(n);}catch(r){this.log("Subscription callback error",r);}}}}};var U=class extends H{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;socketAuthSyncPromise;pushServiceWorkerInitPromise;authSession=null;authStateListeners=[];authConfigListeners=[];currentProfile=void 0;getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return this.getCookieValue(this.getCsrfCookieName())??this.csrfToken??null}getCookieValue(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`)||r.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let n=t.indexOf("=");return n>=0?decodeURIComponent(t.slice(n+1)):null}extractCsrfToken(e,t){let n=e,r=typeof n?.csrfToken=="string"?String(n.csrfToken):typeof n?.csrf_token=="string"?String(n.csrf_token):void 0;if(r)return r;if(!t)return;let i=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof i=="string"&&i.length>0?i:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}setCsrfToken(e){this.csrfToken=e,this.csrfBootstrapAttempted=true,this.log("CSRF token injected",{length:e.length});}async ensureCsrfProtection(){if(this.getCsrfToken()){this.csrfBootstrapAttempted=true;return}if(this.config.httpBase){this.csrfBootstrapAttempted=true;return}this.csrfBootstrapAttempted||(this.csrfInitPromise||(this.csrfBootstrapAttempted=true,this.csrfInitPromise=this.loadAuthConfig().then(()=>{}).finally(()=>{this.csrfInitPromise=void 0;})),await this.csrfInitPromise,this.getCsrfToken()||this.log("CSRF token unavailable after auth config load",{hasAuthConfig:!!this.authConfig,csrfCookieName:this.getCsrfCookieName()}));}async loadAuthConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let n=`${e}/auth/config?${t.toString()}`,r=await this.timedFetch("loadAuthConfig",n,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("loadAuthConfig",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to load auth config",u.QueryFailed),this.authConfig=i,this.csrfToken=this.extractCsrfToken(i,r.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(o){this.log("Auth config listener error",o);}}),this.authConfig}async fetchAuthConfig(){return this.authConfig?this.authConfig:this.loadAuthConfig()}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}setProfile(e){this.currentProfile=e;}setAuthSession(e){this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid):(this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear());let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;this.authStateListeners.forEach(n=>{try{n(t);}catch(r){this.log("Auth state listener error",r);}});}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;try{e(t);}catch(n){this.log("Auth state listener error during initialization",n);}return ()=>{this.authStateListeners=this.authStateListeners.filter(n=>n!==e);}}onAuthStateChange(e){return this.onAuthStateChanged(e)}get currentUser(){return this.currentProfile}getCurrentUser(){return this.currentUser}async syncSocketAuth(e){if(!this.isConnected)return;let t=await this.send("auth",e?{token:e}:{});if(t.type!=="auth_ok")throw new h("Socket auth sync failed",u.AuthenticationFailed);if(!e||t.uid==="anon"){this.authToken=void 0,this.userId=void 0,await this.updateSocketIdentity("anon");return}this.authToken=typeof t.token=="string"?t.token:e,this.userId=typeof t.uid=="string"?t.uid:this.userId,await this.updateSocketIdentity(typeof t.uid=="string"?t.uid:this.userId);}async updateSocketIdentity(e,t=false){let n=typeof e=="string"&&e.length>0?e:"anon",r=n!==this.socketAuthUid;this.socketAuthUid=n,(r||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async beforeActivateSubscription(e){if(!this.isConnected)return;let t=this.authSession;!t?.accessToken||!t.uid||this.socketAuthUid!==t.uid&&(this.socketAuthSyncPromise||(this.socketAuthSyncPromise=this.syncSocketAuth(t.accessToken).catch(n=>{throw this.log("Socket auth sync failed before subscribe",n),n}).finally(()=>{this.socketAuthSyncPromise=void 0;})),await this.socketAuthSyncPromise);}onConnected(){super.onConnected(),this.authSession?.accessToken&&this.syncSocketAuth(this.authSession.accessToken).catch(e=>{this.log("Socket auth sync failed after connect",e);});}handleIncoming(e){if(e.type==="auth_ok"&&!e.correlationId){let t=typeof e.token=="string"?e.token:void 0,n=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(n,this.pendingSubscriptionReplay).catch(r=>{this.log("Socket identity update failed",r);}),t&&n&&n!=="anon"&&n!=="__admin__"?this.fetchAuthMe(t).then(r=>{this.setAuthSession({uid:n,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:r?.email??null,emailVerified:r?.email_verified});}).catch(()=>{this.setAuthSession({uid:n,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):n==="anon"&&this.authSession&&this.setAuthSession(null);}super.handleIncoming(e);}async auth(e){let t=await this.send("auth",{token:e});if(t.type==="auth_ok"){let n=t.token??e;this.authToken=n,this.userId=t.uid;let r=await this.fetchAuthMe(n).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:n,refreshToken:this.authSession?.refreshToken??null,email:r?.email??null,emailVerified:r?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new h("Authentication failed",u.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,n){try{let r=await this.requestEmailPasswordToken(e,t,n?.scope),i=await this.auth(r.access_token),s=await this.fetchAuthMe(r.access_token).catch(()=>null);return this.setAuthSession({uid:i.uid,accessToken:r.access_token,refreshToken:r.refresh_token,provider:r.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",i.uid),{...i,kind:r.kind,accessToken:r.access_token,refreshToken:r.refresh_token,authToken:r}}catch(r){let i=/invalid_email|user.not.found|no user/i.test(r?.message??"");if(n?.createIfMissing&&i){let s=await this.createUserWithEmail(e,t,{scope:n.scope,signInIfAllowed:true});if("verificationRequired"in s&&s.verificationRequired)throw new h("Email verification required before sign-in",u.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw r instanceof h?r:new h(r instanceof Error?r.message:"Sign-in with email/password failed",r.error??r.code??u.AuthenticationFailed,r)}}async signInWithEmail(e,t,n){return this.signInWithEmailAndPassword(e,t,n)}async createUserWithEmail(e,t,n){let r=await this.registerWithEmail(e,t,n);if(r.verification_required)return {kind:r.kind,verificationRequired:true,emailSent:!!r.email_sent,preview:r.preview};let i=String(r.access_token??"");if(!i)throw new h("User created but no access token returned",u.AuthenticationFailed);let s={access_token:i,refresh_token:r.refresh_token?String(r.refresh_token):null,expires_in:r.expires_in?Number(r.expires_in):null,token_type:String(r.token_type??"Bearer"),scope:r.scope?String(r.scope):null,profile:null,provider:"credentials"},o=await this.auth(i),d=await this.fetchAuthMe(i).catch(()=>null);return this.setAuthSession({uid:o.uid,accessToken:i,refreshToken:s.refresh_token,provider:"credentials",email:d?.email??e,emailVerified:d?.email_verified}),{...o,accessToken:i,refreshToken:s.refresh_token,authToken:s,verificationRequired:false,emailSent:!!r.email_sent,preview:r.preview}}async createUserWithEmailAndPassword(e,t,n){return this.createUserWithEmail(e,t,n)}async signInOrCreateWithEmail(e,t,n){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:n?.scope}),created:!1}}catch(r){if(!/invalid_email|user.not.found|no user/i.test(r?.message??""))throw r;let s=await this.createUserWithEmail(e,t,{scope:n?.scope,additionalParams:n?.additionalParams,signInIfAllowed:true});return "verificationRequired"in s&&s.verificationRequired?{...s,created:true}:{...s,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,n){return this.signInOrCreateWithEmail(e,t,n)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendEmailVerification",`${t}/auth/verify/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),r=await this.parseJsonWithTiming("sendEmailVerification",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send verification email",u.AuthenticationFailed),r}async verifyEmailWithCode(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("verifyEmailWithCode",`${n}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("verifyEmailWithCode",r);return r.response.ok||this.throwFetchFlareError(i,"Email verification failed",u.AuthenticationFailed),i}async confirmEmailLink(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("confirmEmailLink",`${n}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,email:t,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("confirmEmailLink",r);return r.response.ok||this.throwFetchFlareError(i,"Email link verification failed",u.AuthenticationFailed),i}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendAccountRecovery",`${t}/auth/recover/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),r=await this.parseJsonWithTiming("sendAccountRecovery",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send recovery email",u.AuthenticationFailed),r}async recoverAccountWithCode(e,t,n){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithCode",`${r}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:n,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",i);return i.response.ok||this.throwFetchFlareError(s,"Account recovery failed",u.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("recoverAccountWithToken",`${n}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("recoverAccountWithToken",r);return r.response.ok||this.throwFetchFlareError(i,"Account recovery failed",u.AuthenticationFailed),i}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4),r=t+n,i=atob(r),s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=1)s[o]=i.charCodeAt(o);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),n=String(t.endpoint??"").trim(),r=String(t.keys?.p256dh??"").trim(),i=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:n,p256dh:r,auth:i});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let n=`${e}/push/config?${t.toString()}`,r=await this.timedFetch("fetchPushSetupConfig",n,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("fetchPushSetupConfig",r);r.response.ok||this.throwFetchFlareError(i,"Failed to fetch push setup config",u.QueryFailed);let s=String(i.vapidPublicKey??"").trim(),o=String(i.serviceWorkerPath??"").trim();if(o.startsWith("/"))try{let l=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");l&&l!=="/"&&!o.startsWith(`${l}/`)&&(o=`${l}${o}`);}catch{}if(!s||!o)throw new h("Push setup response is missing vapidPublicKey or serviceWorkerPath",u.ParseError,i);return {vapidPublicKey:s,serviceWorkerPath:o}}async setupPushServiceWorker(){return typeof window>"u"||typeof navigator>"u"||!("serviceWorker"in navigator)?null:(this.pushServiceWorkerInitPromise||(this.pushServiceWorkerInitPromise=(async()=>{let e=await this.fetchPushSetupConfig(),t=new URL(e.serviceWorkerPath,window.location.origin);if(t.origin!==window.location.origin)throw new h("Service worker URL must be same-origin with the app",u.WriteFailed);return await navigator.serviceWorker.register(t.pathname+t.search,{scope:"/"})})().catch(e=>{throw this.log("Push service worker setup failed",e),e})),this.pushServiceWorkerInitPromise)}async requestPushPermission(){if(typeof window>"u"||typeof Notification>"u")throw new h("Push permission can only be requested in browser runtime",u.WriteFailed);let e=await Notification.requestPermission();if(e!=="granted")throw new h(`Push permission is ${e}`,u.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new h("Push token acquisition can only run in browser runtime",u.WriteFailed);if(!("serviceWorker"in navigator))throw new h("Service worker is not supported in this browser",u.WriteFailed);if(!("PushManager"in window))throw new h("Push manager is not supported in this browser",u.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),n=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,r=e.subscription??await n.pushManager.getSubscription();if(e.forceResubscribe&&r&&(await r.unsubscribe().catch(()=>{}),r=null),!r){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new h("No VAPID public key available for push subscription",u.WriteFailed);r=await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(r),subscription:r}}async enableBrowserPush(e={}){let{token:t,subscription:n}=await this.acquireBrowserPushToken(e);return {...await this.registerPushToken({token:t,platform:e.platform??"web",deviceId:e.deviceId,topics:e.topics,authAppId:e.authAppId}),subscription:n}}async registerPushToken(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=String(e.token??"").trim();if(!n)throw new h("Push token is required",u.WriteFailed);let r=await this.timedFetch("registerPushToken",`${t}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:n,platform:e.platform,deviceId:e.deviceId,topics:e.topics,...e.authAppId?{authAppId:e.authAppId}:{}})}),i=await this.parseJsonWithTiming("registerPushToken",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to register push token",u.WriteFailed),{registered:!!i.registered,appId:String(i.appId??this.config.appId),uid:String(i.uid??this.authSession?.uid??""),token:String(i.token??n),...typeof i.platform=="string"?{platform:i.platform}:{}}}async unregisterPushToken(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=String(e??"").trim();if(!r)throw new h("Push token is required",u.WriteFailed);let i=await this.timedFetch("unregisterPushToken",`${n}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"DELETE",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:r,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",u.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??r),removed:!!s.removed}}async sendPushNotification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendPushNotification",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/notifications/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),r=await this.parseJsonWithTiming("sendPushNotification",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send push notification",u.WriteFailed),{sent:!!r.sent,appId:String(r.appId??this.config.appId),targetCount:Number(r.targetCount??0),successCount:Number(r.successCount??0),failureCount:Number(r.failureCount??0),invalidatedTokenCount:Number(r.invalidatedTokenCount??0),dryRun:!!r.dryRun}}async sendEmail(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendEmail",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/email/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),r=await this.parseJsonWithTiming("sendEmail",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send template email",u.WriteFailed),{sent:!!r.sent,appId:String(r.appId??this.config.appId),tag:String(r.tag??e.tag??""),recipientCount:Number(r.recipientCount??0),acceptedCount:Number(r.acceptedCount??0),rejectedCount:Number(r.rejectedCount??0),...typeof r.includeVerificationLink=="boolean"?{includeVerificationLink:r.includeVerificationLink}:{},...typeof r.linkId=="string"?{linkId:r.linkId}:{},...typeof r.verifyUrl=="string"?{verifyUrl:r.verifyUrl}:{},...typeof r.messageId=="string"?{messageId:r.messageId}:{}}}async verifyEmailLink(e){let t=this.getHttpBase(),n=String(e.token??"").trim();if(!n)throw new h("Verification token is required",u.WriteFailed);let r=await this.timedFetch("verifyEmailLink",`${t}/email/link/verify?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,token:n,...e.tag?{tag:e.tag}:{},...e.email?{email:e.email}:{},...e.authAppId?{authAppId:e.authAppId}:{}})}),i=await this.parseJsonWithTiming("verifyEmailLink",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to verify email link",u.WriteFailed),{verified:!!(i.verified??i.accepted),alreadyVerified:!!(i.alreadyVerified??i.alreadyAccepted),appId:String(i.appId??this.config.appId),linkId:String(i.linkId??""),email:String(i.email??""),tag:String(i.tag??e.tag??""),...typeof i.verifiedAt=="string"?{verifiedAt:i.verifiedAt}:{},...typeof i.acceptedByUid=="string"?{acceptedByUid:i.acceptedByUid}:{}}}async signIn(e,t,n){let r=typeof e?.signIn=="function",i=r?e:await this.getAuthGuard(),s=r?t:e,o=r?n:t;return i.signIn(s,o)}async signInWithGoogle(e){return this.signIn("google",e)}async signInWithGitHub(e){return this.signIn("github",e)}async signInWithFacebook(e){return this.signIn("facebook",e)}async signInWithDropbox(e){return this.signIn("dropbox",e)}async handleSignInRedirect(e,t=false){let n=typeof e?.handleRedirect=="function",r=n?e:await this.getAuthGuard(),i=n?t:typeof e=="boolean"?e:false,s=await r.handleRedirect(i);if(!s||!s.access_token||!s.provider)return null;let o=await this.exchangeProviderToken(s.provider,s.access_token),d=await this.auth(o.token),l=await this.fetchAuthMe(o.token).catch(()=>null);return this.setAuthSession({uid:d.uid,accessToken:o.token,refreshToken:s.refresh_token,provider:s.provider,email:l?.email??null,emailVerified:l?.email_verified}),{...d,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let n=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let r=await this.timedFetch("exchangeProviderToken",n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders()},body:JSON.stringify({appId:this.config.appId,client_id:this.config.apiKey,provider:e,access_token:t})}),i=await this.parseJsonWithTiming("exchangeProviderToken",r);if(r.response.ok||this.throwFetchFlareError(i,"OAuth token exchange failed",u.AuthenticationFailed),!i?.token)throw new h("OAuth token exchange failed",u.ParseError,i);return {token:String(i.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.fetchAuthConfig();if(!e.enabled)throw new h("Authentication is disabled for this app",u.AuthenticationFailed);let t=this.getHttpBase(),n=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,r=[],i=(s,o)=>({...o,token_url:n,tokenParams:{...o.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&r.push({...auth.Credentials({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,createUserUrl:`${t}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,createUserGrantType:"create_user"}),e.providers.anonymous?.enabled&&r.push({...auth.Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&r.push(i("google",auth.Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&r.push(i("github",auth.GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&r.push(i("facebook",auth.Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&r.push(i("dropbox",auth.Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&r.push(i("apple",auth.Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&r.push(i("twitter",auth.Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),r.length===0)throw new h("No authentication providers are enabled for this app",u.AuthenticationFailed);return this.authGuard=new auth.AuthGuard({providers:r,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("refreshAuthSession",`${t}/auth/refresh?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,...e?{refresh_token:e}:{}})}),r=await this.parseJsonWithTiming("refreshAuthSession",n);if(!n.response.ok){if(n.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(r,"Failed to refresh auth session",u.AuthenticationFailed);}let i=String(r.access_token??"");if(!i)throw new h("Refresh succeeded but no access token was returned",u.ParseError);let s=await this.fetchAuthMe(i).catch(()=>null),o={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:i,refreshToken:r.refresh_token?String(r.refresh_token):this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:s?.email??this.authSession?.email??null,emailVerified:s?.email_verified};if(s){try{delete s.kind,s.uid=s.id??s.uid,delete s.id;}catch{}this.setProfile(s);}return this.setAuthSession(o),await this.syncSocketAuth(i).catch(()=>{}),o}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("issueSsrToken",`${t}/auth/ssr/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,ttlSeconds:e})}),r=await this.parseJsonWithTiming("issueSsrToken",n);n.response.ok||this.throwFetchFlareError(r,"Failed to mint SSR token",u.AuthenticationFailed);let i=String(r.token??"");if(!i)throw new h("SSR token response is missing token",u.ParseError,r);return {token:i,token_type:String(r.token_type??"Bearer"),expires_in:Number(r.expires_in??0),uid:String(r.uid??""),role:String(r.role??"user"),...typeof r.email=="string"?{email:r.email}:{}}}async signOut(){try{if(this.authSession?.accessToken||this.authSession?.refreshToken||this.config.httpBase){let t=this.getHttpBase();await this.ensureCsrfProtection(),await this.timedFetch("signOut",`${t}/auth/logout?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,refresh_token:this.authSession?.refreshToken})}).catch(()=>{});}}finally{this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,n){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=new URLSearchParams;i.set("appId",this.config.appId),i.set("client_id",this.config.apiKey??""),i.set("grant_type","create_user"),i.set("email",e),i.set("password",t),n?.scope?.length&&i.set("scope",n.scope.join(" ")),n?.additionalParams&&i.set("additional_params",JSON.stringify(n.additionalParams));let s=await this.timedFetch("registerWithEmail",`${r}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:i.toString()}),o=await this.parseJsonWithTiming("registerWithEmail",s);return !s.response.ok&&s.response.status!==202&&this.throwFetchFlareError(o,"User creation failed",u.WriteFailed),o}async requestEmailPasswordToken(e,t,n){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=new URLSearchParams;i.set("appId",this.config.appId),i.set("client_id",this.config.apiKey??""),i.set("grant_type","password"),i.set("email",e),i.set("password",t),n?.length&&i.set("scope",n.join(" "));let s=await this.timedFetch("requestEmailPasswordToken",`${r}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:i.toString()}),o=await this.parseJsonWithTiming("requestEmailPasswordToken",s);return s.response.ok||this.throwFetchFlareError(o,"Sign-in with email/password failed",u.AuthenticationFailed),{kind:String(o.kind),access_token:String(o.access_token??""),refresh_token:o.refresh_token?String(o.refresh_token):null,expires_in:o.expires_in?Number(o.expires_in):null,token_type:String(o.token_type??"Bearer"),scope:o.scope?String(o.scope):null,profile:null,provider:"credentials"}}async fetchAuthMe(e){let t=this.getHttpBase(),n=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&n.set("apiKey",this.config.apiKey);let r=`${t}/auth/me?${n.toString()}`,i=await this.timedFetch("fetchAuthMe",r,{credentials:"include",headers:{Authorization:`Bearer ${e}`,...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",u.QueryFailed),s}};var Y=class extends U{autoPushRegisteredIdentity;constructor(e){super(e),this.log("FlareClient initialized",e),e.pushNotifications===true&&this.enableAutoPushNotificationsAfterAuth();}enableAutoPushNotificationsAfterAuth(){let e=async()=>{let t=this.authSession,n=String(t?.uid??"").trim()||"anon",r=String(t?.accessToken??"").trim(),i=n!=="anon"&&r?n:"anon";if(this.autoPushRegisteredIdentity!==i)try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=i;}catch(s){this.log("Auto push enable failed",s);}};this.onAuthStateChanged(()=>{e().catch(()=>{});}),e().catch(()=>{});}async autoEnablePushNotifications(){await this.setupPushServiceWorker().catch(()=>{}),await this.requestPushPermission();let{token:e}=await this.acquireBrowserPushToken();await this.registerPushToken({token:e,platform:"web",topics:[this.config.appId]});}},Z=Y;function X(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function ve(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function L(a,e){let t=e.toLowerCase();for(let[n,r]of Object.entries(a??{}))if(n.toLowerCase()===t&&typeof r=="string")return r}function Re(a){let e=L(a,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,n]of Object.entries(a??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(n))return n.filter(r=>typeof r=="string");return []}function xe(a,e){for(let t of a){let n=t.split(";").map(d=>d.trim()),[r]=n;if(!r)continue;let i=r.indexOf("=");if(i<=0)continue;let s=decodeURIComponent(r.slice(0,i)),o=r.slice(i+1);if(s===e)return decodeURIComponent(o)}}async function Ee(a){let e=new URL("/auth/config",a.endpoint);return e.searchParams.set("appId",a.appId),a.apiKey&&e.searchParams.set("apiKey",a.apiKey),await core.withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:a.apiKey?{"x-flare-api-key":a.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function ne(a){let e=await Ee(a),t=e?.data,n=e?.headers??{},r=L(n,"x-flare-csrf")??L(n,"x-csrf-token")??L(n,"csrf-token");if(typeof r=="string"&&r.length>0)return {csrfToken:r,...t};let i=t?.cookie?.csrfTokenName,s=i&&i.length>0?i:ve(a.appId),o=Re(n),d=xe(o,s);if(typeof d=="string"&&d.length>0)return {csrfToken:d,...t}}function ie(a,e,t){return `${encodeURIComponent(a)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function Fe(a){let e=a.proxyCookieName??X(a.appId),t=a.proxyCookieMaxAge??3600;return async function(r){let i=await ne(a),s=i?.csrfToken,o=new Headers({"Content-Type":"application/json"});return s&&o.set("Set-Cookie",ie(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...i}),{status:200,headers:o})}}function Me(a){let e=a.proxyCookieName??X(a.appId),t=a.proxyCookieMaxAge??3600;return async function(r,i){if(r.method!=="GET"&&r.method!=="HEAD"){i.status(405).json({error:"Method not allowed"});return}let o=(await ne(a))?.csrfToken;o&&i.setHeader("Set-Cookie",ie(e,o,t)),i.status(200).json({csrfToken:o??null});}}function Qe(a,e,t){let n=t??X(e);if(a instanceof Request){let s=(a.headers.get("cookie")??"").split(";").map(d=>d.trim()).find(d=>d.startsWith(`${encodeURIComponent(n)}=`)||d.startsWith(`${n}=`));if(!s)return null;let o=s.indexOf("=");return o>=0?decodeURIComponent(s.slice(o+1)):null}let{cookies:r}=a;return typeof r?.get=="function"?r.get(n)?.value??null:r&&typeof r=="object"?r[n]??null:null}function Oe(a,e){let t={};return a&&(t["x-flare-csrf"]=a),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var _e=a=>a==="guest"?"auth == null":a==="auth"?"auth != null":"true",Ne=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},Be=a=>{let e=String(a??"").trim();if(!e||e==="false")return {auth:"any"};if(e==="auth != null")return {auth:"auth"};if(e==="auth == null")return {auth:"guest"};if(e==="true")return {auth:"any"};let t=e.match(/^\((auth != null|auth == null|true)\)\s*&&\s*\((.+)\)$/);if(t)return {auth:se(t[1]),condition:t[2].trim()};let n=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return n?{auth:se(n[1]),condition:n[2].trim()}:{auth:"any",condition:e}},se=a=>{let e=String(a??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},_t=a=>{let e={};for(let t of a){let n=String(t.collection||"").trim();if(!n)continue;let r=n==="any"?"*":n,i=Ne(_e(t.auth),t.condition);e[r]={".read":t.permissions.includes("read")?i:"false",".create":t.permissions.includes("create")?i:"false",".update":t.permissions.includes("update")?i:"false",".delete":t.permissions.includes("delete")?i:"false"};}return e},Nt=a=>Object.entries(a).map(([e,t],n)=>{let r=t?.[".read"],i=t?.[".create"],s=t?.[".update"],o=t?.[".delete"],d=t?.[".write"],l=[];typeof r=="string"&&r.trim()!=="false"&&l.push("read");let f=typeof i=="string"&&i.trim()!=="false"||typeof d=="string"&&d.trim()!=="false",y=typeof s=="string"&&s.trim()!=="false"||typeof d=="string"&&d.trim()!=="false",c=typeof o=="string"&&o.trim()!=="false"||typeof d=="string"&&d.trim()!=="false";f&&l.push("create"),y&&l.push("update"),c&&l.push("delete");let C=Be(r||i||s||o||d);return {id:`${e}-${n}`,name:e==="*"?"All Collections":e,auth:C.auth,collection:e==="*"?"any":e,condition:C.condition,permissions:l}});var De=(y=>(y.authEmailNotVerified="auth/email-not-verified",y.authEmailAlreadyVerified="auth/email-already-verified",y.authInvalidToken="auth/invalid-token",y.authUserDisabled="auth/user-disabled",y.authUserNotFound="auth/user-not-found",y.authWrongPassword="auth/wrong-password",y.authEmailAlreadyInUse="auth/email-already-in-use",y.authInvalidEmail="auth/invalid-email",y.authWeakPassword="auth/weak-password",y.authTooManyRequests="auth/too-many-requests",y.authInternalError="auth/internal-error",y))(De||{});var He=(g=>(g.health="health",g.authConfig="auth_config",g.authRegistration="auth/registration",g.authRegistrationVerificationRequired="auth/registration-verification-required",g.authSession="auth/session",g.authExchange="auth/exchange",g.authLogout="auth/logout",g.authSsrBridge="auth/ssr_bridge",g.authSsrVerify="auth/ssr_verify",g.accountRecovery="account/recovery",g.emailVerification="email/verification",g.verificationDispatch="verification/dispatch",g.authProfile="auth/profile",g.adminToken="admin/token",g.documentDelete="document/delete",g.documentsDelete="documents/delete",g.documents="documents",g.document="document",g.documentCreate="document/create",g.documentUpdate="document/update",g.oauthProviderResponse="oauth_provider_response",g.success="success",g.response="response",g))(He||{});var k=null,O=null,W=null,Ue=a=>JSON.stringify({endpoint:a.endpoint,appId:a.appId,apiKey:a.apiKey,publicKey:a.publicKey,autoReconnect:a.autoReconnect,reconnectDelay:a.reconnectDelay,maxReconnectDelay:a.maxReconnectDelay}),Kt=a=>{let e=Ue(a);if(k&&W!==e&&(k.disconnect(),k=null,O=null,W=null),!k){k=new Z(a),W=e;let t=typeof window<"u"&&typeof document<"u",n=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!n)&&k.connect(),t&&k.setupPushServiceWorker().catch(()=>{}),O=new Proxy(k,{get(r,i,s){if(i==="onAuthStateChange")return r.onAuthStateChanged.bind(r);if(i==="onAuthConfigLoaded")return r.onAuthConfigLoaded.bind(r);let o=Reflect.get(r,i,s);return typeof o=="function"?o.bind(r):o}});}return O??k},qt=()=>O??k,jt=()=>{k&&(k.disconnect(),k=null,O=null,W=null);},Jt=Z;
3
+ Object.defineProperty(exports,"Anonymous",{enumerable:true,get:function(){return auth.Anonymous}});Object.defineProperty(exports,"Apple",{enumerable:true,get:function(){return auth.Apple}});Object.defineProperty(exports,"AuthGuard",{enumerable:true,get:function(){return auth.AuthGuard}});Object.defineProperty(exports,"Credentials",{enumerable:true,get:function(){return auth.Credentials}});Object.defineProperty(exports,"Dropbox",{enumerable:true,get:function(){return auth.Dropbox}});Object.defineProperty(exports,"Facebook",{enumerable:true,get:function(){return auth.Facebook}});Object.defineProperty(exports,"GitHub",{enumerable:true,get:function(){return auth.GitHub}});Object.defineProperty(exports,"Google",{enumerable:true,get:function(){return auth.Google}});Object.defineProperty(exports,"Providers",{enumerable:true,get:function(){return auth.Providers}});Object.defineProperty(exports,"Twitter",{enumerable:true,get:function(){return auth.Twitter}});Object.defineProperty(exports,"setupProvider",{enumerable:true,get:function(){return auth.setupProvider}});exports.CollectionReference=G;exports.DocumentQueryBuilder=A;exports.DocumentReference=Q;exports.FlareAction=ae;exports.FlareError=h;exports.FlareErrors=De;exports.FlareEvent=ce;exports.FlareResponseCodes=He;exports.buildFlareHeaders=Oe;exports.connectApp=Kt;exports.createCsrfProxy=Fe;exports.createCsrfProxyHandler=Me;exports.default=Jt;exports.disconnectFlare=jt;exports.extractCsrfFromRequest=Qe;exports.flareRulesToSecurityMap=_t;exports.getFlare=qt;exports.parseValue=te;exports.parseWhereCondition=J;exports.securityMapToFlareRules=Nt;
package/dist/index.d.cts CHANGED
@@ -332,6 +332,58 @@ type DocAddedCallback<T = any> = (data: T, docId: string) => void;
332
332
  type DocUpdatedCallback<T = any> = (data: T, docId: string) => void;
333
333
  type DocDeletedCallback<T = any> = (docId: string) => void;
334
334
  type DocChangedCallback<T = any> = (data: T | null, docId: string, operation: ChangeOperation) => void;
335
+ type StreamFlushReason = 'snapshot' | 'change-batch';
336
+ interface CollectionStreamOptions<T = any> {
337
+ /** Delay before a queued burst is flushed to listeners. */
338
+ flushMs?: number;
339
+ /** Flush immediately when queued changes reach this count. */
340
+ maxBatchSize?: number;
341
+ /** Field used to identify docs inside snapshots when getId is not provided. */
342
+ idField?: keyof T & string;
343
+ /** Custom identifier extractor for snapshot rows. */
344
+ getId?: (doc: T) => string | undefined;
345
+ /** Where newly inserted docs should be placed when they were not in snapshot. */
346
+ insertAt?: 'start' | 'end';
347
+ /** Optional cap to keep only the newest N docs in local stream state. */
348
+ maxDocs?: number;
349
+ /** Optional local sort run after flush. */
350
+ sort?: (a: T, b: T) => number;
351
+ }
352
+ interface CollectionStreamMeta {
353
+ reason: StreamFlushReason;
354
+ batchSize: number;
355
+ version: number;
356
+ ready: boolean;
357
+ }
358
+ type CollectionStreamListener<T = any> = (rows: readonly T[], meta: CollectionStreamMeta) => void;
359
+ interface CollectionStream<T = any> {
360
+ /** Subscribe to stream updates (call unsubscribe to stop). */
361
+ subscribe: (listener: CollectionStreamListener<T>, emitCurrent?: boolean) => () => void;
362
+ /** Returns the latest immutable snapshot of rows. */
363
+ getSnapshot: () => readonly T[];
364
+ /** Returns true after the initial snapshot has been received. */
365
+ isReady: () => boolean;
366
+ /** Monotonic version incremented on each flush. */
367
+ getVersion: () => number;
368
+ /** Stop the underlying realtime subscription and cleanup timers/listeners. */
369
+ close: () => void;
370
+ /** Attach subscription-level error handler. */
371
+ onError: (callback: SubscriptionErrorCallback) => CollectionStream<T>;
372
+ /** Attach permission-denied handler. */
373
+ onPermissionDenied: (callback: SubscriptionErrorCallback) => CollectionStream<T>;
374
+ }
375
+ interface CollectionExternalStore<T = any> {
376
+ /** Standard external-store subscribe signature used by UI store hooks. */
377
+ subscribe: (onStoreChange: () => void) => () => void;
378
+ /** Returns current immutable rows snapshot. */
379
+ getSnapshot: () => readonly T[];
380
+ /** Server snapshot fallback for SSR-safe store hooks. */
381
+ getServerSnapshot: () => readonly T[];
382
+ /** Access to underlying realtime stream for advanced handlers. */
383
+ stream: CollectionStream<T>;
384
+ /** Stops realtime stream and detaches listeners. */
385
+ destroy: () => void;
386
+ }
335
387
  interface DocumentSnapshot<T = any> {
336
388
  id: string;
337
389
  data: T | null;
@@ -632,6 +684,16 @@ declare class CollectionReference<T = any, TPresetMap extends QueryPresetMap = {
632
684
  * the live result consistent.
633
685
  */
634
686
  onSnapshot(callback: SubscriptionCallback<T[]>): SubscriptionHandle;
687
+ /**
688
+ * High-throughput stream wrapper for bursty collections (chat, feeds, logs).
689
+ * It keeps local state and flushes change bursts in batches to reduce UI churn.
690
+ */
691
+ stream(options?: CollectionStreamOptions<T>): CollectionStream<T>;
692
+ /**
693
+ * Framework-agnostic external-store bridge.
694
+ * Compatible with UI hooks expecting subscribe/getSnapshot signatures.
695
+ */
696
+ asStore(options?: CollectionStreamOptions<T>): CollectionExternalStore<T>;
635
697
  onDocAdded(callback: DocAddedCallback<T>): () => void;
636
698
  onDocUpdated(callback: DocUpdatedCallback<T>): () => void;
637
699
  onDocModified(callback: DocUpdatedCallback<T>): () => void;
@@ -1420,4 +1482,4 @@ declare const getFlare: () => FlareClient | null;
1420
1482
  */
1421
1483
  declare const disconnectFlare: () => void;
1422
1484
 
1423
- 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 CollectionPresetMethods, type CollectionQuery, CollectionReference, type ConnectionState, type CsrfProxyConfig, type CursorValue, type DocAddedCallback, type DocChangedCallback, type DocDeletedCallback, type DocUpdatedCallback, DocumentQueryBuilder, DocumentReference, type DocumentSnapshot, type EmailLinkVerifyResult, type EmailSendResult, FlareAction, type FlareAuthConfig, type FlareAuthProviderId, type FlareAuthProviderPublicConfig, type FlareAuthSession, type FlareAuthUser, 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 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, FlareClient as default, disconnectFlare, extractCsrfFromRequest, flareRulesToSecurityMap, getFlare, parseValue, parseWhereCondition, securityMapToFlareRules };
1485
+ 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 DocAddedCallback, type DocChangedCallback, type DocDeletedCallback, type DocUpdatedCallback, DocumentQueryBuilder, DocumentReference, type DocumentSnapshot, type EmailLinkVerifyResult, type EmailSendResult, FlareAction, type FlareAuthConfig, type FlareAuthProviderId, type FlareAuthProviderPublicConfig, type FlareAuthSession, type FlareAuthUser, 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, FlareClient as default, disconnectFlare, extractCsrfFromRequest, flareRulesToSecurityMap, getFlare, parseValue, parseWhereCondition, securityMapToFlareRules };
package/dist/index.d.ts CHANGED
@@ -332,6 +332,58 @@ type DocAddedCallback<T = any> = (data: T, docId: string) => void;
332
332
  type DocUpdatedCallback<T = any> = (data: T, docId: string) => void;
333
333
  type DocDeletedCallback<T = any> = (docId: string) => void;
334
334
  type DocChangedCallback<T = any> = (data: T | null, docId: string, operation: ChangeOperation) => void;
335
+ type StreamFlushReason = 'snapshot' | 'change-batch';
336
+ interface CollectionStreamOptions<T = any> {
337
+ /** Delay before a queued burst is flushed to listeners. */
338
+ flushMs?: number;
339
+ /** Flush immediately when queued changes reach this count. */
340
+ maxBatchSize?: number;
341
+ /** Field used to identify docs inside snapshots when getId is not provided. */
342
+ idField?: keyof T & string;
343
+ /** Custom identifier extractor for snapshot rows. */
344
+ getId?: (doc: T) => string | undefined;
345
+ /** Where newly inserted docs should be placed when they were not in snapshot. */
346
+ insertAt?: 'start' | 'end';
347
+ /** Optional cap to keep only the newest N docs in local stream state. */
348
+ maxDocs?: number;
349
+ /** Optional local sort run after flush. */
350
+ sort?: (a: T, b: T) => number;
351
+ }
352
+ interface CollectionStreamMeta {
353
+ reason: StreamFlushReason;
354
+ batchSize: number;
355
+ version: number;
356
+ ready: boolean;
357
+ }
358
+ type CollectionStreamListener<T = any> = (rows: readonly T[], meta: CollectionStreamMeta) => void;
359
+ interface CollectionStream<T = any> {
360
+ /** Subscribe to stream updates (call unsubscribe to stop). */
361
+ subscribe: (listener: CollectionStreamListener<T>, emitCurrent?: boolean) => () => void;
362
+ /** Returns the latest immutable snapshot of rows. */
363
+ getSnapshot: () => readonly T[];
364
+ /** Returns true after the initial snapshot has been received. */
365
+ isReady: () => boolean;
366
+ /** Monotonic version incremented on each flush. */
367
+ getVersion: () => number;
368
+ /** Stop the underlying realtime subscription and cleanup timers/listeners. */
369
+ close: () => void;
370
+ /** Attach subscription-level error handler. */
371
+ onError: (callback: SubscriptionErrorCallback) => CollectionStream<T>;
372
+ /** Attach permission-denied handler. */
373
+ onPermissionDenied: (callback: SubscriptionErrorCallback) => CollectionStream<T>;
374
+ }
375
+ interface CollectionExternalStore<T = any> {
376
+ /** Standard external-store subscribe signature used by UI store hooks. */
377
+ subscribe: (onStoreChange: () => void) => () => void;
378
+ /** Returns current immutable rows snapshot. */
379
+ getSnapshot: () => readonly T[];
380
+ /** Server snapshot fallback for SSR-safe store hooks. */
381
+ getServerSnapshot: () => readonly T[];
382
+ /** Access to underlying realtime stream for advanced handlers. */
383
+ stream: CollectionStream<T>;
384
+ /** Stops realtime stream and detaches listeners. */
385
+ destroy: () => void;
386
+ }
335
387
  interface DocumentSnapshot<T = any> {
336
388
  id: string;
337
389
  data: T | null;
@@ -632,6 +684,16 @@ declare class CollectionReference<T = any, TPresetMap extends QueryPresetMap = {
632
684
  * the live result consistent.
633
685
  */
634
686
  onSnapshot(callback: SubscriptionCallback<T[]>): SubscriptionHandle;
687
+ /**
688
+ * High-throughput stream wrapper for bursty collections (chat, feeds, logs).
689
+ * It keeps local state and flushes change bursts in batches to reduce UI churn.
690
+ */
691
+ stream(options?: CollectionStreamOptions<T>): CollectionStream<T>;
692
+ /**
693
+ * Framework-agnostic external-store bridge.
694
+ * Compatible with UI hooks expecting subscribe/getSnapshot signatures.
695
+ */
696
+ asStore(options?: CollectionStreamOptions<T>): CollectionExternalStore<T>;
635
697
  onDocAdded(callback: DocAddedCallback<T>): () => void;
636
698
  onDocUpdated(callback: DocUpdatedCallback<T>): () => void;
637
699
  onDocModified(callback: DocUpdatedCallback<T>): () => void;
@@ -1420,4 +1482,4 @@ declare const getFlare: () => FlareClient | null;
1420
1482
  */
1421
1483
  declare const disconnectFlare: () => void;
1422
1484
 
1423
- 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 CollectionPresetMethods, type CollectionQuery, CollectionReference, type ConnectionState, type CsrfProxyConfig, type CursorValue, type DocAddedCallback, type DocChangedCallback, type DocDeletedCallback, type DocUpdatedCallback, DocumentQueryBuilder, DocumentReference, type DocumentSnapshot, type EmailLinkVerifyResult, type EmailSendResult, FlareAction, type FlareAuthConfig, type FlareAuthProviderId, type FlareAuthProviderPublicConfig, type FlareAuthSession, type FlareAuthUser, 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 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, FlareClient as default, disconnectFlare, extractCsrfFromRequest, flareRulesToSecurityMap, getFlare, parseValue, parseWhereCondition, securityMapToFlareRules };
1485
+ 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 DocAddedCallback, type DocChangedCallback, type DocDeletedCallback, type DocUpdatedCallback, DocumentQueryBuilder, DocumentReference, type DocumentSnapshot, type EmailLinkVerifyResult, type EmailSendResult, FlareAction, type FlareAuthConfig, type FlareAuthProviderId, type FlareAuthProviderPublicConfig, type FlareAuthSession, type FlareAuthUser, 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, FlareClient as default, disconnectFlare, extractCsrfFromRequest, flareRulesToSecurityMap, getFlare, parseValue, parseWhereCondition, securityMapToFlareRules };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {Credentials,Anonymous,Google,GitHub,Facebook,Dropbox,Apple,Twitter,AuthGuard}from'@zuzjs/auth';export{Anonymous,Apple,AuthGuard,Credentials,Dropbox,Facebook,GitHub,Google,Providers,Twitter,setupProvider}from'@zuzjs/auth';import {uuid2,withGet,withPut,withPatch,withPost}from'@zuzjs/core';var h=class extends Error{constructor(t,r,i){super(t);this.code=r;this.cause=i;this.name="ZuzFlareError";}};var X={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},c=X;var ee=(d=>(d.SUBSCRIBE="subscribe",d.UNSUBSCRIBE="unsubscribe",d.WRITE="write",d.DELETE="delete",d.AUTH="auth",d.PING="ping",d.OFFLINE_SYNC="offline_sync",d.CALL="call",d.QUERY="query",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d.PRESENCE_HEARTBEAT="presence_heartbeat",d))(ee||{}),te=(d=>(d.SNAPSHOT="snapshot",d.CHANGE="change",d.ERROR="error",d.ACK="ack",d.PONG="pong",d.AUTH_OK="auth_ok",d.OFFLINE_ACK="offline_ack",d.CALL_RESPONSE="call_response",d.QUERY_RESULT="query_result",d.PRESENCE_STATE="presence_state",d.PRESENCE_JOIN="presence_join",d.PRESENCE_LEAVE="presence_leave",d))(te||{});function O(a){let e=[];for(let[t,r]of Object.entries(a))if(typeof r=="string"){let i=r.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(i){let[,n,s]=i;e.push({field:t,op:n,value:q(s.trim())});}else e.push({field:t,op:"==",value:r});}else Array.isArray(r)?e.push({field:t,op:"in",value:r}):e.push({field:t,op:"==",value:r});return e}function q(a){if(!isNaN(Number(a)))return Number(a);if(a==="true")return true;if(a==="false")return false;if(a==="null")return null;if(a!=="undefined")return a}var b=class{constructor(e,t,r){this.client=e;this.collection=t;this.legacyId=r;}whereCondition;updateData;setData;deleteOp=false;promise;where(e){return this.whereCondition=e,this}update(e){return this.updateData=e,this}set(e){return this.setData=e,this}delete(){return this.deleteOp=true,this}getDocId(){if(this.legacyId)return this.legacyId;if(this.whereCondition&&(this.whereCondition.id||this.whereCondition._id)){let e=this.whereCondition.id??this.whereCondition._id;if(typeof e=="string")return e}throw new h('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',c.QueryFailed)}async execute(){return this._execute()}async _execute(){let e=this.getDocId();if(this.deleteOp){await this.client.send("delete",{collection:this.collection,docId:e});return}if(this.updateData){await this.client.send("write",{collection:this.collection,docId:e,data:this.updateData,merge:true});return}if(this.setData){await this.client.send("write",{collection:this.collection,docId:e,data:this.setData,merge:false});return}return this.get()}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}async get(){let e=this.getDocId(),t=uuid2(18);return new Promise((r,i)=>{let n=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(n(),r(s.data));});setTimeout(()=>{n(),i(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),r=uuid2(18);return this.client.subscribe(r,this.collection,t,void 0,e)}};var _=class{constructor(e,t,r){this.client=e;this.collection=t;this.id=r;}async get(){return new b(this.client,this.collection,this.id).get()}async set(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:false});}async update(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:true});}async delete(){await this.client.send("delete",{collection:this.collection,docId:this.id});}onSnapshot(e){let t=uuid2(18),r=()=>{};return r=this.client.subscribe(t,this.collection,this.id,void 0,i=>{i.type==="snapshot"&&(e(i),r());}),r}onDocUpdated(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data&&e(r.data,r.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&r.operation==="delete"&&e(r.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="change"&&e(r.data??null,r.docId,r.operation);},{skipSnapshot:true})}},P=_;var N=class a{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(r,i,n)=>{if(typeof i=="string"&&!(i in r)&&this.client.hasQueryPreset(i))return (o={})=>r.with(i,o);let s=Reflect.get(r,i,n);return typeof s=="function"?s.bind(r):s}})}sq={};promise;doc(e){return new P(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}normalizeFilterValue(e,t){return e==="in"||e==="not-in"||e==="array-contains-any"?Array.isArray(t)?t:[t]:t}normalizeFilter(e){return {...e,value:this.normalizeFilterValue(e.op,e.value)}}toQueryFilters(e){return O(e).map(t=>this.normalizeFilter(t))}appendOperatorFilter(e,t,r,i){return this.appendFilters([this.normalizeFilter({field:e,op:t,value:r})],i)}appendAndFilters(e){return this.clone({where:[...this.sq.where??[],...e]})}toOrNode(e){return {or:e}}toAndNode(e){return {and:e}}appendOrFilters(e){let t=[...this.sq.where??[]];if(t.length===0)return this.clone({where:[this.toOrNode(e)]});let r=t[0];if(t.length===1&&typeof r=="object"&&r!=null&&"or"in r){let s=r;return this.clone({where:[{or:[...s.or,...e]}]})}let n=t.length===1?t[0]:{and:t};return this.clone({where:[{or:[n,...e]}]})}appendFilters(e,t){return t==="or"?this.appendOrFilters(e):this.appendAndFilters(e)}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e){return this.appendFilters(this.toQueryFilters(e),"and")}and(e){return this.appendFilters(this.toQueryFilters(e),"and")}or(e){return this.appendFilters(this.toQueryFilters(e),"or")}in(e,t){return this.appendOperatorFilter(e,"in",t,"and")}andIn(e,t){return this.appendOperatorFilter(e,"in",t,"and")}orIn(e,t){return this.appendOperatorFilter(e,"in",t,"or")}notIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}andNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}orNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"or")}arrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}andArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}orArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"or")}arrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}andArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}orArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"or")}some(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}andSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}orSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"or")}like(e,t){return this.appendOperatorFilter(e,"like",t,"and")}andLike(e,t){return this.appendOperatorFilter(e,"like",t,"and")}orLike(e,t){return this.appendOperatorFilter(e,"like",t,"or")}notLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}andNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}orNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"or")}exists(e){return this.appendOperatorFilter(e,"exists",true,"and")}andExists(e){return this.appendOperatorFilter(e,"exists",true,"and")}orExists(e){return this.appendOperatorFilter(e,"exists",true,"or")}notExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}andNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}orNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"or")}latest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"desc"}]})}oldest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"asc"}]})}orderBy(e,t="asc"){return this.clone({orderBy:[...this.sq.orderBy??[],{field:e,dir:t}]})}limit(e){return this.clone({limit:e})}offset(e){return this.clone({offset:e})}startAt(...e){return this.clone({startAt:{values:e}})}startAfter(...e){return this.clone({startAfter:{values:e}})}endAt(...e){return this.clone({endAt:{values:e}})}endBefore(...e){return this.clone({endBefore:{values:e}})}aggregate(...e){return this.clone({aggregate:[...this.sq.aggregate??[],...e]})}count(e="count"){return this.aggregate({fn:"count",alias:e})}sum(e,t){return this.aggregate({fn:"sum",field:e,alias:t??`sum_${e}`})}avg(e,t){return this.aggregate({fn:"avg",field:e,alias:t??`avg_${e}`})}min(e,t){return this.aggregate({fn:"min",field:e,alias:t??`min_${e}`})}max(e,t){return this.aggregate({fn:"max",field:e,alias:t??`max_${e}`})}distinct(e,t){return this.aggregate({fn:"distinct",field:e,alias:t??`distinct_${e}`})}groupBy(...e){return this.clone({groupBy:{fields:e}})}having(e,t,r){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:r}]})}buildStructuredJoin(e,t){let i={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(i.where=t.where),Array.isArray(t?.orderBy)&&(i.orderBy=t.orderBy),typeof t?.limit=="number"&&(i.limit=t.limit),typeof t?.offset=="number"&&(i.offset=t.offset),t?.startAt&&(i.startAt=t.startAt),t?.startAfter&&(i.startAfter=t.startAfter),t?.endAt&&(i.endAt=t.endAt),t?.endBefore&&(i.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(i.aggregate=t.aggregate),t?.groupBy&&(i.groupBy=t.groupBy),Array.isArray(t?.having)&&(i.having=t.having),t?.vectorSearch&&(i.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(i.select=t.select),typeof t?.distinctField=="string"&&(i.distinctField=t.distinctField),Array.isArray(t?.joins)&&(i.joins=t.joins.map(n=>this.buildStructuredJoin(String(n?.collection??""),n))),i}Join(e,t){let r=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],r]})}join(e,t){if(typeof e=="string")return this.Join(e,t);let r=String(e.collection??e.from??""),i=this.buildStructuredJoin(r,e);return this.clone({joins:[...this.sq.joins??[],i]})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}async get(){return this._execute()}_isStructured(){return !!(this.sq.orderBy?.length||this.sq.aggregate?.length||this.sq.groupBy||this.sq.having?.length||this.sq.joins?.length||this.sq.vectorSearch||this.sq.distinctField||this.sq.offset||this.sq.startAt||this.sq.startAfter||this.sq.endAt||this.sq.endBefore||this.sq.select?.length)}async _execute(){return this._isStructured()?this._executeQuery():this._executeSubscribe()}async _executeQuery(){return (await this.client.send("query",{collection:this.collection,query:this.sq})).data??[]}async _executeSubscribe(){let e=uuid2(18);return new Promise((t,r)=>{let i=Object.keys(this.sq).length>0?this.sq:void 0,n=this.client.subscribe(e,this.collection,void 0,i,s=>{s.type==="snapshot"&&(n(),t(s.data));});setTimeout(()=>{n(),r(new Error("Collection fetch timeout"));},1e4);})}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}onSnapshot(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0,i=(()=>{});return i=this.client.subscribe(t,this.collection,void 0,r,n=>{n.type==="snapshot"&&(e(n),i());}),i}onDocAdded(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&i.operation==="insert"&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&(i.operation==="update"||i.operation==="replace")&&i.data!=null&&e(i.data,i.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&i.operation==="delete"&&e(i.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="change"&&e(i.data??null,i.docId,i.operation);},{skipSnapshot:true})}async add(e){let t=uuid2(18),r=this.doc(t);return await r.set(e),r}update(e){return new b(this.client,this.collection).update(e)}delete(){return new b(this.client,this.collection).delete()}},B=N;async function ie(a){let e=a.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,""),t=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary"),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",r.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function re(a,e){let t=await ie(e),r=new TextEncoder().encode(JSON.stringify(a)),n=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,r),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(n))):Buffer.from(n).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var R=class{socket=null;reconnectInterval;maxReconnectDelay;isConnected=false;shouldReconnect=true;options;messageQueue=[];heartbeatInterval=null;connectionTimeout=null;constructor(e){this.options=e,this.reconnectInterval=e.reconnectDelay||2,this.maxReconnectDelay=e.maxReconnectDelay||60,this.log("Transport initialized",e.url);}connect(){if(this.socket){this.log("Socket already exists, skipping connection");return}this.log("Connecting to",this.options.url),this.socket=new WebSocket(this.options.url),this.connectionTimeout=setTimeout(()=>{this.isConnected||(this.log("Connection timeout"),this.socket?.close(),this.handleReconnect());},1e4),this.socket.onopen=()=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=true,this.reconnectInterval=this.options.reconnectDelay||2,this.log("Connected to server"),this.options.onOpen?.(),this.startHeartbeat(),this.flushQueue();},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data);this.options.onMessage(t);}catch(t){this.log("Parse error",t),this.options.onError?.(t);}},this.socket.onerror=e=>{this.log("WebSocket error",e),this.options.onError?.(new Error("WebSocket error"));},this.socket.onclose=e=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=false,this.socket=null,this.stopHeartbeat(),this.log("Connection closed",e.code,e.reason),this.options.onClose?.(),e.code!==1e3&&this.shouldReconnect&&this.options.autoReconnect&&this.handleReconnect();};}handleReconnect(){let e=this.reconnectInterval*1e3;this.log(`Reconnecting in ${this.reconnectInterval}s...`),setTimeout(()=>{this.reconnectInterval=Math.min(this.reconnectInterval*2,this.maxReconnectDelay),this.connect();},e);}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send({type:"ping",id:Date.now().toString(),ts:Date.now()});},3e4);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}flushQueue(){for(this.log("Flushing message queue",this.messageQueue.length);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}send(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){let t=r=>{try{this.socket.send(r),this.log("Sent message",e);}catch(i){this.log("Send error",i),this.messageQueue.push(e);}};this.options.publicKey?re(e,this.options.publicKey).then(t).catch(r=>{this.log("RSA encrypt error \u2014 sending plaintext",r),t(JSON.stringify(e));}):t(JSON.stringify(e));}else this.log("Socket not ready, queueing message"),this.messageQueue.push(e);}disconnect(){this.shouldReconnect=false,this.stopHeartbeat(),this.socket&&(this.socket.close(1e3,"Client disconnect"),this.socket=null),this.isConnected=false,this.log("Disconnected");}get connected(){return this.isConnected}log(...e){this.options.debug&&console.log("[FlareTransport]",...e);}};var ue={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},j={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},F=class{transport;config;pendingAcks=new Map;subscriptions=new Map;activeSubscriptions=new Map;queryPresets=new Map;subscriptionErrorHandlers=new Map;subscriptionPermissionHandlers=new Map;subscriptionLastErrors=new Map;offlineQueue=[];currentState="disconnected";connectionListeners=[];errorListeners=[];isDebug=false;socketAuthUid="anon";pendingSubscriptionReplay=false;subscriptionReplayPromise=Promise.resolve();requestTraceSeq=0;requestTimingEnabled=true;httpInFlight=new Map;httpResponseCache=new Map;maxHttpCacheEntries=200;presenceCallbacks=new Map;presenceJoinCbs=new Map;presenceLeaveCbs=new Map;presenceHeartbeatTimer;embedder;vectorSchema=new Map;throwFetchFlareError(e,t,r){let i=e,n=typeof i?.error=="string"&&i.error.length>0?i.error:r,s=typeof i?.message=="string"&&i.message.length>0?i.message:t;throw new h(s,n,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((r,i)=>{t[i]=r;});else if(Array.isArray(e))for(let[r,i]of e)t[String(r)]=String(i);else for(let[r,i]of Object.entries(e))t[String(r)]=String(i);return t}redactHeaders(e){let t={...e};for(let r of Object.keys(t)){let i=r.toLowerCase();(i==="authorization"||i==="x-flare-csrf"||i==="x-csrf-token")&&(t[r]="[redacted]");}return t}stableStringify(e){if(e==null)return "";if(typeof e=="string")return e;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return e.toString();if(typeof e!="object")return String(e);if(Array.isArray(e))return `[${e.map(i=>this.stableStringify(i)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(i=>`${i}:${this.stableStringify(t[i])}`).join(",")}}`}buildHttpCacheKey(e,t,r,i,n){let o=Object.entries(r).map(([l,g])=>[l.toLowerCase(),g]).sort(([l],[g])=>l.localeCompare(g)).map(([l,g])=>`${l}:${g}`).join("|"),u=this.stableStringify(i);return `${e}|${t}|${n??""}|${o}|${u}`}shouldCacheResponse(e,t){return !!(e==="GET"||e==="POST"&&/\/auth\/refresh(?:\?|$)/.test(t))}rememberHttpResponse(e,t){if(this.httpResponseCache.set(e,t),this.httpResponseCache.size<=this.maxHttpCacheEntries)return;let r=this.httpResponseCache.keys().next().value;r&&this.httpResponseCache.delete(r);}createTimedFetchTrace(e,t,r,i,n,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:o=>{let u=o.toLowerCase();for(let[l,g]of Object.entries(e.headers))if(l.toLowerCase()===u)return String(g);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:r,networkMs:s,method:i,url:n}}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let r=new Headers(e);for(let[i,n]of Object.entries(t))r.set(i,n);return r}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(ue[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(j[t]?j[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(i=>this.normalizeOutboundData(i));if(!e||typeof e!="object")return e;let t=e,r={};for(let[i,n]of Object.entries(t))r[this.toWireField(i)]=this.normalizeOutboundData(n);return r}normalizeInboundData(e){if(Array.isArray(e))return e.map(i=>this.normalizeInboundData(i));if(!e||typeof e!="object")return e;let t=e,r={};for(let[i,n]of Object.entries(t))r[this.fromWireField(i)]=this.normalizeInboundData(n);return r}normalizeOutboundAnyFilter(e){return Array.isArray(e.or)?{...e,or:e.or.map(t=>this.normalizeOutboundAnyFilter(t))}:Array.isArray(e.and)?{...e,and:e.and.map(t=>this.normalizeOutboundAnyFilter(t))}:typeof e.field=="string"?{...e,field:this.toWireField(e.field)}:{...e}}normalizeOutboundQuery(e){if(!e)return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.field=="string")return this.normalizeOutboundAnyFilter(e);if(Array.isArray(e))return e.map(n=>this.normalizeOutboundAnyFilter(n));if(typeof e!="object")return e;let t=e,r={...t},i=n=>{let s={...n};return s.localField=this.toWireField(String(n?.localField??"")),s.foreignField=this.toWireField(String(n?.foreignField??"")),Array.isArray(n.where)&&(s.where=n.where.map(o=>this.normalizeOutboundAnyFilter(o))),Array.isArray(n.orderBy)&&(s.orderBy=n.orderBy.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),n.groupBy&&typeof n.groupBy=="object"&&Array.isArray(n.groupBy.fields)&&(s.groupBy={...n.groupBy,fields:n.groupBy.fields.map(o=>this.toWireField(String(o??"")))}),Array.isArray(n.having)&&(s.having=n.having.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),Array.isArray(n.select)&&(s.select=n.select.map(o=>this.toWireField(String(o??"")))),typeof n.distinctField=="string"&&(s.distinctField=this.toWireField(n.distinctField)),n.vectorSearch&&typeof n.vectorSearch=="object"&&(s.vectorSearch={...n.vectorSearch,field:this.toWireField(String(n.vectorSearch.field??""))}),Array.isArray(n.joins)&&(s.joins=n.joins.map(o=>i(o))),s};return Array.isArray(t.where)&&(r.where=t.where.map(n=>this.normalizeOutboundAnyFilter(n))),Array.isArray(t.orderBy)&&(r.orderBy=t.orderBy.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(r.groupBy={...t.groupBy,fields:t.groupBy.fields.map(n=>this.toWireField(String(n??"")))}),Array.isArray(t.having)&&(r.having=t.having.map(n=>({...n,field:this.toWireField(String(n?.field??""))}))),Array.isArray(t.select)&&(r.select=t.select.map(n=>this.toWireField(String(n??"")))),typeof t.distinctField=="string"&&(r.distinctField=this.toWireField(t.distinctField)),t.vectorSearch&&typeof t.vectorSearch=="object"&&(r.vectorSearch={...t.vectorSearch,field:this.toWireField(String(t.vectorSearch.field??""))}),Array.isArray(t.joins)&&(r.joins=t.joins.map(n=>i(n))),r}async timedFetch(e,t,r){let i=++this.requestTraceSeq,n=this.nowMs(),s=String(r?.method??"GET").toUpperCase(),o=this.normalizeHeaders(r?.headers),u=this.redactHeaders(o),l=r?.body,g=this.buildHttpCacheKey(s,t,o,l,r?.credentials),f=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${i} ${e} start`,{method:s,url:t,headers:u,hasBody:!!r?.body});try{if(f){let T=this.httpResponseCache.get(g);if(T)return this.logHttpTiming(`#${i} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(T,i,n,s,t,0)}let d=this.httpInFlight.get(g);if(d){let T=await d,p=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} deduped`,{method:s,url:t,networkMs:Number(p.toFixed(2))}),this.createTimedFetchTrace(T,i,n,s,t,p)}let A=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(i)}),S=this.normalizeHeaders(A),G=this.redactHeaders(S),I={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:S,withCredentials:r?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${i} ${e} request`,{method:s,url:t,headers:G,hasBody:!!r?.body});let M=s.toUpperCase(),W=(async()=>{let T=M==="GET"?await withGet(t,I):M==="PUT"?await withPut(t,l,I):M==="PATCH"?await withPatch(t,l,I):await withPost(t,l,I),p={status:Number(T?.status??0),headers:Object.fromEntries(Object.entries(T?.headers??{}).map(([Y,Z])=>[Y,String(Z)])),data:T?.data??{}};return f&&this.rememberHttpResponse(g,p),p})();this.httpInFlight.set(g,W);let L=await W.finally(()=>{this.httpInFlight.delete(g);}),$=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} response`,{status:L.status,networkMs:Number($.toFixed(2))}),this.createTimedFetchTrace(L,i,n,s,t,$)}catch(d){let A=this.nowMs()-n;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(A.toFixed(2)),message:d?.message??String(d)}),d}}async parseJsonWithTiming(e,t){let r=this.nowMs(),i=await t.response.json().catch(()=>({})),n=this.nowMs()-r,s=this.nowMs()-t.startedAtMs;return this.logHttpTiming(`#${t.requestId} ${e} complete`,{method:t.method,url:t.url,status:t.response.status,networkMs:Number(t.networkMs.toFixed(2)),parseMs:Number(n.toFixed(2)),totalMs:Number(s.toFixed(2))}),i}getHttpBase(){if(this.config.httpBase)return this.config.httpBase.replace(/\/$/,"");let e=new URL(this.config.endpoint);return `${e.protocol}//${e.host}`}log(...e){this.isDebug&&console.log("[FlareClient]",...e);}constructor(e){this.config={autoReconnect:true,reconnectDelay:2,maxReconnectDelay:60,debug:false,connectionTimeout:1e4,...e},this.isDebug=this.config.debug||false,this.requestTimingEnabled=this.config.requestTiming??true;let{hostname:t,port:r,protocol:i}=new URL(this.config.endpoint),n=i==="https:",u=`${n?"wss":"ws"}://${t}:${r||(n?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new R({url:u,publicKey:this.config.publicKey,autoReconnect:this.config.autoReconnect,reconnectDelay:this.config.reconnectDelay,maxReconnectDelay:this.config.maxReconnectDelay,onMessage:l=>this.handleIncoming(l),onOpen:()=>this.onConnected(),onClose:()=>this.onDisconnected(),onError:l=>this.handleTransportError(l),debug:this.isDebug});}connect(){this.setState("connecting"),this.transport.connect();}disconnect(){this.transport.disconnect(),this.setState("disconnected");}get connectionState(){return this.currentState}get isConnected(){return this.currentState==="connected"}onConnectionStateChange(e){return this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e);}}collection(e){return new B(this,e)}registerQueryPreset(e,t){let r=String(e??"").trim();if(!r)throw new h("Preset name is required",c.QueryFailed);if(typeof t!="function")throw new h(`Query preset "${r}" handler must be a function`,c.QueryFailed);return this.queryPresets.set(r,t),this}registerQueryPresets(e){for(let[t,r]of Object.entries(e??{}))this.registerQueryPreset(t,r);return this}hasQueryPreset(e){return this.queryPresets.has(String(e??"").trim())}applyQueryPreset(e,t,r={}){let i=String(t??"").trim(),n=this.queryPresets.get(i);if(!n)throw new h(`Unknown query preset "${i}"`,c.QueryFailed);let s=n(e,r??{});if(!s||typeof s.get!="function")throw new h(`Query preset "${i}" must return a CollectionReference`,c.QueryFailed);return s}doc(e,t){return t!==void 0?new P(this,e,t):new b(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let r=await this.send("call",{topic:e,payload:t});if(!r.success)throw new h(r.error??`CALL "${e}" failed`,c.QueryFailed);return r.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,r={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,r);}async embedVectorFields(e,t){let r=this.vectorSchema.get(e);if(!r)return t;let i={...t};for(let[n,s]of r){let o=i[n];if(typeof o=="string"){let u=s.embed??this.embedder;if(!u){this.log(`[vector] No embedder for field "${n}" \u2014 storing raw text`);continue}i[n]=await u(o);}}return i}async joinPresence(e,t){return await this.send("presence_join",{room:e,meta:t}),this._startPresenceHeartbeat(e,t),()=>this.leavePresence(e)}async leavePresence(e){await this.send("presence_leave",{room:e}),this._stopPresenceHeartbeat();}onPresenceState(e,t){return this.presenceCallbacks.has(e)||this.presenceCallbacks.set(e,[]),this.presenceCallbacks.get(e).push(t),()=>{let r=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,r.filter(i=>i!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let r=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,r.filter(i=>i!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let r=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,r.filter(i=>i!==t));}}_startPresenceHeartbeat(e,t){this.presenceHeartbeatTimer||(this.presenceHeartbeatTimer=setInterval(()=>{this.isConnected&&this.send("presence_heartbeat",{meta:t}).catch(()=>{});},2e4));}_stopPresenceHeartbeat(){this.presenceHeartbeatTimer&&(clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=void 0);}async syncOffline(){if(this.offlineQueue.length===0)return;this.log("Syncing offline operations",this.offlineQueue.length);let e=[...this.offlineQueue];this.offlineQueue.length=0;let t=await this.send("offline_sync",{operations:e});t.conflicts&&t.conflicts.length>0&&(this.log("Offline sync conflicts",t.conflicts),t.conflicts.forEach(r=>{let i=e.find(n=>n.id===r.operationId);i&&this.offlineQueue.push(i);}));}async beforeActivateSubscription(e){}async activateSubscription(e){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}await this.beforeActivateSubscription(e),this.subscriptions.set(e.liveId,e.callback);try{let t=await this.send("subscribe",{collection:e.collection,docId:e.docId,query:e.query,skipSnapshot:e.options.skipSnapshot});if(!this.activeSubscriptions.has(e.baseId)){this.subscriptions.delete(e.liveId);return}t.subscriptionId&&t.subscriptionId!==e.liveId&&(this.subscriptions.delete(e.liveId),e.liveId=t.subscriptionId,this.subscriptions.set(e.liveId,e.callback),this.log("Subscription remapped",e.baseId,"\u2192",e.liveId));}catch(t){this.subscriptions.delete(e.liveId),this.pendingSubscriptionReplay=true;let r=this.toSubscriptionError(t);this.emitSubscriptionError(e.baseId,r),this.log("Subscription failed",t);}}toSubscriptionError(e){let t=e instanceof Error?e.message:String(e??"Unknown subscription error"),r=t.match(/^\[([^\]]+)\]\s*(.*)$/),i=r?.[1],n=(r?.[2]??t).trim()||t,s=i===c.PermissionDenied||t.includes(c.PermissionDenied);return {code:i,message:n,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let r=this.subscriptionErrorHandlers.get(e);if(r)for(let i of r)try{i(t);}catch(n){this.log("Subscription error callback failed",n);}if(t.permissionDenied){let i=this.subscriptionPermissionHandlers.get(e);if(i)for(let n of i)try{n(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let r=t.liveId;this.subscriptions.delete(r),t.liveId=t.baseId,r&&await this.send("unsubscribe",{subscriptionId:r}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,r,i,n,s={}){this.log("Creating subscription",e,t,r);let o={baseId:e,liveId:e,collection:t,docId:r,query:i,callback:n,options:s};this.activeSubscriptions.set(e,o),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(o).catch(g=>{this.log("Subscription activation failed",g);});let u=()=>{let f=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",f),this.activeSubscriptions.delete(e),this.subscriptions.delete(f),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:f}).catch(d=>this.log("Unsubscribe failed",d));},l=u;return l.unsubscribe=u,l.onError=g=>{this.subscriptionErrorHandlers.get(e)?.add(g);let f=this.subscriptionLastErrors.get(e);if(f)try{g(f);}catch(d){this.log("Subscription error callback failed",d);}return l},l.onPermissionDenied=g=>{this.subscriptionPermissionHandlers.get(e)?.add(g);let f=this.subscriptionLastErrors.get(e);if(f?.permissionDenied)try{g(f);}catch(d){this.log("Subscription permission callback failed",d);}return l},l.catch=g=>l.onError(g),l}async send(e,t){if(e==="write"&&t.collection&&t.data){let r=await this.embedVectorFields(t.collection,t.data);t={...t,data:this.normalizeOutboundData(r)};}return (e==="subscribe"||e==="query")&&t?.query&&(t={...t,query:this.normalizeOutboundQuery(t.query)}),new Promise((r,i)=>{let n=uuid2(18),s={id:n,type:e,ts:Date.now(),...t};this.pendingAcks.set(n,o=>{o.type==="error"?i(new Error(`[${o.code}] ${o.message}`)):r(o);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),i(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(n)&&(this.pendingAcks.delete(n),i(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(r){this.log("Error listener error",r);}});}onConnected(){this.setState("connected"),this.log("Connected to FlareServer"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.offlineQueue.length>0&&this.syncOffline().catch(e=>{this.log("Offline sync failed",e);});}onDisconnected(){this.currentState!=="disconnected"&&this.setState("reconnecting"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.log("Disconnected from FlareServer");}setState(e){this.currentState!==e&&(this.currentState=e,this.log("Connection state changed",e),this.connectionListeners.forEach(t=>{try{t(e);}catch(r){this.log("Connection listener error",r);}}));}handleIncoming(e){if(this.log("Received message",e.type,e),e.type==="query_result"&&Array.isArray(e.data)&&(e={...e,data:this.normalizeInboundData(e.data)}),e.type==="ack"||e.type==="pong"||e.type==="auth_ok"||e.type==="call_response"||e.type==="query_result"){let t=this.pendingAcks.get(e.correlationId||e.id);t&&(t(e),this.pendingAcks.delete(e.correlationId||e.id));return}if(e.type==="error"){this.log("Server error",e.code,e.message);let t=new Error(`[${e.code}] ${e.message}`);this.errorListeners.forEach(i=>{try{i(t);}catch(n){this.log("Error listener error",n);}});let r=Array.from(this.activeSubscriptions.values()).find(i=>i.liveId===e.correlationId||i.baseId===e.correlationId);if(r&&this.emitSubscriptionError(r.baseId,{code:typeof e.code=="string"?e.code:void 0,message:String(e.message??"Subscription error"),permissionDenied:e.code===c.PermissionDenied,raw:e}),e.correlationId){let i=this.pendingAcks.get(e.correlationId);i&&(i(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(r=>{try{r(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(r=>{try{r(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(r=>{try{r(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),i={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(r)?r:[]};try{t(i);}catch(n){this.log("Subscription callback error",n);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:e.operation==="delete"?null:this.normalizeInboundData(e.data)};try{t(r);}catch(i){this.log("Subscription callback error",i);}}}}};var E=class extends F{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;socketAuthSyncPromise;pushServiceWorkerInitPromise;authSession=null;authStateListeners=[];authConfigListeners=[];currentProfile=void 0;getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return this.getCookieValue(this.getCsrfCookieName())??this.csrfToken??null}getCookieValue(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`)||i.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let r=t.indexOf("=");return r>=0?decodeURIComponent(t.slice(r+1)):null}extractCsrfToken(e,t){let r=e,i=typeof r?.csrfToken=="string"?String(r.csrfToken):typeof r?.csrf_token=="string"?String(r.csrf_token):void 0;if(i)return i;if(!t)return;let n=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof n=="string"&&n.length>0?n:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}setCsrfToken(e){this.csrfToken=e,this.csrfBootstrapAttempted=true,this.log("CSRF token injected",{length:e.length});}async ensureCsrfProtection(){if(this.getCsrfToken()){this.csrfBootstrapAttempted=true;return}if(this.config.httpBase){this.csrfBootstrapAttempted=true;return}this.csrfBootstrapAttempted||(this.csrfInitPromise||(this.csrfBootstrapAttempted=true,this.csrfInitPromise=this.loadAuthConfig().then(()=>{}).finally(()=>{this.csrfInitPromise=void 0;})),await this.csrfInitPromise,this.getCsrfToken()||this.log("CSRF token unavailable after auth config load",{hasAuthConfig:!!this.authConfig,csrfCookieName:this.getCsrfCookieName()}));}async loadAuthConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/auth/config?${t.toString()}`,i=await this.timedFetch("loadAuthConfig",r,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("loadAuthConfig",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to load auth config",c.QueryFailed),this.authConfig=n,this.csrfToken=this.extractCsrfToken(n,i.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(o){this.log("Auth config listener error",o);}}),this.authConfig}async fetchAuthConfig(){return this.authConfig?this.authConfig:this.loadAuthConfig()}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}setProfile(e){this.currentProfile=e;}setAuthSession(e){this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid):(this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear());let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;this.authStateListeners.forEach(r=>{try{r(t);}catch(i){this.log("Auth state listener error",i);}});}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;try{e(t);}catch(r){this.log("Auth state listener error during initialization",r);}return ()=>{this.authStateListeners=this.authStateListeners.filter(r=>r!==e);}}onAuthStateChange(e){return this.onAuthStateChanged(e)}get currentUser(){return this.currentProfile}getCurrentUser(){return this.currentUser}async syncSocketAuth(e){if(!this.isConnected)return;let t=await this.send("auth",e?{token:e}:{});if(t.type!=="auth_ok")throw new h("Socket auth sync failed",c.AuthenticationFailed);if(!e||t.uid==="anon"){this.authToken=void 0,this.userId=void 0,await this.updateSocketIdentity("anon");return}this.authToken=typeof t.token=="string"?t.token:e,this.userId=typeof t.uid=="string"?t.uid:this.userId,await this.updateSocketIdentity(typeof t.uid=="string"?t.uid:this.userId);}async updateSocketIdentity(e,t=false){let r=typeof e=="string"&&e.length>0?e:"anon",i=r!==this.socketAuthUid;this.socketAuthUid=r,(i||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async beforeActivateSubscription(e){if(!this.isConnected)return;let t=this.authSession;!t?.accessToken||!t.uid||this.socketAuthUid!==t.uid&&(this.socketAuthSyncPromise||(this.socketAuthSyncPromise=this.syncSocketAuth(t.accessToken).catch(r=>{throw this.log("Socket auth sync failed before subscribe",r),r}).finally(()=>{this.socketAuthSyncPromise=void 0;})),await this.socketAuthSyncPromise);}onConnected(){super.onConnected(),this.authSession?.accessToken&&this.syncSocketAuth(this.authSession.accessToken).catch(e=>{this.log("Socket auth sync failed after connect",e);});}handleIncoming(e){if(e.type==="auth_ok"&&!e.correlationId){let t=typeof e.token=="string"?e.token:void 0,r=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(r,this.pendingSubscriptionReplay).catch(i=>{this.log("Socket identity update failed",i);}),t&&r&&r!=="anon"&&r!=="__admin__"?this.fetchAuthMe(t).then(i=>{this.setAuthSession({uid:r,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified});}).catch(()=>{this.setAuthSession({uid:r,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):r==="anon"&&this.authSession&&this.setAuthSession(null);}super.handleIncoming(e);}async auth(e){let t=await this.send("auth",{token:e});if(t.type==="auth_ok"){let r=t.token??e;this.authToken=r,this.userId=t.uid;let i=await this.fetchAuthMe(r).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:r,refreshToken:this.authSession?.refreshToken??null,email:i?.email??null,emailVerified:i?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new h("Authentication failed",c.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,r){try{let i=await this.requestEmailPasswordToken(e,t,r?.scope),n=await this.auth(i.access_token),s=await this.fetchAuthMe(i.access_token).catch(()=>null);return this.setAuthSession({uid:n.uid,accessToken:i.access_token,refreshToken:i.refresh_token,provider:i.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",n.uid),{...n,kind:i.kind,accessToken:i.access_token,refreshToken:i.refresh_token,authToken:i}}catch(i){let n=/invalid_email|user.not.found|no user/i.test(i?.message??"");if(r?.createIfMissing&&n){let s=await this.createUserWithEmail(e,t,{scope:r.scope,signInIfAllowed:true});if("verificationRequired"in s&&s.verificationRequired)throw new h("Email verification required before sign-in",c.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw i instanceof h?i:new h(i instanceof Error?i.message:"Sign-in with email/password failed",i.error??i.code??c.AuthenticationFailed,i)}}async signInWithEmail(e,t,r){return this.signInWithEmailAndPassword(e,t,r)}async createUserWithEmail(e,t,r){let i=await this.registerWithEmail(e,t,r);if(i.verification_required)return {kind:i.kind,verificationRequired:true,emailSent:!!i.email_sent,preview:i.preview};let n=String(i.access_token??"");if(!n)throw new h("User created but no access token returned",c.AuthenticationFailed);let s={access_token:n,refresh_token:i.refresh_token?String(i.refresh_token):null,expires_in:i.expires_in?Number(i.expires_in):null,token_type:String(i.token_type??"Bearer"),scope:i.scope?String(i.scope):null,profile:null,provider:"credentials"},o=await this.auth(n),u=await this.fetchAuthMe(n).catch(()=>null);return this.setAuthSession({uid:o.uid,accessToken:n,refreshToken:s.refresh_token,provider:"credentials",email:u?.email??e,emailVerified:u?.email_verified}),{...o,accessToken:n,refreshToken:s.refresh_token,authToken:s,verificationRequired:false,emailSent:!!i.email_sent,preview:i.preview}}async createUserWithEmailAndPassword(e,t,r){return this.createUserWithEmail(e,t,r)}async signInOrCreateWithEmail(e,t,r){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:r?.scope}),created:!1}}catch(i){if(!/invalid_email|user.not.found|no user/i.test(i?.message??""))throw i;let s=await this.createUserWithEmail(e,t,{scope:r?.scope,additionalParams:r?.additionalParams,signInIfAllowed:true});return "verificationRequired"in s&&s.verificationRequired?{...s,created:true}:{...s,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,r){return this.signInOrCreateWithEmail(e,t,r)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendEmailVerification",`${t}/auth/verify/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendEmailVerification",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send verification email",c.AuthenticationFailed),i}async verifyEmailWithCode(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("verifyEmailWithCode",`${r}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("verifyEmailWithCode",i);return i.response.ok||this.throwFetchFlareError(n,"Email verification failed",c.AuthenticationFailed),n}async confirmEmailLink(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("confirmEmailLink",`${r}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,email:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("confirmEmailLink",i);return i.response.ok||this.throwFetchFlareError(n,"Email link verification failed",c.AuthenticationFailed),n}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendAccountRecovery",`${t}/auth/recover/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("sendAccountRecovery",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send recovery email",c.AuthenticationFailed),i}async recoverAccountWithCode(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("recoverAccountWithCode",`${i}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:r,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",n);return n.response.ok||this.throwFetchFlareError(s,"Account recovery failed",c.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithToken",`${r}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),n=await this.parseJsonWithTiming("recoverAccountWithToken",i);return i.response.ok||this.throwFetchFlareError(n,"Account recovery failed",c.AuthenticationFailed),n}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4),i=t+r,n=atob(i),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),r=String(t.endpoint??"").trim(),i=String(t.keys?.p256dh??"").trim(),n=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:r,p256dh:i,auth:n});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/push/config?${t.toString()}`,i=await this.timedFetch("fetchPushSetupConfig",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),n=await this.parseJsonWithTiming("fetchPushSetupConfig",i);i.response.ok||this.throwFetchFlareError(n,"Failed to fetch push setup config",c.QueryFailed);let s=String(n.vapidPublicKey??"").trim(),o=String(n.serviceWorkerPath??"").trim();if(o.startsWith("/"))try{let l=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");l&&l!=="/"&&!o.startsWith(`${l}/`)&&(o=`${l}${o}`);}catch{}if(!s||!o)throw new h("Push setup response is missing vapidPublicKey or serviceWorkerPath",c.ParseError,n);return {vapidPublicKey:s,serviceWorkerPath:o}}async setupPushServiceWorker(){return typeof window>"u"||typeof navigator>"u"||!("serviceWorker"in navigator)?null:(this.pushServiceWorkerInitPromise||(this.pushServiceWorkerInitPromise=(async()=>{let e=await this.fetchPushSetupConfig(),t=new URL(e.serviceWorkerPath,window.location.origin);if(t.origin!==window.location.origin)throw new h("Service worker URL must be same-origin with the app",c.WriteFailed);return await navigator.serviceWorker.register(t.pathname+t.search,{scope:"/"})})().catch(e=>{throw this.log("Push service worker setup failed",e),e})),this.pushServiceWorkerInitPromise)}async requestPushPermission(){if(typeof window>"u"||typeof Notification>"u")throw new h("Push permission can only be requested in browser runtime",c.WriteFailed);let e=await Notification.requestPermission();if(e!=="granted")throw new h(`Push permission is ${e}`,c.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new h("Push token acquisition can only run in browser runtime",c.WriteFailed);if(!("serviceWorker"in navigator))throw new h("Service worker is not supported in this browser",c.WriteFailed);if(!("PushManager"in window))throw new h("Push manager is not supported in this browser",c.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),r=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,i=e.subscription??await r.pushManager.getSubscription();if(e.forceResubscribe&&i&&(await i.unsubscribe().catch(()=>{}),i=null),!i){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new h("No VAPID public key available for push subscription",c.WriteFailed);i=await r.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(i),subscription:i}}async enableBrowserPush(e={}){let{token:t,subscription:r}=await this.acquireBrowserPushToken(e);return {...await this.registerPushToken({token:t,platform:e.platform??"web",deviceId:e.deviceId,topics:e.topics,authAppId:e.authAppId}),subscription:r}}async registerPushToken(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=String(e.token??"").trim();if(!r)throw new h("Push token is required",c.WriteFailed);let i=await this.timedFetch("registerPushToken",`${t}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:r,platform:e.platform,deviceId:e.deviceId,topics:e.topics,...e.authAppId?{authAppId:e.authAppId}:{}})}),n=await this.parseJsonWithTiming("registerPushToken",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to register push token",c.WriteFailed),{registered:!!n.registered,appId:String(n.appId??this.config.appId),uid:String(n.uid??this.authSession?.uid??""),token:String(n.token??r),...typeof n.platform=="string"?{platform:n.platform}:{}}}async unregisterPushToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=String(e??"").trim();if(!i)throw new h("Push token is required",c.WriteFailed);let n=await this.timedFetch("unregisterPushToken",`${r}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"DELETE",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:i,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",n);return n.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",c.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??i),removed:!!s.removed}}async sendPushNotification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendPushNotification",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/notifications/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),i=await this.parseJsonWithTiming("sendPushNotification",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send push notification",c.WriteFailed),{sent:!!i.sent,appId:String(i.appId??this.config.appId),targetCount:Number(i.targetCount??0),successCount:Number(i.successCount??0),failureCount:Number(i.failureCount??0),invalidatedTokenCount:Number(i.invalidatedTokenCount??0),dryRun:!!i.dryRun}}async sendEmail(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("sendEmail",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/email/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),i=await this.parseJsonWithTiming("sendEmail",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to send template email",c.WriteFailed),{sent:!!i.sent,appId:String(i.appId??this.config.appId),tag:String(i.tag??e.tag??""),recipientCount:Number(i.recipientCount??0),acceptedCount:Number(i.acceptedCount??0),rejectedCount:Number(i.rejectedCount??0),...typeof i.includeVerificationLink=="boolean"?{includeVerificationLink:i.includeVerificationLink}:{},...typeof i.linkId=="string"?{linkId:i.linkId}:{},...typeof i.verifyUrl=="string"?{verifyUrl:i.verifyUrl}:{},...typeof i.messageId=="string"?{messageId:i.messageId}:{}}}async verifyEmailLink(e){let t=this.getHttpBase(),r=String(e.token??"").trim();if(!r)throw new h("Verification token is required",c.WriteFailed);let i=await this.timedFetch("verifyEmailLink",`${t}/email/link/verify?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,token:r,...e.tag?{tag:e.tag}:{},...e.email?{email:e.email}:{},...e.authAppId?{authAppId:e.authAppId}:{}})}),n=await this.parseJsonWithTiming("verifyEmailLink",i);return i.response.ok||this.throwFetchFlareError(n,"Failed to verify email link",c.WriteFailed),{verified:!!(n.verified??n.accepted),alreadyVerified:!!(n.alreadyVerified??n.alreadyAccepted),appId:String(n.appId??this.config.appId),linkId:String(n.linkId??""),email:String(n.email??""),tag:String(n.tag??e.tag??""),...typeof n.verifiedAt=="string"?{verifiedAt:n.verifiedAt}:{},...typeof n.acceptedByUid=="string"?{acceptedByUid:n.acceptedByUid}:{}}}async signIn(e,t,r){let i=typeof e?.signIn=="function",n=i?e:await this.getAuthGuard(),s=i?t:e,o=i?r:t;return n.signIn(s,o)}async signInWithGoogle(e){return this.signIn("google",e)}async signInWithGitHub(e){return this.signIn("github",e)}async signInWithFacebook(e){return this.signIn("facebook",e)}async signInWithDropbox(e){return this.signIn("dropbox",e)}async handleSignInRedirect(e,t=false){let r=typeof e?.handleRedirect=="function",i=r?e:await this.getAuthGuard(),n=r?t:typeof e=="boolean"?e:false,s=await i.handleRedirect(n);if(!s||!s.access_token||!s.provider)return null;let o=await this.exchangeProviderToken(s.provider,s.access_token),u=await this.auth(o.token),l=await this.fetchAuthMe(o.token).catch(()=>null);return this.setAuthSession({uid:u.uid,accessToken:o.token,refreshToken:s.refresh_token,provider:s.provider,email:l?.email??null,emailVerified:l?.email_verified}),{...u,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let r=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let i=await this.timedFetch("exchangeProviderToken",r,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders()},body:JSON.stringify({appId:this.config.appId,client_id:this.config.apiKey,provider:e,access_token:t})}),n=await this.parseJsonWithTiming("exchangeProviderToken",i);if(i.response.ok||this.throwFetchFlareError(n,"OAuth token exchange failed",c.AuthenticationFailed),!n?.token)throw new h("OAuth token exchange failed",c.ParseError,n);return {token:String(n.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.fetchAuthConfig();if(!e.enabled)throw new h("Authentication is disabled for this app",c.AuthenticationFailed);let t=this.getHttpBase(),r=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,i=[],n=(s,o)=>({...o,token_url:r,tokenParams:{...o.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&i.push({...Credentials({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,createUserUrl:`${t}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,createUserGrantType:"create_user"}),e.providers.anonymous?.enabled&&i.push({...Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&i.push(n("google",Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&i.push(n("github",GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&i.push(n("facebook",Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&i.push(n("dropbox",Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&i.push(n("apple",Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&i.push(n("twitter",Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),i.length===0)throw new h("No authentication providers are enabled for this app",c.AuthenticationFailed);return this.authGuard=new AuthGuard({providers:i,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("refreshAuthSession",`${t}/auth/refresh?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,...e?{refresh_token:e}:{}})}),i=await this.parseJsonWithTiming("refreshAuthSession",r);if(!r.response.ok){if(r.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(i,"Failed to refresh auth session",c.AuthenticationFailed);}let n=String(i.access_token??"");if(!n)throw new h("Refresh succeeded but no access token was returned",c.ParseError);let s=await this.fetchAuthMe(n).catch(()=>null),o={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:n,refreshToken:i.refresh_token?String(i.refresh_token):this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:s?.email??this.authSession?.email??null,emailVerified:s?.email_verified};if(s){try{delete s.kind,s.uid=s.id??s.uid,delete s.id;}catch{}this.setProfile(s);}return this.setAuthSession(o),await this.syncSocketAuth(n).catch(()=>{}),o}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("issueSsrToken",`${t}/auth/ssr/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,ttlSeconds:e})}),i=await this.parseJsonWithTiming("issueSsrToken",r);r.response.ok||this.throwFetchFlareError(i,"Failed to mint SSR token",c.AuthenticationFailed);let n=String(i.token??"");if(!n)throw new h("SSR token response is missing token",c.ParseError,i);return {token:n,token_type:String(i.token_type??"Bearer"),expires_in:Number(i.expires_in??0),uid:String(i.uid??""),role:String(i.role??"user"),...typeof i.email=="string"?{email:i.email}:{}}}async signOut(){try{if(this.authSession?.accessToken||this.authSession?.refreshToken||this.config.httpBase){let t=this.getHttpBase();await this.ensureCsrfProtection(),await this.timedFetch("signOut",`${t}/auth/logout?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,refresh_token:this.authSession?.refreshToken})}).catch(()=>{});}}finally{this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=new URLSearchParams;n.set("appId",this.config.appId),n.set("client_id",this.config.apiKey??""),n.set("grant_type","create_user"),n.set("email",e),n.set("password",t),r?.scope?.length&&n.set("scope",r.scope.join(" ")),r?.additionalParams&&n.set("additional_params",JSON.stringify(r.additionalParams));let s=await this.timedFetch("registerWithEmail",`${i}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:n.toString()}),o=await this.parseJsonWithTiming("registerWithEmail",s);return !s.response.ok&&s.response.status!==202&&this.throwFetchFlareError(o,"User creation failed",c.WriteFailed),o}async requestEmailPasswordToken(e,t,r){let i=this.getHttpBase();await this.ensureCsrfProtection();let n=new URLSearchParams;n.set("appId",this.config.appId),n.set("client_id",this.config.apiKey??""),n.set("grant_type","password"),n.set("email",e),n.set("password",t),r?.length&&n.set("scope",r.join(" "));let s=await this.timedFetch("requestEmailPasswordToken",`${i}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:n.toString()}),o=await this.parseJsonWithTiming("requestEmailPasswordToken",s);return s.response.ok||this.throwFetchFlareError(o,"Sign-in with email/password failed",c.AuthenticationFailed),{kind:String(o.kind),access_token:String(o.access_token??""),refresh_token:o.refresh_token?String(o.refresh_token):null,expires_in:o.expires_in?Number(o.expires_in):null,token_type:String(o.token_type??"Bearer"),scope:o.scope?String(o.scope):null,profile:null,provider:"credentials"}}async fetchAuthMe(e){let t=this.getHttpBase(),r=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&r.set("apiKey",this.config.apiKey);let i=`${t}/auth/me?${r.toString()}`,n=await this.timedFetch("fetchAuthMe",i,{credentials:"include",headers:{Authorization:`Bearer ${e}`,...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",n);return n.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",c.QueryFailed),s}};var H=class extends E{autoPushRegisteredIdentity;constructor(e){super(e),this.log("FlareClient initialized",e),e.pushNotifications===true&&this.enableAutoPushNotificationsAfterAuth();}enableAutoPushNotificationsAfterAuth(){let e=async()=>{let t=this.authSession,r=String(t?.uid??"").trim()||"anon",i=String(t?.accessToken??"").trim(),n=r!=="anon"&&i?r:"anon";if(this.autoPushRegisteredIdentity!==n)try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=n;}catch(s){this.log("Auto push enable failed",s);}};this.onAuthStateChanged(()=>{e().catch(()=>{});}),e().catch(()=>{});}async autoEnablePushNotifications(){await this.setupPushServiceWorker().catch(()=>{}),await this.requestPushPermission();let{token:e}=await this.acquireBrowserPushToken();await this.registerPushToken({token:e,platform:"web",topics:[this.config.appId]});}},D=H;function U(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Te(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function x(a,e){let t=e.toLowerCase();for(let[r,i]of Object.entries(a??{}))if(r.toLowerCase()===t&&typeof i=="string")return i}function Ce(a){let e=x(a,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,r]of Object.entries(a??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(r))return r.filter(i=>typeof i=="string");return []}function Se(a,e){for(let t of a){let r=t.split(";").map(u=>u.trim()),[i]=r;if(!i)continue;let n=i.indexOf("=");if(n<=0)continue;let s=decodeURIComponent(i.slice(0,n)),o=i.slice(n+1);if(s===e)return decodeURIComponent(o)}}async function Pe(a){let e=new URL("/auth/config",a.endpoint);return e.searchParams.set("appId",a.appId),a.apiKey&&e.searchParams.set("apiKey",a.apiKey),await withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:a.apiKey?{"x-flare-api-key":a.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function J(a){let e=await Pe(a),t=e?.data,r=e?.headers??{},i=x(r,"x-flare-csrf")??x(r,"x-csrf-token")??x(r,"csrf-token");if(typeof i=="string"&&i.length>0)return {csrfToken:i,...t};let n=t?.cookie?.csrfTokenName,s=n&&n.length>0?n:Te(a.appId),o=Ce(r),u=Se(o,s);if(typeof u=="string"&&u.length>0)return {csrfToken:u,...t}}function V(a,e,t){return `${encodeURIComponent(a)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function we(a){let e=a.proxyCookieName??U(a.appId),t=a.proxyCookieMaxAge??3600;return async function(i){let n=await J(a),s=n?.csrfToken,o=new Headers({"Content-Type":"application/json"});return s&&o.set("Set-Cookie",V(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...n}),{status:200,headers:o})}}function Ae(a){let e=a.proxyCookieName??U(a.appId),t=a.proxyCookieMaxAge??3600;return async function(i,n){if(i.method!=="GET"&&i.method!=="HEAD"){n.status(405).json({error:"Method not allowed"});return}let o=(await J(a))?.csrfToken;o&&n.setHeader("Set-Cookie",V(e,o,t)),n.status(200).json({csrfToken:o??null});}}function Ie(a,e,t){let r=t??U(e);if(a instanceof Request){let s=(a.headers.get("cookie")??"").split(";").map(u=>u.trim()).find(u=>u.startsWith(`${encodeURIComponent(r)}=`)||u.startsWith(`${r}=`));if(!s)return null;let o=s.indexOf("=");return o>=0?decodeURIComponent(s.slice(o+1)):null}let{cookies:i}=a;return typeof i?.get=="function"?i.get(r)?.value??null:i&&typeof i=="object"?i[r]??null:null}function ve(a,e){let t={};return a&&(t["x-flare-csrf"]=a),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var Re=a=>a==="guest"?"auth == null":a==="auth"?"auth != null":"true",Fe=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},Ee=a=>{let e=String(a??"").trim();if(!e||e==="false")return {auth:"any"};if(e==="auth != null")return {auth:"auth"};if(e==="auth == null")return {auth:"guest"};if(e==="true")return {auth:"any"};let t=e.match(/^\((auth != null|auth == null|true)\)\s*&&\s*\((.+)\)$/);if(t)return {auth:z(t[1]),condition:t[2].trim()};let r=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return r?{auth:z(r[1]),condition:r[2].trim()}:{auth:"any",condition:e}},z=a=>{let e=String(a??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},Rt=a=>{let e={};for(let t of a){let r=String(t.collection||"").trim();if(!r)continue;let i=r==="any"?"*":r,n=Fe(Re(t.auth),t.condition);e[i]={".read":t.permissions.includes("read")?n:"false",".create":t.permissions.includes("create")?n:"false",".update":t.permissions.includes("update")?n:"false",".delete":t.permissions.includes("delete")?n:"false"};}return e},Ft=a=>Object.entries(a).map(([e,t],r)=>{let i=t?.[".read"],n=t?.[".create"],s=t?.[".update"],o=t?.[".delete"],u=t?.[".write"],l=[];typeof i=="string"&&i.trim()!=="false"&&l.push("read");let g=typeof n=="string"&&n.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",f=typeof s=="string"&&s.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",d=typeof o=="string"&&o.trim()!=="false"||typeof u=="string"&&u.trim()!=="false";g&&l.push("create"),f&&l.push("update"),d&&l.push("delete");let S=Ee(i||n||s||o||u);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:S.auth,collection:e==="*"?"any":e,condition:S.condition,permissions:l}});var xe=(f=>(f.authEmailNotVerified="auth/email-not-verified",f.authEmailAlreadyVerified="auth/email-already-verified",f.authInvalidToken="auth/invalid-token",f.authUserDisabled="auth/user-disabled",f.authUserNotFound="auth/user-not-found",f.authWrongPassword="auth/wrong-password",f.authEmailAlreadyInUse="auth/email-already-in-use",f.authInvalidEmail="auth/invalid-email",f.authWeakPassword="auth/weak-password",f.authTooManyRequests="auth/too-many-requests",f.authInternalError="auth/internal-error",f))(xe||{});var Qe=(p=>(p.health="health",p.authConfig="auth_config",p.authRegistration="auth/registration",p.authRegistrationVerificationRequired="auth/registration-verification-required",p.authSession="auth/session",p.authExchange="auth/exchange",p.authLogout="auth/logout",p.authSsrBridge="auth/ssr_bridge",p.authSsrVerify="auth/ssr_verify",p.accountRecovery="account/recovery",p.emailVerification="email/verification",p.verificationDispatch="verification/dispatch",p.authProfile="auth/profile",p.adminToken="admin/token",p.documentDelete="document/delete",p.documentsDelete="documents/delete",p.documents="documents",p.document="document",p.documentCreate="document/create",p.documentUpdate="document/update",p.oauthProviderResponse="oauth_provider_response",p.success="success",p.response="response",p))(Qe||{});var k=null,w=null,Q=null,Me=a=>JSON.stringify({endpoint:a.endpoint,appId:a.appId,apiKey:a.apiKey,publicKey:a.publicKey,autoReconnect:a.autoReconnect,reconnectDelay:a.reconnectDelay,maxReconnectDelay:a.maxReconnectDelay}),Bt=a=>{let e=Me(a);if(k&&Q!==e&&(k.disconnect(),k=null,w=null,Q=null),!k){k=new D(a),Q=e;let t=typeof window<"u"&&typeof document<"u",r=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!r)&&k.connect(),t&&k.setupPushServiceWorker().catch(()=>{}),w=new Proxy(k,{get(i,n,s){if(n==="onAuthStateChange")return i.onAuthStateChanged.bind(i);if(n==="onAuthConfigLoaded")return i.onAuthConfigLoaded.bind(i);let o=Reflect.get(i,n,s);return typeof o=="function"?o.bind(i):o}});}return w??k},Ht=()=>w??k,Dt=()=>{k&&(k.disconnect(),k=null,w=null,Q=null);},Ut=D;
2
- export{B as CollectionReference,b as DocumentQueryBuilder,P as DocumentReference,ee as FlareAction,h as FlareError,xe as FlareErrors,te as FlareEvent,Qe as FlareResponseCodes,ve as buildFlareHeaders,Bt as connectApp,we as createCsrfProxy,Ae as createCsrfProxyHandler,Ut as default,Dt as disconnectFlare,Ie as extractCsrfFromRequest,Rt as flareRulesToSecurityMap,Ht as getFlare,q as parseValue,O as parseWhereCondition,Ft as securityMapToFlareRules};
1
+ import {Credentials,Anonymous,Google,GitHub,Facebook,Dropbox,Apple,Twitter,AuthGuard}from'@zuzjs/auth';export{Anonymous,Apple,AuthGuard,Credentials,Dropbox,Facebook,GitHub,Google,Providers,Twitter,setupProvider}from'@zuzjs/auth';import {uuid2,withGet,withPut,withPatch,withPost}from'@zuzjs/core';var h=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="ZuzFlareError";}};var ae={AuthenticationFailed:"AUTHENTICATION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",QueryFailed:"QUERY_FAILED",ParseError:"PARSE_ERROR"},u=ae;var ce=(c=>(c.SUBSCRIBE="subscribe",c.UNSUBSCRIBE="unsubscribe",c.WRITE="write",c.DELETE="delete",c.AUTH="auth",c.PING="ping",c.OFFLINE_SYNC="offline_sync",c.CALL="call",c.QUERY="query",c.PRESENCE_JOIN="presence_join",c.PRESENCE_LEAVE="presence_leave",c.PRESENCE_HEARTBEAT="presence_heartbeat",c))(ce||{}),ue=(c=>(c.SNAPSHOT="snapshot",c.CHANGE="change",c.ERROR="error",c.ACK="ack",c.PONG="pong",c.AUTH_OK="auth_ok",c.OFFLINE_ACK="offline_ack",c.CALL_RESPONSE="call_response",c.QUERY_RESULT="query_result",c.PRESENCE_STATE="presence_state",c.PRESENCE_JOIN="presence_join",c.PRESENCE_LEAVE="presence_leave",c))(ue||{});function V(a){let e=[];for(let[t,n]of Object.entries(a))if(typeof n=="string"){let r=n.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(r){let[,i,s]=r;e.push({field:t,op:i,value:re(s.trim())});}else e.push({field:t,op:"==",value:n});}else Array.isArray(n)?e.push({field:t,op:"in",value:n}):e.push({field:t,op:"==",value:n});return e}function re(a){if(!isNaN(Number(a)))return Number(a);if(a==="true")return true;if(a==="false")return false;if(a==="null")return null;if(a!=="undefined")return a}var I=class{constructor(e,t,n){this.client=e;this.collection=t;this.legacyId=n;}whereCondition;updateData;setData;deleteOp=false;promise;where(e){return this.whereCondition=e,this}update(e){return this.updateData=e,this}set(e){return this.setData=e,this}delete(){return this.deleteOp=true,this}getDocId(){if(this.legacyId)return this.legacyId;if(this.whereCondition&&(this.whereCondition.id||this.whereCondition._id)){let e=this.whereCondition.id??this.whereCondition._id;if(typeof e=="string")return e}throw new h('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',u.QueryFailed)}async execute(){return this._execute()}async _execute(){let e=this.getDocId();if(this.deleteOp){await this.client.send("delete",{collection:this.collection,docId:e});return}if(this.updateData){await this.client.send("write",{collection:this.collection,docId:e,data:this.updateData,merge:true});return}if(this.setData){await this.client.send("write",{collection:this.collection,docId:e,data:this.setData,merge:false});return}return this.get()}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}async get(){let e=this.getDocId(),t=uuid2(18);return new Promise((n,r)=>{let i=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(i(),n(s.data));});setTimeout(()=>{i(),r(new Error("Document fetch timeout"));},1e4);})}onSnapshot(e){let t=this.getDocId(),n=uuid2(18);return this.client.subscribe(n,this.collection,t,void 0,e)}};var z=class{constructor(e,t,n){this.client=e;this.collection=t;this.id=n;}async get(){return new I(this.client,this.collection,this.id).get()}async set(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:false});}async update(e){await this.client.send("write",{collection:this.collection,docId:this.id,data:e,merge:true});}async delete(){await this.client.send("delete",{collection:this.collection,docId:this.id});}onSnapshot(e){let t=uuid2(18),n=()=>{};return n=this.client.subscribe(t,this.collection,this.id,void 0,r=>{r.type==="snapshot"&&(e(r),n());}),n}onDocUpdated(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&(n.operation==="update"||n.operation==="replace")&&n.data&&e(n.data,n.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&n.operation==="delete"&&e(n.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18);return this.client.subscribe(t,this.collection,this.id,void 0,n=>{n.type==="change"&&e(n.data??null,n.docId,n.operation);},{skipSnapshot:true})}},O=z;var G=class a{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(n,r,i)=>{if(typeof r=="string"&&!(r in n)&&this.client.hasQueryPreset(r))return (o={})=>n.with(r,o);let s=Reflect.get(n,r,i);return typeof s=="function"?s.bind(n):s}})}sq={};promise;doc(e){return new O(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}normalizeFilterValue(e,t){return e==="in"||e==="not-in"||e==="array-contains-any"?Array.isArray(t)?t:[t]:t}normalizeFilter(e){return {...e,value:this.normalizeFilterValue(e.op,e.value)}}toQueryFilters(e){return V(e).map(t=>this.normalizeFilter(t))}appendOperatorFilter(e,t,n,r){return this.appendFilters([this.normalizeFilter({field:e,op:t,value:n})],r)}appendAndFilters(e){return this.clone({where:[...this.sq.where??[],...e]})}toOrNode(e){return {or:e}}toAndNode(e){return {and:e}}appendOrFilters(e){let t=[...this.sq.where??[]];if(t.length===0)return this.clone({where:[this.toOrNode(e)]});let n=t[0];if(t.length===1&&typeof n=="object"&&n!=null&&"or"in n){let s=n;return this.clone({where:[{or:[...s.or,...e]}]})}let i=t.length===1?t[0]:{and:t};return this.clone({where:[{or:[i,...e]}]})}appendFilters(e,t){return t==="or"?this.appendOrFilters(e):this.appendAndFilters(e)}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e){return this.appendFilters(this.toQueryFilters(e),"and")}and(e){return this.appendFilters(this.toQueryFilters(e),"and")}or(e){return this.appendFilters(this.toQueryFilters(e),"or")}in(e,t){return this.appendOperatorFilter(e,"in",t,"and")}andIn(e,t){return this.appendOperatorFilter(e,"in",t,"and")}orIn(e,t){return this.appendOperatorFilter(e,"in",t,"or")}notIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}andNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"and")}orNotIn(e,t){return this.appendOperatorFilter(e,"not-in",t,"or")}arrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}andArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"and")}orArrayContains(e,t){return this.appendOperatorFilter(e,"array-contains",t,"or")}arrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}andArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"and")}orArrayContainsAny(e,t){return this.appendOperatorFilter(e,"array-contains-any",t,"or")}some(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}andSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"and")}orSome(e,t){return this.appendOperatorFilter(e,"elem-match",t,"or")}like(e,t){return this.appendOperatorFilter(e,"like",t,"and")}andLike(e,t){return this.appendOperatorFilter(e,"like",t,"and")}orLike(e,t){return this.appendOperatorFilter(e,"like",t,"or")}notLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}andNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"and")}orNotLike(e,t){return this.appendOperatorFilter(e,"not-like",t,"or")}exists(e){return this.appendOperatorFilter(e,"exists",true,"and")}andExists(e){return this.appendOperatorFilter(e,"exists",true,"and")}orExists(e){return this.appendOperatorFilter(e,"exists",true,"or")}notExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}andNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"and")}orNotExists(e){return this.appendOperatorFilter(e,"not-exists",true,"or")}latest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"desc"}]})}oldest(){return this.clone({orderBy:[...this.sq.orderBy??[],{field:"_seq",dir:"asc"}]})}orderBy(e,t="asc"){return this.clone({orderBy:[...this.sq.orderBy??[],{field:e,dir:t}]})}limit(e){return this.clone({limit:e})}offset(e){return this.clone({offset:e})}startAt(...e){return this.clone({startAt:{values:e}})}startAfter(...e){return this.clone({startAfter:{values:e}})}endAt(...e){return this.clone({endAt:{values:e}})}endBefore(...e){return this.clone({endBefore:{values:e}})}aggregate(...e){return this.clone({aggregate:[...this.sq.aggregate??[],...e]})}count(e="count"){return this.aggregate({fn:"count",alias:e})}sum(e,t){return this.aggregate({fn:"sum",field:e,alias:t??`sum_${e}`})}avg(e,t){return this.aggregate({fn:"avg",field:e,alias:t??`avg_${e}`})}min(e,t){return this.aggregate({fn:"min",field:e,alias:t??`min_${e}`})}max(e,t){return this.aggregate({fn:"max",field:e,alias:t??`max_${e}`})}distinct(e,t){return this.aggregate({fn:"distinct",field:e,alias:t??`distinct_${e}`})}groupBy(...e){return this.clone({groupBy:{fields:e}})}having(e,t,n){return this.clone({having:[...this.sq.having??[],{field:e,op:t,value:n}]})}buildStructuredJoin(e,t){let r={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(r.where=t.where),Array.isArray(t?.orderBy)&&(r.orderBy=t.orderBy),typeof t?.limit=="number"&&(r.limit=t.limit),typeof t?.offset=="number"&&(r.offset=t.offset),t?.startAt&&(r.startAt=t.startAt),t?.startAfter&&(r.startAfter=t.startAfter),t?.endAt&&(r.endAt=t.endAt),t?.endBefore&&(r.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(r.aggregate=t.aggregate),t?.groupBy&&(r.groupBy=t.groupBy),Array.isArray(t?.having)&&(r.having=t.having),t?.vectorSearch&&(r.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(r.select=t.select),typeof t?.distinctField=="string"&&(r.distinctField=t.distinctField),Array.isArray(t?.joins)&&(r.joins=t.joins.map(i=>this.buildStructuredJoin(String(i?.collection??""),i))),r}Join(e,t){let n=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],n]})}join(e,t){if(typeof e=="string")return this.Join(e,t);let n=String(e.collection??e.from??""),r=this.buildStructuredJoin(n,e);return this.clone({joins:[...this.sq.joins??[],r]})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}async get(){return this._execute()}_isStructured(){return !!(this.sq.orderBy?.length||this.sq.aggregate?.length||this.sq.groupBy||this.sq.having?.length||this.sq.joins?.length||this.sq.vectorSearch||this.sq.distinctField||this.sq.offset||this.sq.startAt||this.sq.startAfter||this.sq.endAt||this.sq.endBefore||this.sq.select?.length)}async _execute(){return this._isStructured()?this._executeQuery():this._executeSubscribe()}async _executeQuery(){return (await this.client.send("query",{collection:this.collection,query:this.sq})).data??[]}async _executeSubscribe(){let e=uuid2(18);return new Promise((t,n)=>{let r=Object.keys(this.sq).length>0?this.sq:void 0,i=this.client.subscribe(e,this.collection,void 0,r,s=>{s.type==="snapshot"&&(i(),t(s.data));});setTimeout(()=>{i(),n(new Error("Collection fetch timeout"));},1e4);})}then(e,t){return this.promise||(this.promise=this._execute()),this.promise.then(e,t)}onSnapshot(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0,r=(()=>{});return r=this.client.subscribe(t,this.collection,void 0,n,i=>{i.type==="snapshot"&&(e(i),r());}),r}stream(e={}){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0,r=new Set,i=[],s=new Map,o=Math.max(0,Number(e.flushMs??24)),d=Math.max(1,Number(e.maxBatchSize??200)),l=e.insertAt??"end",f=typeof e.maxDocs=="number"&&e.maxDocs>0?Math.floor(e.maxDocs):void 0,y=String(e.idField??"id"),c=[],P=false,S=false,E=0,w,v=()=>{s.clear();for(let p=0;p<c.length;p+=1){let m=K(c[p]);m&&s.set(m,p);}},K=(p,m)=>{if(m)return m;if(p==null)return;if(typeof e.getId=="function"){let R=e.getId(p);if(typeof R=="string"&&R.length>0)return R}let A=p?.[y]??p?._id??p?.docId;if(typeof A=="string"&&A.length>0)return A},F=()=>{f==null||c.length<=f||(c=c.slice(0,f));},M=()=>{typeof e.sort=="function"&&(c=c.slice().sort(e.sort));},Q=(p,m)=>{E+=1;let A=c.slice(),R={reason:p,batchSize:m,version:E,ready:S};for(let B of Array.from(r))try{B(A,R);}catch{}},C=()=>{w!=null&&(clearTimeout(w),w=void 0);},g=p=>{if(p.operation==="delete"){let B=s.get(p.docId);if(B==null)return;c.splice(B,1),v();return}let m=p.data;if(m==null)return;let A=K(m,p.docId);if(!A)return;let R=s.get(A);if(typeof R=="number"){c[R]=m;return}l==="start"?c.unshift(m):c.push(m),F(),v();},N=()=>{if(P||i.length===0)return;C();let p=i.splice(0,i.length);for(let m of p)g(m);M(),v(),Q("change-batch",p.length);},q=()=>{P||w!=null||(w=setTimeout(N,o));},j=this.client.subscribe(t,this.collection,void 0,n,p=>{if(!P){if(p.type==="snapshot"){c=Array.isArray(p.data)?[...p.data]:[],S=true,C(),i.length=0,M(),F(),v(),Q("snapshot",0);return}if(i.push(p),i.length>=d){N();return}q();}}),J={subscribe(p,m=true){if(r.add(p),m){let A={reason:S?"change-batch":"snapshot",batchSize:0,version:E,ready:S};try{p(c.slice(),A);}catch{}}return ()=>{r.delete(p);}},getSnapshot(){return c.slice()},isReady(){return S},getVersion(){return E},close:()=>{P||(P=true,C(),i.length=0,r.clear(),j());},onError(p){return j.onError(p),J},onPermissionDenied(p){return j.onPermissionDenied(p),J}};return J}asStore(e={}){let t=this.stream(e);return {subscribe:n=>t.subscribe(()=>{n();},false),getSnapshot:()=>t.getSnapshot(),getServerSnapshot:()=>[],stream:t,destroy:()=>{t.close();}}}onDocAdded(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&r.operation==="insert"&&r.data!=null&&e(r.data,r.docId);},{skipSnapshot:true})}onDocUpdated(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data!=null&&e(r.data,r.docId);},{skipSnapshot:true})}onDocModified(e){return this.onDocUpdated(e)}onDocChange(e){return this.onDocUpdated(e)}onDocDeleted(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&r.operation==="delete"&&e(r.docId);},{skipSnapshot:true})}onDocChanged(e){let t=uuid2(18),n=Object.keys(this.sq).length>0?this.sq:void 0;return this.client.subscribe(t,this.collection,void 0,n,r=>{r.type==="change"&&e(r.data??null,r.docId,r.operation);},{skipSnapshot:true})}async add(e){let t=uuid2(18),n=this.doc(t);return await n.set(e),n}update(e){return new I(this.client,this.collection).update(e)}delete(){return new I(this.client,this.collection).delete()}},Y=G;async function de(a){let e=a.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,""),t=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary"),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",n.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function le(a,e){let t=await de(e),n=new TextEncoder().encode(JSON.stringify(a)),i=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,n),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(i))):Buffer.from(i).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var H=class{socket=null;reconnectInterval;maxReconnectDelay;isConnected=false;shouldReconnect=true;options;messageQueue=[];heartbeatInterval=null;connectionTimeout=null;constructor(e){this.options=e,this.reconnectInterval=e.reconnectDelay||2,this.maxReconnectDelay=e.maxReconnectDelay||60,this.log("Transport initialized",e.url);}connect(){if(this.socket){this.log("Socket already exists, skipping connection");return}this.log("Connecting to",this.options.url),this.socket=new WebSocket(this.options.url),this.connectionTimeout=setTimeout(()=>{this.isConnected||(this.log("Connection timeout"),this.socket?.close(),this.handleReconnect());},1e4),this.socket.onopen=()=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=true,this.reconnectInterval=this.options.reconnectDelay||2,this.log("Connected to server"),this.options.onOpen?.(),this.startHeartbeat(),this.flushQueue();},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data);this.options.onMessage(t);}catch(t){this.log("Parse error",t),this.options.onError?.(t);}},this.socket.onerror=e=>{this.log("WebSocket error",e),this.options.onError?.(new Error("WebSocket error"));},this.socket.onclose=e=>{this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=null),this.isConnected=false,this.socket=null,this.stopHeartbeat(),this.log("Connection closed",e.code,e.reason),this.options.onClose?.(),e.code!==1e3&&this.shouldReconnect&&this.options.autoReconnect&&this.handleReconnect();};}handleReconnect(){let e=this.reconnectInterval*1e3;this.log(`Reconnecting in ${this.reconnectInterval}s...`),setTimeout(()=>{this.reconnectInterval=Math.min(this.reconnectInterval*2,this.maxReconnectDelay),this.connect();},e);}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.isConnected&&this.send({type:"ping",id:Date.now().toString(),ts:Date.now()});},3e4);}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);}flushQueue(){for(this.log("Flushing message queue",this.messageQueue.length);this.messageQueue.length>0;){let e=this.messageQueue.shift();e&&this.send(e);}}send(e){if(this.socket&&this.socket.readyState===WebSocket.OPEN){let t=n=>{try{this.socket.send(n),this.log("Sent message",e);}catch(r){this.log("Send error",r),this.messageQueue.push(e);}};this.options.publicKey?le(e,this.options.publicKey).then(t).catch(n=>{this.log("RSA encrypt error \u2014 sending plaintext",n),t(JSON.stringify(e));}):t(JSON.stringify(e));}else this.log("Socket not ready, queueing message"),this.messageQueue.push(e);}disconnect(){this.shouldReconnect=false,this.stopHeartbeat(),this.socket&&(this.socket.close(1e3,"Client disconnect"),this.socket=null),this.isConnected=false,this.log("Disconnected");}get connected(){return this.isConnected}log(...e){this.options.debug&&console.log("[FlareTransport]",...e);}};var me={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},ne={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},U=class{transport;config;pendingAcks=new Map;subscriptions=new Map;activeSubscriptions=new Map;queryPresets=new Map;subscriptionErrorHandlers=new Map;subscriptionPermissionHandlers=new Map;subscriptionLastErrors=new Map;offlineQueue=[];currentState="disconnected";connectionListeners=[];errorListeners=[];isDebug=false;socketAuthUid="anon";pendingSubscriptionReplay=false;subscriptionReplayPromise=Promise.resolve();requestTraceSeq=0;requestTimingEnabled=true;httpInFlight=new Map;httpResponseCache=new Map;maxHttpCacheEntries=200;presenceCallbacks=new Map;presenceJoinCbs=new Map;presenceLeaveCbs=new Map;presenceHeartbeatTimer;embedder;vectorSchema=new Map;throwFetchFlareError(e,t,n){let r=e,i=typeof r?.error=="string"&&r.error.length>0?r.error:n,s=typeof r?.message=="string"&&r.message.length>0?r.message:t;throw new h(s,i,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r]=n;});else if(Array.isArray(e))for(let[n,r]of e)t[String(n)]=String(r);else for(let[n,r]of Object.entries(e))t[String(n)]=String(r);return t}redactHeaders(e){let t={...e};for(let n of Object.keys(t)){let r=n.toLowerCase();(r==="authorization"||r==="x-flare-csrf"||r==="x-csrf-token")&&(t[n]="[redacted]");}return t}stableStringify(e){if(e==null)return "";if(typeof e=="string")return e;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return e.toString();if(typeof e!="object")return String(e);if(Array.isArray(e))return `[${e.map(r=>this.stableStringify(r)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(r=>`${r}:${this.stableStringify(t[r])}`).join(",")}}`}buildHttpCacheKey(e,t,n,r,i){let o=Object.entries(n).map(([l,f])=>[l.toLowerCase(),f]).sort(([l],[f])=>l.localeCompare(f)).map(([l,f])=>`${l}:${f}`).join("|"),d=this.stableStringify(r);return `${e}|${t}|${i??""}|${o}|${d}`}shouldCacheResponse(e,t){return !!(e==="GET"||e==="POST"&&/\/auth\/refresh(?:\?|$)/.test(t))}rememberHttpResponse(e,t){if(this.httpResponseCache.set(e,t),this.httpResponseCache.size<=this.maxHttpCacheEntries)return;let n=this.httpResponseCache.keys().next().value;n&&this.httpResponseCache.delete(n);}createTimedFetchTrace(e,t,n,r,i,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:o=>{let d=o.toLowerCase();for(let[l,f]of Object.entries(e.headers))if(l.toLowerCase()===d)return String(f);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:n,networkMs:s,method:r,url:i}}logHttpTiming(...e){this.requestTimingEnabled&&this.log("[FlareClient][http]",...e);}mergeHeaders(e,t){if(!e)return t;if(e instanceof Headers){let n=new Headers(e);for(let[r,i]of Object.entries(t))n.set(r,i);return n}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(me[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(ne[t]?ne[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(r=>this.normalizeOutboundData(r));if(!e||typeof e!="object")return e;let t=e,n={};for(let[r,i]of Object.entries(t))n[this.toWireField(r)]=this.normalizeOutboundData(i);return n}normalizeInboundData(e){if(Array.isArray(e))return e.map(r=>this.normalizeInboundData(r));if(!e||typeof e!="object")return e;let t=e,n={};for(let[r,i]of Object.entries(t))n[this.fromWireField(r)]=this.normalizeInboundData(i);return n}normalizeOutboundAnyFilter(e){return Array.isArray(e.or)?{...e,or:e.or.map(t=>this.normalizeOutboundAnyFilter(t))}:Array.isArray(e.and)?{...e,and:e.and.map(t=>this.normalizeOutboundAnyFilter(t))}:typeof e.field=="string"?{...e,field:this.toWireField(e.field)}:{...e}}normalizeOutboundQuery(e){if(!e)return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.field=="string")return this.normalizeOutboundAnyFilter(e);if(Array.isArray(e))return e.map(i=>this.normalizeOutboundAnyFilter(i));if(typeof e!="object")return e;let t=e,n={...t},r=i=>{let s={...i};return s.localField=this.toWireField(String(i?.localField??"")),s.foreignField=this.toWireField(String(i?.foreignField??"")),Array.isArray(i.where)&&(s.where=i.where.map(o=>this.normalizeOutboundAnyFilter(o))),Array.isArray(i.orderBy)&&(s.orderBy=i.orderBy.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),i.groupBy&&typeof i.groupBy=="object"&&Array.isArray(i.groupBy.fields)&&(s.groupBy={...i.groupBy,fields:i.groupBy.fields.map(o=>this.toWireField(String(o??"")))}),Array.isArray(i.having)&&(s.having=i.having.map(o=>({...o,field:this.toWireField(String(o?.field??""))}))),Array.isArray(i.select)&&(s.select=i.select.map(o=>this.toWireField(String(o??"")))),typeof i.distinctField=="string"&&(s.distinctField=this.toWireField(i.distinctField)),i.vectorSearch&&typeof i.vectorSearch=="object"&&(s.vectorSearch={...i.vectorSearch,field:this.toWireField(String(i.vectorSearch.field??""))}),Array.isArray(i.joins)&&(s.joins=i.joins.map(o=>r(o))),s};return Array.isArray(t.where)&&(n.where=t.where.map(i=>this.normalizeOutboundAnyFilter(i))),Array.isArray(t.orderBy)&&(n.orderBy=t.orderBy.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(n.groupBy={...t.groupBy,fields:t.groupBy.fields.map(i=>this.toWireField(String(i??"")))}),Array.isArray(t.having)&&(n.having=t.having.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),Array.isArray(t.select)&&(n.select=t.select.map(i=>this.toWireField(String(i??"")))),typeof t.distinctField=="string"&&(n.distinctField=this.toWireField(t.distinctField)),t.vectorSearch&&typeof t.vectorSearch=="object"&&(n.vectorSearch={...t.vectorSearch,field:this.toWireField(String(t.vectorSearch.field??""))}),Array.isArray(t.joins)&&(n.joins=t.joins.map(i=>r(i))),n}async timedFetch(e,t,n){let r=++this.requestTraceSeq,i=this.nowMs(),s=String(n?.method??"GET").toUpperCase(),o=this.normalizeHeaders(n?.headers),d=this.redactHeaders(o),l=n?.body,f=this.buildHttpCacheKey(s,t,o,l,n?.credentials),y=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${r} ${e} start`,{method:s,url:t,headers:d,hasBody:!!n?.body});try{if(y){let C=this.httpResponseCache.get(f);if(C)return this.logHttpTiming(`#${r} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(C,r,i,s,t,0)}let c=this.httpInFlight.get(f);if(c){let C=await c,g=this.nowMs()-i;return this.logHttpTiming(`#${r} ${e} deduped`,{method:s,url:t,networkMs:Number(g.toFixed(2))}),this.createTimedFetchTrace(C,r,i,s,t,g)}let P=this.mergeHeaders(n?.headers,{"x-flare-request-id":String(r)}),S=this.normalizeHeaders(P),E=this.redactHeaders(S),w={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:S,withCredentials:n?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${r} ${e} request`,{method:s,url:t,headers:E,hasBody:!!n?.body});let v=s.toUpperCase(),F=(async()=>{let C=v==="GET"?await withGet(t,w):v==="PUT"?await withPut(t,l,w):v==="PATCH"?await withPatch(t,l,w):await withPost(t,l,w),g={status:Number(C?.status??0),headers:Object.fromEntries(Object.entries(C?.headers??{}).map(([N,q])=>[N,String(q)])),data:C?.data??{}};return y&&this.rememberHttpResponse(f,g),g})();this.httpInFlight.set(f,F);let M=await F.finally(()=>{this.httpInFlight.delete(f);}),Q=this.nowMs()-i;return this.logHttpTiming(`#${r} ${e} response`,{status:M.status,networkMs:Number(Q.toFixed(2))}),this.createTimedFetchTrace(M,r,i,s,t,Q)}catch(c){let P=this.nowMs()-i;throw this.logHttpTiming(`#${r} ${e} failed`,{networkMs:Number(P.toFixed(2)),message:c?.message??String(c)}),c}}async parseJsonWithTiming(e,t){let n=this.nowMs(),r=await t.response.json().catch(()=>({})),i=this.nowMs()-n,s=this.nowMs()-t.startedAtMs;return this.logHttpTiming(`#${t.requestId} ${e} complete`,{method:t.method,url:t.url,status:t.response.status,networkMs:Number(t.networkMs.toFixed(2)),parseMs:Number(i.toFixed(2)),totalMs:Number(s.toFixed(2))}),r}getHttpBase(){if(this.config.httpBase)return this.config.httpBase.replace(/\/$/,"");let e=new URL(this.config.endpoint);return `${e.protocol}//${e.host}`}log(...e){this.isDebug&&console.log("[FlareClient]",...e);}constructor(e){this.config={autoReconnect:true,reconnectDelay:2,maxReconnectDelay:60,debug:false,connectionTimeout:1e4,...e},this.isDebug=this.config.debug||false,this.requestTimingEnabled=this.config.requestTiming??true;let{hostname:t,port:n,protocol:r}=new URL(this.config.endpoint),i=r==="https:",d=`${i?"wss":"ws"}://${t}:${n||(i?"443":"80")}/?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new H({url:d,publicKey:this.config.publicKey,autoReconnect:this.config.autoReconnect,reconnectDelay:this.config.reconnectDelay,maxReconnectDelay:this.config.maxReconnectDelay,onMessage:l=>this.handleIncoming(l),onOpen:()=>this.onConnected(),onClose:()=>this.onDisconnected(),onError:l=>this.handleTransportError(l),debug:this.isDebug});}connect(){this.setState("connecting"),this.transport.connect();}disconnect(){this.transport.disconnect(),this.setState("disconnected");}get connectionState(){return this.currentState}get isConnected(){return this.currentState==="connected"}onConnectionStateChange(e){return this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);}}onError(e){return this.errorListeners.push(e),()=>{this.errorListeners=this.errorListeners.filter(t=>t!==e);}}collection(e){return new Y(this,e)}registerQueryPreset(e,t){let n=String(e??"").trim();if(!n)throw new h("Preset name is required",u.QueryFailed);if(typeof t!="function")throw new h(`Query preset "${n}" handler must be a function`,u.QueryFailed);return this.queryPresets.set(n,t),this}registerQueryPresets(e){for(let[t,n]of Object.entries(e??{}))this.registerQueryPreset(t,n);return this}hasQueryPreset(e){return this.queryPresets.has(String(e??"").trim())}applyQueryPreset(e,t,n={}){let r=String(t??"").trim(),i=this.queryPresets.get(r);if(!i)throw new h(`Unknown query preset "${r}"`,u.QueryFailed);let s=i(e,n??{});if(!s||typeof s.get!="function")throw new h(`Query preset "${r}" must return a CollectionReference`,u.QueryFailed);return s}doc(e,t){return t!==void 0?new O(this,e,t):new I(this,e)}async ping(){let e=Date.now();return await this.send("ping",{}),Date.now()-e}async call(e,t={}){let n=await this.send("call",{topic:e,payload:t});if(!n.success)throw new h(n.error??`CALL "${e}" failed`,u.QueryFailed);return n.result}async query(e,t={}){return (await this.send("query",{collection:e,query:t})).data??[]}setEmbedder(e){this.embedder=e;}markVectorField(e,t,n={dimensions:1536}){this.vectorSchema.has(e)||this.vectorSchema.set(e,new Map),this.vectorSchema.get(e).set(t,n);}async embedVectorFields(e,t){let n=this.vectorSchema.get(e);if(!n)return t;let r={...t};for(let[i,s]of n){let o=r[i];if(typeof o=="string"){let d=s.embed??this.embedder;if(!d){this.log(`[vector] No embedder for field "${i}" \u2014 storing raw text`);continue}r[i]=await d(o);}}return r}async joinPresence(e,t){return await this.send("presence_join",{room:e,meta:t}),this._startPresenceHeartbeat(e,t),()=>this.leavePresence(e)}async leavePresence(e){await this.send("presence_leave",{room:e}),this._stopPresenceHeartbeat();}onPresenceState(e,t){return this.presenceCallbacks.has(e)||this.presenceCallbacks.set(e,[]),this.presenceCallbacks.get(e).push(t),()=>{let n=this.presenceCallbacks.get(e)??[];this.presenceCallbacks.set(e,n.filter(r=>r!==t));}}onPresenceJoin(e,t){return this.presenceJoinCbs.has(e)||this.presenceJoinCbs.set(e,[]),this.presenceJoinCbs.get(e).push(t),()=>{let n=this.presenceJoinCbs.get(e)??[];this.presenceJoinCbs.set(e,n.filter(r=>r!==t));}}onPresenceLeave(e,t){return this.presenceLeaveCbs.has(e)||this.presenceLeaveCbs.set(e,[]),this.presenceLeaveCbs.get(e).push(t),()=>{let n=this.presenceLeaveCbs.get(e)??[];this.presenceLeaveCbs.set(e,n.filter(r=>r!==t));}}_startPresenceHeartbeat(e,t){this.presenceHeartbeatTimer||(this.presenceHeartbeatTimer=setInterval(()=>{this.isConnected&&this.send("presence_heartbeat",{meta:t}).catch(()=>{});},2e4));}_stopPresenceHeartbeat(){this.presenceHeartbeatTimer&&(clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=void 0);}async syncOffline(){if(this.offlineQueue.length===0)return;this.log("Syncing offline operations",this.offlineQueue.length);let e=[...this.offlineQueue];this.offlineQueue.length=0;let t=await this.send("offline_sync",{operations:e});t.conflicts&&t.conflicts.length>0&&(this.log("Offline sync conflicts",t.conflicts),t.conflicts.forEach(n=>{let r=e.find(i=>i.id===n.operationId);r&&this.offlineQueue.push(r);}));}async beforeActivateSubscription(e){}async activateSubscription(e){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}await this.beforeActivateSubscription(e),this.subscriptions.set(e.liveId,e.callback);try{let t=await this.send("subscribe",{collection:e.collection,docId:e.docId,query:e.query,skipSnapshot:e.options.skipSnapshot});if(!this.activeSubscriptions.has(e.baseId)){this.subscriptions.delete(e.liveId);return}t.subscriptionId&&t.subscriptionId!==e.liveId&&(this.subscriptions.delete(e.liveId),e.liveId=t.subscriptionId,this.subscriptions.set(e.liveId,e.callback),this.log("Subscription remapped",e.baseId,"\u2192",e.liveId));}catch(t){this.subscriptions.delete(e.liveId),this.pendingSubscriptionReplay=true;let n=this.toSubscriptionError(t);this.emitSubscriptionError(e.baseId,n),this.log("Subscription failed",t);}}toSubscriptionError(e){let t=e instanceof Error?e.message:String(e??"Unknown subscription error"),n=t.match(/^\[([^\]]+)\]\s*(.*)$/),r=n?.[1],i=(n?.[2]??t).trim()||t,s=r===u.PermissionDenied||t.includes(u.PermissionDenied);return {code:r,message:i,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let n=this.subscriptionErrorHandlers.get(e);if(n)for(let r of n)try{r(t);}catch(i){this.log("Subscription error callback failed",i);}if(t.permissionDenied){let r=this.subscriptionPermissionHandlers.get(e);if(r)for(let i of r)try{i(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let n=t.liveId;this.subscriptions.delete(n),t.liveId=t.baseId,n&&await this.send("unsubscribe",{subscriptionId:n}).catch(()=>{}),await this.activateSubscription(t);}}).catch(t=>{this.pendingSubscriptionReplay=true,this.log("Subscription replay failed",t);}),await this.subscriptionReplayPromise;}subscribe(e,t,n,r,i,s={}){this.log("Creating subscription",e,t,n);let o={baseId:e,liveId:e,collection:t,docId:n,query:r,callback:i,options:s};this.activeSubscriptions.set(e,o),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(o).catch(f=>{this.log("Subscription activation failed",f);});let d=()=>{let y=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",y),this.activeSubscriptions.delete(e),this.subscriptions.delete(y),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:y}).catch(c=>this.log("Unsubscribe failed",c));},l=d;return l.unsubscribe=d,l.onError=f=>{this.subscriptionErrorHandlers.get(e)?.add(f);let y=this.subscriptionLastErrors.get(e);if(y)try{f(y);}catch(c){this.log("Subscription error callback failed",c);}return l},l.onPermissionDenied=f=>{this.subscriptionPermissionHandlers.get(e)?.add(f);let y=this.subscriptionLastErrors.get(e);if(y?.permissionDenied)try{f(y);}catch(c){this.log("Subscription permission callback failed",c);}return l},l.catch=f=>l.onError(f),l}async send(e,t){if(e==="write"&&t.collection&&t.data){let n=await this.embedVectorFields(t.collection,t.data);t={...t,data:this.normalizeOutboundData(n)};}return (e==="subscribe"||e==="query")&&t?.query&&(t={...t,query:this.normalizeOutboundQuery(t.query)}),new Promise((n,r)=>{let i=uuid2(18),s={id:i,type:e,ts:Date.now(),...t};this.pendingAcks.set(i,o=>{o.type==="error"?r(new Error(`[${o.code}] ${o.message}`)):n(o);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),r(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(i)&&(this.pendingAcks.delete(i),r(new Error("Request timeout")));},this.config.connectionTimeout);})}handleTransportError(e){this.log("Transport error",e),this.errorListeners.forEach(t=>{try{t(e);}catch(n){this.log("Error listener error",n);}});}onConnected(){this.setState("connected"),this.log("Connected to FlareServer"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.offlineQueue.length>0&&this.syncOffline().catch(e=>{this.log("Offline sync failed",e);});}onDisconnected(){this.currentState!=="disconnected"&&this.setState("reconnecting"),this.activeSubscriptions.size>0&&(this.pendingSubscriptionReplay=true),this.log("Disconnected from FlareServer");}setState(e){this.currentState!==e&&(this.currentState=e,this.log("Connection state changed",e),this.connectionListeners.forEach(t=>{try{t(e);}catch(n){this.log("Connection listener error",n);}}));}handleIncoming(e){if(this.log("Received message",e.type,e),e.type==="query_result"&&Array.isArray(e.data)&&(e={...e,data:this.normalizeInboundData(e.data)}),e.type==="ack"||e.type==="pong"||e.type==="auth_ok"||e.type==="call_response"||e.type==="query_result"){let t=this.pendingAcks.get(e.correlationId||e.id);t&&(t(e),this.pendingAcks.delete(e.correlationId||e.id));return}if(e.type==="error"){this.log("Server error",e.code,e.message);let t=new Error(`[${e.code}] ${e.message}`);this.errorListeners.forEach(r=>{try{r(t);}catch(i){this.log("Error listener error",i);}});let n=Array.from(this.activeSubscriptions.values()).find(r=>r.liveId===e.correlationId||r.baseId===e.correlationId);if(n&&this.emitSubscriptionError(n.baseId,{code:typeof e.code=="string"?e.code:void 0,message:String(e.message??"Subscription error"),permissionDenied:e.code===u.PermissionDenied,raw:e}),e.correlationId){let r=this.pendingAcks.get(e.correlationId);r&&(r(e),this.pendingAcks.delete(e.correlationId));}return}if(e.type==="presence_state"){(this.presenceCallbacks.get(e.room)??[]).forEach(n=>{try{n(e.members);}catch{}});return}if(e.type==="presence_join"){(this.presenceJoinCbs.get(e.room)??[]).forEach(n=>{try{n(e);}catch{}});return}if(e.type==="presence_leave"){(this.presenceLeaveCbs.get(e.room)??[]).forEach(n=>{try{n(e.uid);}catch{}});return}if(e.type==="snapshot"){let t=this.subscriptions.get(e.subscriptionId);if(t){let n=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),r={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(n)?n:[]};try{t(r);}catch(i){this.log("Subscription callback error",i);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let n={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:e.operation==="delete"?null:this.normalizeInboundData(e.data)};try{t(n);}catch(r){this.log("Subscription callback error",r);}}}}};var L=class extends U{authToken;userId;authGuard;authConfig;csrfToken;csrfInitPromise;csrfBootstrapAttempted=false;socketAuthSyncPromise;pushServiceWorkerInitPromise;authSession=null;authStateListeners=[];authConfigListeners=[];currentProfile=void 0;getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return this.getCookieValue(this.getCsrfCookieName())??this.csrfToken??null}getCookieValue(e){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`)||r.startsWith(`${encodeURIComponent(e)}=`));if(!t)return null;let n=t.indexOf("=");return n>=0?decodeURIComponent(t.slice(n+1)):null}extractCsrfToken(e,t){let n=e,r=typeof n?.csrfToken=="string"?String(n.csrfToken):typeof n?.csrf_token=="string"?String(n.csrf_token):void 0;if(r)return r;if(!t)return;let i=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof i=="string"&&i.length>0?i:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}setCsrfToken(e){this.csrfToken=e,this.csrfBootstrapAttempted=true,this.log("CSRF token injected",{length:e.length});}async ensureCsrfProtection(){if(this.getCsrfToken()){this.csrfBootstrapAttempted=true;return}if(this.config.httpBase){this.csrfBootstrapAttempted=true;return}this.csrfBootstrapAttempted||(this.csrfInitPromise||(this.csrfBootstrapAttempted=true,this.csrfInitPromise=this.loadAuthConfig().then(()=>{}).finally(()=>{this.csrfInitPromise=void 0;})),await this.csrfInitPromise,this.getCsrfToken()||this.log("CSRF token unavailable after auth config load",{hasAuthConfig:!!this.authConfig,csrfCookieName:this.getCsrfCookieName()}));}async loadAuthConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let n=`${e}/auth/config?${t.toString()}`,r=await this.timedFetch("loadAuthConfig",n,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("loadAuthConfig",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to load auth config",u.QueryFailed),this.authConfig=i,this.csrfToken=this.extractCsrfToken(i,r.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(o){this.log("Auth config listener error",o);}}),this.authConfig}async fetchAuthConfig(){return this.authConfig?this.authConfig:this.loadAuthConfig()}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}setProfile(e){this.currentProfile=e;}setAuthSession(e){this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid):(this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear());let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;this.authStateListeners.forEach(n=>{try{n(t);}catch(r){this.log("Auth state listener error",r);}});}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.authSession?{...this.authSession,...this.currentProfile??{}}:null;try{e(t);}catch(n){this.log("Auth state listener error during initialization",n);}return ()=>{this.authStateListeners=this.authStateListeners.filter(n=>n!==e);}}onAuthStateChange(e){return this.onAuthStateChanged(e)}get currentUser(){return this.currentProfile}getCurrentUser(){return this.currentUser}async syncSocketAuth(e){if(!this.isConnected)return;let t=await this.send("auth",e?{token:e}:{});if(t.type!=="auth_ok")throw new h("Socket auth sync failed",u.AuthenticationFailed);if(!e||t.uid==="anon"){this.authToken=void 0,this.userId=void 0,await this.updateSocketIdentity("anon");return}this.authToken=typeof t.token=="string"?t.token:e,this.userId=typeof t.uid=="string"?t.uid:this.userId,await this.updateSocketIdentity(typeof t.uid=="string"?t.uid:this.userId);}async updateSocketIdentity(e,t=false){let n=typeof e=="string"&&e.length>0?e:"anon",r=n!==this.socketAuthUid;this.socketAuthUid=n,(r||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async beforeActivateSubscription(e){if(!this.isConnected)return;let t=this.authSession;!t?.accessToken||!t.uid||this.socketAuthUid!==t.uid&&(this.socketAuthSyncPromise||(this.socketAuthSyncPromise=this.syncSocketAuth(t.accessToken).catch(n=>{throw this.log("Socket auth sync failed before subscribe",n),n}).finally(()=>{this.socketAuthSyncPromise=void 0;})),await this.socketAuthSyncPromise);}onConnected(){super.onConnected(),this.authSession?.accessToken&&this.syncSocketAuth(this.authSession.accessToken).catch(e=>{this.log("Socket auth sync failed after connect",e);});}handleIncoming(e){if(e.type==="auth_ok"&&!e.correlationId){let t=typeof e.token=="string"?e.token:void 0,n=typeof e.uid=="string"?e.uid:void 0;this.updateSocketIdentity(n,this.pendingSubscriptionReplay).catch(r=>{this.log("Socket identity update failed",r);}),t&&n&&n!=="anon"&&n!=="__admin__"?this.fetchAuthMe(t).then(r=>{this.setAuthSession({uid:n,accessToken:t,refreshToken:this.authSession?.refreshToken??null,email:r?.email??null,emailVerified:r?.email_verified});}).catch(()=>{this.setAuthSession({uid:n,accessToken:t,refreshToken:this.authSession?.refreshToken??null});}):n==="anon"&&this.authSession&&this.setAuthSession(null);}super.handleIncoming(e);}async auth(e){let t=await this.send("auth",{token:e});if(t.type==="auth_ok"){let n=t.token??e;this.authToken=n,this.userId=t.uid;let r=await this.fetchAuthMe(n).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:n,refreshToken:this.authSession?.refreshToken??null,email:r?.email??null,emailVerified:r?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new h("Authentication failed",u.AuthenticationFailed)}async signInWithEmailAndPassword(e,t,n){try{let r=await this.requestEmailPasswordToken(e,t,n?.scope),i=await this.auth(r.access_token),s=await this.fetchAuthMe(r.access_token).catch(()=>null);return this.setAuthSession({uid:i.uid,accessToken:r.access_token,refreshToken:r.refresh_token,provider:r.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",i.uid),{...i,kind:r.kind,accessToken:r.access_token,refreshToken:r.refresh_token,authToken:r}}catch(r){let i=/invalid_email|user.not.found|no user/i.test(r?.message??"");if(n?.createIfMissing&&i){let s=await this.createUserWithEmail(e,t,{scope:n.scope,signInIfAllowed:true});if("verificationRequired"in s&&s.verificationRequired)throw new h("Email verification required before sign-in",u.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw r instanceof h?r:new h(r instanceof Error?r.message:"Sign-in with email/password failed",r.error??r.code??u.AuthenticationFailed,r)}}async signInWithEmail(e,t,n){return this.signInWithEmailAndPassword(e,t,n)}async createUserWithEmail(e,t,n){let r=await this.registerWithEmail(e,t,n);if(r.verification_required)return {kind:r.kind,verificationRequired:true,emailSent:!!r.email_sent,preview:r.preview};let i=String(r.access_token??"");if(!i)throw new h("User created but no access token returned",u.AuthenticationFailed);let s={access_token:i,refresh_token:r.refresh_token?String(r.refresh_token):null,expires_in:r.expires_in?Number(r.expires_in):null,token_type:String(r.token_type??"Bearer"),scope:r.scope?String(r.scope):null,profile:null,provider:"credentials"},o=await this.auth(i),d=await this.fetchAuthMe(i).catch(()=>null);return this.setAuthSession({uid:o.uid,accessToken:i,refreshToken:s.refresh_token,provider:"credentials",email:d?.email??e,emailVerified:d?.email_verified}),{...o,accessToken:i,refreshToken:s.refresh_token,authToken:s,verificationRequired:false,emailSent:!!r.email_sent,preview:r.preview}}async createUserWithEmailAndPassword(e,t,n){return this.createUserWithEmail(e,t,n)}async signInOrCreateWithEmail(e,t,n){try{return {...await this.signInWithEmailAndPassword(e,t,{scope:n?.scope}),created:!1}}catch(r){if(!/invalid_email|user.not.found|no user/i.test(r?.message??""))throw r;let s=await this.createUserWithEmail(e,t,{scope:n?.scope,additionalParams:n?.additionalParams,signInIfAllowed:true});return "verificationRequired"in s&&s.verificationRequired?{...s,created:true}:{...s,created:true}}}async signInOrCreateWithEmailAndPassword(e,t,n){return this.signInOrCreateWithEmail(e,t,n)}async sendEmailVerification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendEmailVerification",`${t}/auth/verify/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),r=await this.parseJsonWithTiming("sendEmailVerification",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send verification email",u.AuthenticationFailed),r}async verifyEmailWithCode(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("verifyEmailWithCode",`${n}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("verifyEmailWithCode",r);return r.response.ok||this.throwFetchFlareError(i,"Email verification failed",u.AuthenticationFailed),i}async confirmEmailLink(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("confirmEmailLink",`${n}/auth/verify/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,email:t,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("confirmEmailLink",r);return r.response.ok||this.throwFetchFlareError(i,"Email link verification failed",u.AuthenticationFailed),i}async sendAccountRecovery(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendAccountRecovery",`${t}/auth/recover/send?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,appId:this.config.appId,apiKey:this.config.apiKey})}),r=await this.parseJsonWithTiming("sendAccountRecovery",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send recovery email",u.AuthenticationFailed),r}async recoverAccountWithCode(e,t,n){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithCode",`${r}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:n,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",i);return i.response.ok||this.throwFetchFlareError(s,"Account recovery failed",u.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=await this.timedFetch("recoverAccountWithToken",`${n}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({token:e,newPassword:t,appId:this.config.appId,apiKey:this.config.apiKey})}),i=await this.parseJsonWithTiming("recoverAccountWithToken",r);return r.response.ok||this.throwFetchFlareError(i,"Account recovery failed",u.AuthenticationFailed),i}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4),r=t+n,i=atob(r),s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=1)s[o]=i.charCodeAt(o);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),n=String(t.endpoint??"").trim(),r=String(t.keys?.p256dh??"").trim(),i=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:n,p256dh:r,auth:i});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let n=`${e}/push/config?${t.toString()}`,r=await this.timedFetch("fetchPushSetupConfig",n,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("fetchPushSetupConfig",r);r.response.ok||this.throwFetchFlareError(i,"Failed to fetch push setup config",u.QueryFailed);let s=String(i.vapidPublicKey??"").trim(),o=String(i.serviceWorkerPath??"").trim();if(o.startsWith("/"))try{let l=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");l&&l!=="/"&&!o.startsWith(`${l}/`)&&(o=`${l}${o}`);}catch{}if(!s||!o)throw new h("Push setup response is missing vapidPublicKey or serviceWorkerPath",u.ParseError,i);return {vapidPublicKey:s,serviceWorkerPath:o}}async setupPushServiceWorker(){return typeof window>"u"||typeof navigator>"u"||!("serviceWorker"in navigator)?null:(this.pushServiceWorkerInitPromise||(this.pushServiceWorkerInitPromise=(async()=>{let e=await this.fetchPushSetupConfig(),t=new URL(e.serviceWorkerPath,window.location.origin);if(t.origin!==window.location.origin)throw new h("Service worker URL must be same-origin with the app",u.WriteFailed);return await navigator.serviceWorker.register(t.pathname+t.search,{scope:"/"})})().catch(e=>{throw this.log("Push service worker setup failed",e),e})),this.pushServiceWorkerInitPromise)}async requestPushPermission(){if(typeof window>"u"||typeof Notification>"u")throw new h("Push permission can only be requested in browser runtime",u.WriteFailed);let e=await Notification.requestPermission();if(e!=="granted")throw new h(`Push permission is ${e}`,u.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new h("Push token acquisition can only run in browser runtime",u.WriteFailed);if(!("serviceWorker"in navigator))throw new h("Service worker is not supported in this browser",u.WriteFailed);if(!("PushManager"in window))throw new h("Push manager is not supported in this browser",u.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),n=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,r=e.subscription??await n.pushManager.getSubscription();if(e.forceResubscribe&&r&&(await r.unsubscribe().catch(()=>{}),r=null),!r){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new h("No VAPID public key available for push subscription",u.WriteFailed);r=await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(r),subscription:r}}async enableBrowserPush(e={}){let{token:t,subscription:n}=await this.acquireBrowserPushToken(e);return {...await this.registerPushToken({token:t,platform:e.platform??"web",deviceId:e.deviceId,topics:e.topics,authAppId:e.authAppId}),subscription:n}}async registerPushToken(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=String(e.token??"").trim();if(!n)throw new h("Push token is required",u.WriteFailed);let r=await this.timedFetch("registerPushToken",`${t}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:n,platform:e.platform,deviceId:e.deviceId,topics:e.topics,...e.authAppId?{authAppId:e.authAppId}:{}})}),i=await this.parseJsonWithTiming("registerPushToken",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to register push token",u.WriteFailed),{registered:!!i.registered,appId:String(i.appId??this.config.appId),uid:String(i.uid??this.authSession?.uid??""),token:String(i.token??n),...typeof i.platform=="string"?{platform:i.platform}:{}}}async unregisterPushToken(e,t){let n=this.getHttpBase();await this.ensureCsrfProtection();let r=String(e??"").trim();if(!r)throw new h("Push token is required",u.WriteFailed);let i=await this.timedFetch("unregisterPushToken",`${n}/notify/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"DELETE",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,token:r,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",u.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??r),removed:!!s.removed}}async sendPushNotification(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendPushNotification",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/notifications/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),r=await this.parseJsonWithTiming("sendPushNotification",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send push notification",u.WriteFailed),{sent:!!r.sent,appId:String(r.appId??this.config.appId),targetCount:Number(r.targetCount??0),successCount:Number(r.successCount??0),failureCount:Number(r.failureCount??0),invalidatedTokenCount:Number(r.invalidatedTokenCount??0),dryRun:!!r.dryRun}}async sendEmail(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("sendEmail",`${t}/system/apps/${encodeURIComponent(this.config.appId)}/email/send`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({...e,appId:this.config.appId})}),r=await this.parseJsonWithTiming("sendEmail",n);return n.response.ok||this.throwFetchFlareError(r,"Failed to send template email",u.WriteFailed),{sent:!!r.sent,appId:String(r.appId??this.config.appId),tag:String(r.tag??e.tag??""),recipientCount:Number(r.recipientCount??0),acceptedCount:Number(r.acceptedCount??0),rejectedCount:Number(r.rejectedCount??0),...typeof r.includeVerificationLink=="boolean"?{includeVerificationLink:r.includeVerificationLink}:{},...typeof r.linkId=="string"?{linkId:r.linkId}:{},...typeof r.verifyUrl=="string"?{verifyUrl:r.verifyUrl}:{},...typeof r.messageId=="string"?{messageId:r.messageId}:{}}}async verifyEmailLink(e){let t=this.getHttpBase(),n=String(e.token??"").trim();if(!n)throw new h("Verification token is required",u.WriteFailed);let r=await this.timedFetch("verifyEmailLink",`${t}/email/link/verify?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{},...e.authAppId?{"x-flare-auth-app-id":e.authAppId}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,token:n,...e.tag?{tag:e.tag}:{},...e.email?{email:e.email}:{},...e.authAppId?{authAppId:e.authAppId}:{}})}),i=await this.parseJsonWithTiming("verifyEmailLink",r);return r.response.ok||this.throwFetchFlareError(i,"Failed to verify email link",u.WriteFailed),{verified:!!(i.verified??i.accepted),alreadyVerified:!!(i.alreadyVerified??i.alreadyAccepted),appId:String(i.appId??this.config.appId),linkId:String(i.linkId??""),email:String(i.email??""),tag:String(i.tag??e.tag??""),...typeof i.verifiedAt=="string"?{verifiedAt:i.verifiedAt}:{},...typeof i.acceptedByUid=="string"?{acceptedByUid:i.acceptedByUid}:{}}}async signIn(e,t,n){let r=typeof e?.signIn=="function",i=r?e:await this.getAuthGuard(),s=r?t:e,o=r?n:t;return i.signIn(s,o)}async signInWithGoogle(e){return this.signIn("google",e)}async signInWithGitHub(e){return this.signIn("github",e)}async signInWithFacebook(e){return this.signIn("facebook",e)}async signInWithDropbox(e){return this.signIn("dropbox",e)}async handleSignInRedirect(e,t=false){let n=typeof e?.handleRedirect=="function",r=n?e:await this.getAuthGuard(),i=n?t:typeof e=="boolean"?e:false,s=await r.handleRedirect(i);if(!s||!s.access_token||!s.provider)return null;let o=await this.exchangeProviderToken(s.provider,s.access_token),d=await this.auth(o.token),l=await this.fetchAuthMe(o.token).catch(()=>null);return this.setAuthSession({uid:d.uid,accessToken:o.token,refreshToken:s.refresh_token,provider:s.provider,email:l?.email??null,emailVerified:l?.email_verified}),{...d,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let n=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let r=await this.timedFetch("exchangeProviderToken",n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders()},body:JSON.stringify({appId:this.config.appId,client_id:this.config.apiKey,provider:e,access_token:t})}),i=await this.parseJsonWithTiming("exchangeProviderToken",r);if(r.response.ok||this.throwFetchFlareError(i,"OAuth token exchange failed",u.AuthenticationFailed),!i?.token)throw new h("OAuth token exchange failed",u.ParseError,i);return {token:String(i.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.fetchAuthConfig();if(!e.enabled)throw new h("Authentication is disabled for this app",u.AuthenticationFailed);let t=this.getHttpBase(),n=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,r=[],i=(s,o)=>({...o,token_url:n,tokenParams:{...o.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&r.push({...Credentials({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,createUserUrl:`${t}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,createUserGrantType:"create_user"}),e.providers.anonymous?.enabled&&r.push({...Anonymous({clientId:this.config.apiKey}),token_url:`${t}/auth/token?appId=${encodeURIComponent(this.config.appId)}`}),e.providers.google?.enabled&&e.providers.google.clientId&&r.push(i("google",Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&r.push(i("github",GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&r.push(i("facebook",Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&r.push(i("dropbox",Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&r.push(i("apple",Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&r.push(i("twitter",Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),r.length===0)throw new h("No authentication providers are enabled for this app",u.AuthenticationFailed);return this.authGuard=new AuthGuard({providers:r,redirectUri:e.redirectUri}),this.authGuard}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("refreshAuthSession",`${t}/auth/refresh?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,...e?{refresh_token:e}:{}})}),r=await this.parseJsonWithTiming("refreshAuthSession",n);if(!n.response.ok){if(n.response.status===401)return this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(r,"Failed to refresh auth session",u.AuthenticationFailed);}let i=String(r.access_token??"");if(!i)throw new h("Refresh succeeded but no access token was returned",u.ParseError);let s=await this.fetchAuthMe(i).catch(()=>null),o={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:i,refreshToken:r.refresh_token?String(r.refresh_token):this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:s?.email??this.authSession?.email??null,emailVerified:s?.email_verified};if(s){try{delete s.kind,s.uid=s.id??s.uid,delete s.id;}catch{}this.setProfile(s);}return this.setAuthSession(o),await this.syncSocketAuth(i).catch(()=>{}),o}async issueSsrToken(e=120){let t=this.getHttpBase();await this.ensureCsrfProtection();let n=await this.timedFetch("issueSsrToken",`${t}/auth/ssr/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,ttlSeconds:e})}),r=await this.parseJsonWithTiming("issueSsrToken",n);n.response.ok||this.throwFetchFlareError(r,"Failed to mint SSR token",u.AuthenticationFailed);let i=String(r.token??"");if(!i)throw new h("SSR token response is missing token",u.ParseError,r);return {token:i,token_type:String(r.token_type??"Bearer"),expires_in:Number(r.expires_in??0),uid:String(r.uid??""),role:String(r.role??"user"),...typeof r.email=="string"?{email:r.email}:{}}}async signOut(){try{if(this.authSession?.accessToken||this.authSession?.refreshToken||this.config.httpBase){let t=this.getHttpBase();await this.ensureCsrfProtection(),await this.timedFetch("signOut",`${t}/auth/logout?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{},...this.authSession?.accessToken?{Authorization:`Bearer ${this.authSession.accessToken}`}:{}},body:JSON.stringify({appId:this.config.appId,apiKey:this.config.apiKey,refresh_token:this.authSession?.refreshToken})}).catch(()=>{});}}finally{this.setAuthSession(null),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,n){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=new URLSearchParams;i.set("appId",this.config.appId),i.set("client_id",this.config.apiKey??""),i.set("grant_type","create_user"),i.set("email",e),i.set("password",t),n?.scope?.length&&i.set("scope",n.scope.join(" ")),n?.additionalParams&&i.set("additional_params",JSON.stringify(n.additionalParams));let s=await this.timedFetch("registerWithEmail",`${r}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:i.toString()}),o=await this.parseJsonWithTiming("registerWithEmail",s);return !s.response.ok&&s.response.status!==202&&this.throwFetchFlareError(o,"User creation failed",u.WriteFailed),o}async requestEmailPasswordToken(e,t,n){let r=this.getHttpBase();await this.ensureCsrfProtection();let i=new URLSearchParams;i.set("appId",this.config.appId),i.set("client_id",this.config.apiKey??""),i.set("grant_type","password"),i.set("email",e),i.set("password",t),n?.length&&i.set("scope",n.join(" "));let s=await this.timedFetch("requestEmailPasswordToken",`${r}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:i.toString()}),o=await this.parseJsonWithTiming("requestEmailPasswordToken",s);return s.response.ok||this.throwFetchFlareError(o,"Sign-in with email/password failed",u.AuthenticationFailed),{kind:String(o.kind),access_token:String(o.access_token??""),refresh_token:o.refresh_token?String(o.refresh_token):null,expires_in:o.expires_in?Number(o.expires_in):null,token_type:String(o.token_type??"Bearer"),scope:o.scope?String(o.scope):null,profile:null,provider:"credentials"}}async fetchAuthMe(e){let t=this.getHttpBase(),n=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&n.set("apiKey",this.config.apiKey);let r=`${t}/auth/me?${n.toString()}`,i=await this.timedFetch("fetchAuthMe",r,{credentials:"include",headers:{Authorization:`Bearer ${e}`,...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",u.QueryFailed),s}};var Z=class extends L{autoPushRegisteredIdentity;constructor(e){super(e),this.log("FlareClient initialized",e),e.pushNotifications===true&&this.enableAutoPushNotificationsAfterAuth();}enableAutoPushNotificationsAfterAuth(){let e=async()=>{let t=this.authSession,n=String(t?.uid??"").trim()||"anon",r=String(t?.accessToken??"").trim(),i=n!=="anon"&&r?n:"anon";if(this.autoPushRegisteredIdentity!==i)try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=i;}catch(s){this.log("Auto push enable failed",s);}};this.onAuthStateChanged(()=>{e().catch(()=>{});}),e().catch(()=>{});}async autoEnablePushNotifications(){await this.setupPushServiceWorker().catch(()=>{}),await this.requestPushPermission();let{token:e}=await this.acquireBrowserPushToken();await this.registerPushToken({token:e,platform:"web",topics:[this.config.appId]});}},X=Z;function ee(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Re(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function W(a,e){let t=e.toLowerCase();for(let[n,r]of Object.entries(a??{}))if(n.toLowerCase()===t&&typeof r=="string")return r}function xe(a){let e=W(a,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,n]of Object.entries(a??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(n))return n.filter(r=>typeof r=="string");return []}function Ee(a,e){for(let t of a){let n=t.split(";").map(d=>d.trim()),[r]=n;if(!r)continue;let i=r.indexOf("=");if(i<=0)continue;let s=decodeURIComponent(r.slice(0,i)),o=r.slice(i+1);if(s===e)return decodeURIComponent(o)}}async function Fe(a){let e=new URL("/auth/config",a.endpoint);return e.searchParams.set("appId",a.appId),a.apiKey&&e.searchParams.set("apiKey",a.apiKey),await withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:a.apiKey?{"x-flare-api-key":a.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function ie(a){let e=await Fe(a),t=e?.data,n=e?.headers??{},r=W(n,"x-flare-csrf")??W(n,"x-csrf-token")??W(n,"csrf-token");if(typeof r=="string"&&r.length>0)return {csrfToken:r,...t};let i=t?.cookie?.csrfTokenName,s=i&&i.length>0?i:Re(a.appId),o=xe(n),d=Ee(o,s);if(typeof d=="string"&&d.length>0)return {csrfToken:d,...t}}function se(a,e,t){return `${encodeURIComponent(a)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function Me(a){let e=a.proxyCookieName??ee(a.appId),t=a.proxyCookieMaxAge??3600;return async function(r){let i=await ie(a),s=i?.csrfToken,o=new Headers({"Content-Type":"application/json"});return s&&o.set("Set-Cookie",se(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...i}),{status:200,headers:o})}}function Qe(a){let e=a.proxyCookieName??ee(a.appId),t=a.proxyCookieMaxAge??3600;return async function(r,i){if(r.method!=="GET"&&r.method!=="HEAD"){i.status(405).json({error:"Method not allowed"});return}let o=(await ie(a))?.csrfToken;o&&i.setHeader("Set-Cookie",se(e,o,t)),i.status(200).json({csrfToken:o??null});}}function Oe(a,e,t){let n=t??ee(e);if(a instanceof Request){let s=(a.headers.get("cookie")??"").split(";").map(d=>d.trim()).find(d=>d.startsWith(`${encodeURIComponent(n)}=`)||d.startsWith(`${n}=`));if(!s)return null;let o=s.indexOf("=");return o>=0?decodeURIComponent(s.slice(o+1)):null}let{cookies:r}=a;return typeof r?.get=="function"?r.get(n)?.value??null:r&&typeof r=="object"?r[n]??null:null}function _e(a,e){let t={};return a&&(t["x-flare-csrf"]=a),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var Ne=a=>a==="guest"?"auth == null":a==="auth"?"auth != null":"true",Be=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},De=a=>{let e=String(a??"").trim();if(!e||e==="false")return {auth:"any"};if(e==="auth != null")return {auth:"auth"};if(e==="auth == null")return {auth:"guest"};if(e==="true")return {auth:"any"};let t=e.match(/^\((auth != null|auth == null|true)\)\s*&&\s*\((.+)\)$/);if(t)return {auth:oe(t[1]),condition:t[2].trim()};let n=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return n?{auth:oe(n[1]),condition:n[2].trim()}:{auth:"any",condition:e}},oe=a=>{let e=String(a??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},Nt=a=>{let e={};for(let t of a){let n=String(t.collection||"").trim();if(!n)continue;let r=n==="any"?"*":n,i=Be(Ne(t.auth),t.condition);e[r]={".read":t.permissions.includes("read")?i:"false",".create":t.permissions.includes("create")?i:"false",".update":t.permissions.includes("update")?i:"false",".delete":t.permissions.includes("delete")?i:"false"};}return e},Bt=a=>Object.entries(a).map(([e,t],n)=>{let r=t?.[".read"],i=t?.[".create"],s=t?.[".update"],o=t?.[".delete"],d=t?.[".write"],l=[];typeof r=="string"&&r.trim()!=="false"&&l.push("read");let f=typeof i=="string"&&i.trim()!=="false"||typeof d=="string"&&d.trim()!=="false",y=typeof s=="string"&&s.trim()!=="false"||typeof d=="string"&&d.trim()!=="false",c=typeof o=="string"&&o.trim()!=="false"||typeof d=="string"&&d.trim()!=="false";f&&l.push("create"),y&&l.push("update"),c&&l.push("delete");let S=De(r||i||s||o||d);return {id:`${e}-${n}`,name:e==="*"?"All Collections":e,auth:S.auth,collection:e==="*"?"any":e,condition:S.condition,permissions:l}});var He=(y=>(y.authEmailNotVerified="auth/email-not-verified",y.authEmailAlreadyVerified="auth/email-already-verified",y.authInvalidToken="auth/invalid-token",y.authUserDisabled="auth/user-disabled",y.authUserNotFound="auth/user-not-found",y.authWrongPassword="auth/wrong-password",y.authEmailAlreadyInUse="auth/email-already-in-use",y.authInvalidEmail="auth/invalid-email",y.authWeakPassword="auth/weak-password",y.authTooManyRequests="auth/too-many-requests",y.authInternalError="auth/internal-error",y))(He||{});var Ue=(g=>(g.health="health",g.authConfig="auth_config",g.authRegistration="auth/registration",g.authRegistrationVerificationRequired="auth/registration-verification-required",g.authSession="auth/session",g.authExchange="auth/exchange",g.authLogout="auth/logout",g.authSsrBridge="auth/ssr_bridge",g.authSsrVerify="auth/ssr_verify",g.accountRecovery="account/recovery",g.emailVerification="email/verification",g.verificationDispatch="verification/dispatch",g.authProfile="auth/profile",g.adminToken="admin/token",g.documentDelete="document/delete",g.documentsDelete="documents/delete",g.documents="documents",g.document="document",g.documentCreate="document/create",g.documentUpdate="document/update",g.oauthProviderResponse="oauth_provider_response",g.success="success",g.response="response",g))(Ue||{});var T=null,_=null,$=null,Le=a=>JSON.stringify({endpoint:a.endpoint,appId:a.appId,apiKey:a.apiKey,publicKey:a.publicKey,autoReconnect:a.autoReconnect,reconnectDelay:a.reconnectDelay,maxReconnectDelay:a.maxReconnectDelay}),qt=a=>{let e=Le(a);if(T&&$!==e&&(T.disconnect(),T=null,_=null,$=null),!T){T=new X(a),$=e;let t=typeof window<"u"&&typeof document<"u",n=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!n)&&T.connect(),t&&T.setupPushServiceWorker().catch(()=>{}),_=new Proxy(T,{get(r,i,s){if(i==="onAuthStateChange")return r.onAuthStateChanged.bind(r);if(i==="onAuthConfigLoaded")return r.onAuthConfigLoaded.bind(r);let o=Reflect.get(r,i,s);return typeof o=="function"?o.bind(r):o}});}return _??T},jt=()=>_??T,Jt=()=>{T&&(T.disconnect(),T=null,_=null,$=null);},Vt=X;
2
+ export{Y as CollectionReference,I as DocumentQueryBuilder,O as DocumentReference,ce as FlareAction,h as FlareError,He as FlareErrors,ue as FlareEvent,Ue as FlareResponseCodes,_e as buildFlareHeaders,qt as connectApp,Me as createCsrfProxy,Qe as createCsrfProxyHandler,Vt as default,Jt as disconnectFlare,Oe as extractCsrfFromRequest,Nt as flareRulesToSecurityMap,jt as getFlare,re as parseValue,V as parseWhereCondition,Bt as securityMapToFlareRules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuzjs/flare",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "keywords": [
5
5
  "core",
6
6
  "zuz",