@zuzjs/flare 0.2.5 → 0.2.6

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,8 +158,87 @@ await app.sendPushNotification({
158
158
  await app.unregisterPushToken(token);
159
159
  ```
160
160
 
161
+ ### Direct Query Helpers (Knex-Style)
162
+
163
+ `collection()` query chaining uses object-based logical steps and dedicated operator families:
164
+
165
+ - Logic: `where({...})`, `and({...})`, `or({...})`
166
+ - `in` family: `in`, `andIn`, `orIn`
167
+ - `notIn` family: `notIn`, `andNotIn`, `orNotIn`
168
+ - `arrayContains` family: `arrayContains`, `andArrayContains`, `orArrayContains`
169
+ - `arrayContainsAny` family: `arrayContainsAny`, `andArrayContainsAny`, `orArrayContainsAny`
170
+ - `some` family (array of objects): `some`, `andSome`, `orSome`
171
+ - `like` family: `like`, `andLike`, `orLike`
172
+ - `notLike` family: `notLike`, `andNotLike`, `orNotLike`
173
+ - `exists` family: `exists`, `andExists`, `orExists`
174
+ - `notExists` family: `notExists`, `andNotExists`, `orNotExists`
175
+
176
+ ```ts
177
+ const uid = 'bDEgnSqsEDT5qdDdtOX1';
178
+
179
+ const boards = await app
180
+ .collection('boards')
181
+ .where({ uid })
182
+ .orArrayContains('team', uid)
183
+ .orderBy('createdAt', 'desc')
184
+ .limit(20)
185
+ .get();
186
+
187
+ const sameBoards = await app
188
+ .collection('boards')
189
+ .where({ uid })
190
+ .orArrayContains('team', uid)
191
+ .get();
192
+
193
+ const active = await app
194
+ .collection('tasks')
195
+ .in('status', ['todo', 'doing'])
196
+ .andArrayContainsAny('labels', ['urgent', 'backend'])
197
+ .andLike('title', '%bug%')
198
+ .get();
199
+
200
+ const boardAccess = await app
201
+ .collection('boards')
202
+ .some('team', { uid: 'xyz', role: 1 })
203
+ .get();
204
+ ```
205
+
161
206
  ### Template-Based Email APIs
162
207
 
208
+ ### Security Rules Example (Boards Owner Or Team Member)
209
+
210
+ For a `boards` document shape like:
211
+
212
+ ```json
213
+ {
214
+ "uid": "ownerUid",
215
+ "team": ["memberUid1", "memberUid2"]
216
+ }
217
+ ```
218
+
219
+ Use this DSL to allow read for owner or team member, and allow write only for owner:
220
+
221
+ ```txt
222
+ service cloud.firestore {
223
+ match /databases/{database}/documents {
224
+ function isOwner(ownerUid) {
225
+ return auth != null && auth.uid == ownerUid;
226
+ }
227
+
228
+ function isTeamMember(teamUids) {
229
+ return auth != null && auth.uid in teamUids;
230
+ }
231
+
232
+ match /boards/{boardId} {
233
+ allow read: if isOwner(resourceData.uid) || isTeamMember(resourceData.team);
234
+ allow create, update, delete: if isOwner(resourceData.uid);
235
+ }
236
+ }
237
+ }
238
+ ```
239
+
240
+ Tip: if you set owner uid at create time, prefer checking `requestData.uid` on create and `resourceData.uid` on update/delete.
241
+
163
242
  Emails are sent only through app-level templates stored in `_flare_email_templates`.
164
243
 
165
244
  Template placeholders use `{key}` syntax and are replaced from `values`.
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 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=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 B=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=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})}},C=B;var Q=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 C(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e,t,r){let i;return typeof e=="string"?i=[{field:e,op:t,value:r}]:i=M(e),this.clone({where:[...this.sq.where??[],...i]})}orWhere(e){return this.clone({where:[...this.sq.where??[],{or:e}]})}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 b(this.client,this.collection).update(e)}delete(){return new b(this.client,this.collection).delete()}},N=Q;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 A=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,f])=>[l.toLowerCase(),f]).sort(([l],[f])=>l.localeCompare(f)).map(([l,f])=>`${l}:${f}`).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,f]of Object.entries(e.headers))if(l.toLowerCase()===u)return String(f);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))}: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,f=this.buildHttpCacheKey(s,t,o,l,r?.credentials),g=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${i} ${e} start`,{method:s,url:t,headers:u,hasBody:!!r?.body});try{if(g){let k=this.httpResponseCache.get(f);if(k)return this.logHttpTiming(`#${i} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(k,i,n,s,t,0)}let d=this.httpInFlight.get(f);if(d){let k=await d,p=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} deduped`,{method:s,url:t,networkMs:Number(p.toFixed(2))}),this.createTimedFetchTrace(k,i,n,s,t,p)}let P=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(i)}),T=this.normalizeHeaders(P),z=this.redactHeaders(T),I={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:T,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 _=s.toUpperCase(),U=(async()=>{let k=_==="GET"?await core.withGet(t,I):_==="PUT"?await core.withPut(t,l,I):_==="PATCH"?await core.withPatch(t,l,I):await core.withPost(t,l,I),p={status:Number(k?.status??0),headers:Object.fromEntries(Object.entries(k?.headers??{}).map(([G,Y])=>[G,String(Y)])),data:k?.data??{}};return g&&this.rememberHttpResponse(f,p),p})();this.httpInFlight.set(f,U);let W=await U.finally(()=>{this.httpInFlight.delete(f);}),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 P=this.nowMs()-n;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(P.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 A({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 C(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(f=>{this.log("Subscription activation failed",f);});let u=()=>{let g=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",g),this.activeSubscriptions.delete(e),this.subscriptions.delete(g),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:g}).catch(d=>this.log("Unsubscribe failed",d));},l=u;return l.unsubscribe=u,l.onError=f=>{this.subscriptionErrorHandlers.get(e)?.add(f);let g=this.subscriptionLastErrors.get(e);if(g)try{f(g);}catch(d){this.log("Subscription error callback failed",d);}return l},l.onPermissionDenied=f=>{this.subscriptionPermissionHandlers.get(e)?.add(f);let g=this.subscriptionLastErrors.get(e);if(g?.permissionDenied)try{f(g);}catch(d){this.log("Subscription permission callback failed",d);}return l},l.catch=f=>l.onError(f),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 E=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 O=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]});}},H=O;function D(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function ke(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 Se(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 Te(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 Ce(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 Ce(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:ke(a.appId),o=Se(r),u=Te(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 we(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 Pe(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 Ie(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 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 Ae=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},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: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"},At=a=>{let e={};for(let t of a){let r=String(t.collection||"").trim();if(!r)continue;let i=r==="any"?"*":r,n=Re(Ae(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 f=typeof n=="string"&&n.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",g=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";f&&l.push("create"),g&&l.push("update"),d&&l.push("delete");let T=Ee(i||n||s||o||u);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:T.auth,collection:e==="*"?"any":e,condition:T.condition,permissions:l}});var xe=(g=>(g.authEmailNotVerified="auth/email-not-verified",g.authEmailAlreadyVerified="auth/email-already-verified",g.authInvalidToken="auth/invalid-token",g.authUserDisabled="auth/user-disabled",g.authUserNotFound="auth/user-not-found",g.authWrongPassword="auth/wrong-password",g.authEmailAlreadyInUse="auth/email-already-in-use",g.authInvalidEmail="auth/invalid-email",g.authWeakPassword="auth/weak-password",g.authTooManyRequests="auth/too-many-requests",g.authInternalError="auth/internal-error",g))(xe||{});var Fe=(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))(Fe||{});var m=null,w=null,F=null,_e=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=_e(a);if(m&&F!==e&&(m.disconnect(),m=null,w=null,F=null),!m){m=new H(a),F=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(()=>{}),w=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 w??m},Ot=()=>w??m,Ht=()=>{m&&(m.disconnect(),m=null,w=null,F=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=b;exports.DocumentReference=C;exports.FlareAction=X;exports.FlareError=h;exports.FlareErrors=xe;exports.FlareEvent=ee;exports.FlareResponseCodes=Fe;exports.buildFlareHeaders=ve;exports.connectApp=Nt;exports.createCsrfProxy=we;exports.createCsrfProxyHandler=Pe;exports.default=Dt;exports.disconnectFlare=Ht;exports.extractCsrfFromRequest=Ie;exports.flareRulesToSecurityMap=At;exports.getFlare=Ot;exports.parseValue=K;exports.parseWhereCondition=M;exports.securityMapToFlareRules=Rt;
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;
package/dist/index.d.cts CHANGED
@@ -162,7 +162,7 @@ type AuthConfigListener = (conf: FlareAuthConfig) => void;
162
162
  interface SubscribeOptions {
163
163
  skipSnapshot?: boolean;
164
164
  }
165
- type QueryOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any" | "like" | "not-like" | "contains" | "exists" | "not-exists";
165
+ type QueryOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any" | "elem-match" | "like" | "not-like" | "contains" | "exists" | "not-exists";
166
166
  interface QueryConfig {
167
167
  field: string;
168
168
  op: QueryOperator;
@@ -170,9 +170,13 @@ interface QueryConfig {
170
170
  }
171
171
  /** OR group */
172
172
  interface OrFilter {
173
- or: QueryConfig[];
173
+ or: AnyFilter[];
174
174
  }
175
- type AnyFilter = QueryConfig | OrFilter;
175
+ /** AND group */
176
+ interface AndFilter {
177
+ and: AnyFilter[];
178
+ }
179
+ type AnyFilter = QueryConfig | OrFilter | AndFilter;
176
180
  type WhereCondition = Record<string, string | number | boolean | any[]>;
177
181
  interface OrderByClause {
178
182
  field: string;
@@ -522,14 +526,48 @@ declare class CollectionReference<T = any, TPresetMap extends QueryPresetMap = {
522
526
  constructor(client: FlareClient<TPresetMap>, collection: string);
523
527
  doc(id: string): DocumentReference<T>;
524
528
  private clone;
529
+ private normalizeFilterValue;
530
+ private normalizeFilter;
531
+ private toQueryFilters;
532
+ private appendOperatorFilter;
533
+ private appendAndFilters;
534
+ private toOrNode;
535
+ private toAndNode;
536
+ private appendOrFilters;
537
+ private appendFilters;
525
538
  with<Name extends keyof TPresetMap & string>(name: Name, params: QueryPresetParams<TPresetMap[Name]>): CollectionQuery<QueryPresetRow<TPresetMap[Name]>, TPresetMap>;
526
539
  with(name: string, params?: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
527
540
  /** ORM shorthand: .where({ age: ">= 25", role: "admin" }) */
528
541
  where(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
529
- /** Explicit field/op/value */
530
- where(field: string, op: QueryConfig['op'], value: unknown): CollectionQuery<T, TPresetMap>;
531
- /** OR group: .orWhere([{ field:"status", op:"==", value:"active" }, ...]) */
532
- orWhere(filters: QueryConfig[]): CollectionQuery<T, TPresetMap>;
542
+ and(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
543
+ or(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
544
+ in(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
545
+ andIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
546
+ orIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
547
+ notIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
548
+ andNotIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
549
+ orNotIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
550
+ arrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
551
+ andArrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
552
+ orArrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
553
+ arrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
554
+ andArrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
555
+ orArrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
556
+ some(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
557
+ andSome(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
558
+ orSome(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
559
+ like(field: string, value: string): CollectionQuery<T, TPresetMap>;
560
+ andLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
561
+ orLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
562
+ notLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
563
+ andNotLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
564
+ orNotLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
565
+ exists(field: string): CollectionQuery<T, TPresetMap>;
566
+ andExists(field: string): CollectionQuery<T, TPresetMap>;
567
+ orExists(field: string): CollectionQuery<T, TPresetMap>;
568
+ notExists(field: string): CollectionQuery<T, TPresetMap>;
569
+ andNotExists(field: string): CollectionQuery<T, TPresetMap>;
570
+ orNotExists(field: string): CollectionQuery<T, TPresetMap>;
533
571
  /** Get items starting from the most recently created (descending sequence) */
534
572
  latest(): CollectionQuery<T, TPresetMap>;
535
573
  /** Get items starting from the first ever created (ascending sequence) */
@@ -1382,4 +1420,4 @@ declare const getFlare: () => FlareClient | null;
1382
1420
  */
1383
1421
  declare const disconnectFlare: () => void;
1384
1422
 
1385
- export { type AggregateFunction, type AggregateSpec, 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 };
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 };
package/dist/index.d.ts CHANGED
@@ -162,7 +162,7 @@ type AuthConfigListener = (conf: FlareAuthConfig) => void;
162
162
  interface SubscribeOptions {
163
163
  skipSnapshot?: boolean;
164
164
  }
165
- type QueryOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any" | "like" | "not-like" | "contains" | "exists" | "not-exists";
165
+ type QueryOperator = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any" | "elem-match" | "like" | "not-like" | "contains" | "exists" | "not-exists";
166
166
  interface QueryConfig {
167
167
  field: string;
168
168
  op: QueryOperator;
@@ -170,9 +170,13 @@ interface QueryConfig {
170
170
  }
171
171
  /** OR group */
172
172
  interface OrFilter {
173
- or: QueryConfig[];
173
+ or: AnyFilter[];
174
174
  }
175
- type AnyFilter = QueryConfig | OrFilter;
175
+ /** AND group */
176
+ interface AndFilter {
177
+ and: AnyFilter[];
178
+ }
179
+ type AnyFilter = QueryConfig | OrFilter | AndFilter;
176
180
  type WhereCondition = Record<string, string | number | boolean | any[]>;
177
181
  interface OrderByClause {
178
182
  field: string;
@@ -522,14 +526,48 @@ declare class CollectionReference<T = any, TPresetMap extends QueryPresetMap = {
522
526
  constructor(client: FlareClient<TPresetMap>, collection: string);
523
527
  doc(id: string): DocumentReference<T>;
524
528
  private clone;
529
+ private normalizeFilterValue;
530
+ private normalizeFilter;
531
+ private toQueryFilters;
532
+ private appendOperatorFilter;
533
+ private appendAndFilters;
534
+ private toOrNode;
535
+ private toAndNode;
536
+ private appendOrFilters;
537
+ private appendFilters;
525
538
  with<Name extends keyof TPresetMap & string>(name: Name, params: QueryPresetParams<TPresetMap[Name]>): CollectionQuery<QueryPresetRow<TPresetMap[Name]>, TPresetMap>;
526
539
  with(name: string, params?: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
527
540
  /** ORM shorthand: .where({ age: ">= 25", role: "admin" }) */
528
541
  where(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
529
- /** Explicit field/op/value */
530
- where(field: string, op: QueryConfig['op'], value: unknown): CollectionQuery<T, TPresetMap>;
531
- /** OR group: .orWhere([{ field:"status", op:"==", value:"active" }, ...]) */
532
- orWhere(filters: QueryConfig[]): CollectionQuery<T, TPresetMap>;
542
+ and(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
543
+ or(condition: WhereCondition): CollectionQuery<T, TPresetMap>;
544
+ in(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
545
+ andIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
546
+ orIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
547
+ notIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
548
+ andNotIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
549
+ orNotIn(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
550
+ arrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
551
+ andArrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
552
+ orArrayContains(field: string, value: unknown): CollectionQuery<T, TPresetMap>;
553
+ arrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
554
+ andArrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
555
+ orArrayContainsAny(field: string, values: unknown[] | unknown): CollectionQuery<T, TPresetMap>;
556
+ some(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
557
+ andSome(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
558
+ orSome(field: string, condition: Record<string, unknown>): CollectionQuery<T, TPresetMap>;
559
+ like(field: string, value: string): CollectionQuery<T, TPresetMap>;
560
+ andLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
561
+ orLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
562
+ notLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
563
+ andNotLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
564
+ orNotLike(field: string, value: string): CollectionQuery<T, TPresetMap>;
565
+ exists(field: string): CollectionQuery<T, TPresetMap>;
566
+ andExists(field: string): CollectionQuery<T, TPresetMap>;
567
+ orExists(field: string): CollectionQuery<T, TPresetMap>;
568
+ notExists(field: string): CollectionQuery<T, TPresetMap>;
569
+ andNotExists(field: string): CollectionQuery<T, TPresetMap>;
570
+ orNotExists(field: string): CollectionQuery<T, TPresetMap>;
533
571
  /** Get items starting from the most recently created (descending sequence) */
534
572
  latest(): CollectionQuery<T, TPresetMap>;
535
573
  /** Get items starting from the first ever created (ascending sequence) */
@@ -1382,4 +1420,4 @@ declare const getFlare: () => FlareClient | null;
1382
1420
  */
1383
1421
  declare const disconnectFlare: () => void;
1384
1422
 
1385
- export { type AggregateFunction, type AggregateSpec, 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 };
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 };
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 B(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 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=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 Q=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=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})}},w=Q;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 w(this.client,this.collection,e)}clone(e){let t=new a(this.client,this.collection);return t.sq={...this.sq,...e},t}with(e,t={}){return this.client.applyQueryPreset(this,e,t)}where(e,t,r){let i;return typeof e=="string"?i=[{field:e,op:t,value:r}]:i=B(e),this.clone({where:[...this.sq.where??[],...i]})}orWhere(e){return this.clone({where:[...this.sq.where??[],{or:e}]})}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 k(this.client,this.collection).update(e)}delete(){return new k(this.client,this.collection).delete()}},O=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"},E=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,f])=>[l.toLowerCase(),f]).sort(([l],[f])=>l.localeCompare(f)).map(([l,f])=>`${l}:${f}`).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,f]of Object.entries(e.headers))if(l.toLowerCase()===u)return String(f);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))}: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,f=this.buildHttpCacheKey(s,t,o,l,r?.credentials),g=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${i} ${e} start`,{method:s,url:t,headers:u,hasBody:!!r?.body});try{if(g){let S=this.httpResponseCache.get(f);if(S)return this.logHttpTiming(`#${i} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(S,i,n,s,t,0)}let d=this.httpInFlight.get(f);if(d){let S=await d,p=this.nowMs()-n;return this.logHttpTiming(`#${i} ${e} deduped`,{method:s,url:t,networkMs:Number(p.toFixed(2))}),this.createTimedFetchTrace(S,i,n,s,t,p)}let I=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(i)}),C=this.normalizeHeaders(I),G=this.redactHeaders(C),v={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:G,hasBody:!!r?.body});let M=s.toUpperCase(),W=(async()=>{let S=M==="GET"?await withGet(t,v):M==="PUT"?await withPut(t,l,v):M==="PATCH"?await withPatch(t,l,v):await withPost(t,l,v),p={status:Number(S?.status??0),headers:Object.fromEntries(Object.entries(S?.headers??{}).map(([Y,Z])=>[Y,String(Z)])),data:S?.data??{}};return g&&this.rememberHttpResponse(f,p),p})();this.httpInFlight.set(f,W);let L=await W.finally(()=>{this.httpInFlight.delete(f);}),$=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 I=this.nowMs()-n;throw this.logHttpTiming(`#${i} ${e} failed`,{networkMs:Number(I.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 O(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 w(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(f=>{this.log("Subscription activation failed",f);});let u=()=>{let g=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",g),this.activeSubscriptions.delete(e),this.subscriptions.delete(g),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:g}).catch(d=>this.log("Unsubscribe failed",d));},l=u;return l.unsubscribe=u,l.onError=f=>{this.subscriptionErrorHandlers.get(e)?.add(f);let g=this.subscriptionLastErrors.get(e);if(g)try{f(g);}catch(d){this.log("Subscription error callback failed",d);}return l},l.onPermissionDenied=f=>{this.subscriptionPermissionHandlers.get(e)?.add(f);let g=this.subscriptionLastErrors.get(e);if(g?.permissionDenied)try{f(g);}catch(d){this.log("Subscription permission callback failed",d);}return l},l.catch=f=>l.onError(f),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 x=class extends E{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 x{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 Se(a){return `__flare_csrf_${a.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function F(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=F(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 we(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 we(a),t=e?.data,r=e?.headers??{},i=F(r,"x-flare-csrf")??F(r,"x-csrf-token")??F(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:Se(a.appId),o=Te(r),u=Ce(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 Pe(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 Ie(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 ve(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 Ae(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",Ee=(a,e)=>{let t=String(e??"").trim();return t?a==="true"?t:`(${a}) && (${t})`:a},xe=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=Ee(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},Et=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 f=typeof n=="string"&&n.trim()!=="false"||typeof u=="string"&&u.trim()!=="false",g=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";f&&l.push("create"),g&&l.push("update"),d&&l.push("delete");let C=xe(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 Fe=(g=>(g.authEmailNotVerified="auth/email-not-verified",g.authEmailAlreadyVerified="auth/email-already-verified",g.authInvalidToken="auth/invalid-token",g.authUserDisabled="auth/user-disabled",g.authUserNotFound="auth/user-not-found",g.authWrongPassword="auth/wrong-password",g.authEmailAlreadyInUse="auth/email-already-in-use",g.authInvalidEmail="auth/invalid-email",g.authWeakPassword="auth/weak-password",g.authTooManyRequests="auth/too-many-requests",g.authInternalError="auth/internal-error",g))(Fe||{});var _e=(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))(_e||{});var b=null,P=null,_=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}),Ot=a=>{let e=Me(a);if(b&&_!==e&&(b.disconnect(),b=null,P=null,_=null),!b){b=new D(a),_=e;let t=typeof window<"u"&&typeof document<"u",r=typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";(t||!r)&&b.connect(),t&&b.setupPushServiceWorker().catch(()=>{}),P=new Proxy(b,{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??b},Ht=()=>P??b,Dt=()=>{b&&(b.disconnect(),b=null,P=null,_=null);},Ut=D;
2
- export{O as CollectionReference,k as DocumentQueryBuilder,w as DocumentReference,ee as FlareAction,h as FlareError,Fe as FlareErrors,te as FlareEvent,_e as FlareResponseCodes,Ae as buildFlareHeaders,Ot as connectApp,Pe as createCsrfProxy,Ie as createCsrfProxyHandler,Ut as default,Dt as disconnectFlare,ve as extractCsrfFromRequest,Rt as flareRulesToSecurityMap,Ht as getFlare,q as parseValue,B as parseWhereCondition,Et 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,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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuzjs/flare",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "keywords": [
5
5
  "core",
6
6
  "zuz",