@zuzjs/flare 0.2.27 → 0.2.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-CnmBBd-u.d.cts → index-BDbL-6Rr.d.cts} +2 -2
- package/dist/{index-DPlKzY-d.d.ts → index-DvHbnHDV.d.ts} +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {Credentials,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,getCookie,withGet,withPut,withPatch,withPost}from'@zuzjs/core';var f=class extends Error{constructor(t,r,n){super(t);this.code=r;this.cause=n;this.name="ZuzFlareError";}};var be={NotFound:"404",ConnectionFailed:"CONNECTION_FAILED",ConnectionTimeout:"CONNECTION_TIMEOUT",NotConnected:"NOT_CONNECTED",AuthenticationFailed:"AUTHENTICATION_FAILED",SubscriptionFailed:"SUBSCRIPTION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",DeleteFailed:"DELETE_FAILED",QueryFailed:"QUERY_FAILED",Timeout:"TIMEOUT",ParseError:"PARSE_ERROR",Unknown:"UNKNOWN"},d=be;var ke=(l=>(l.SUBSCRIBE="subscribe",l.UNSUBSCRIBE="unsubscribe",l.WRITE="write",l.DELETE="delete",l.AUTH="auth",l.PING="ping",l.OFFLINE_SYNC="offline_sync",l.CALL="call",l.QUERY="query",l.PRESENCE_JOIN="presence_join",l.PRESENCE_LEAVE="presence_leave",l.PRESENCE_HEARTBEAT="presence_heartbeat",l))(ke||{}),Se=(l=>(l.SNAPSHOT="snapshot",l.CHANGE="change",l.ERROR="error",l.ACK="ack",l.PONG="pong",l.AUTH_OK="auth_ok",l.OFFLINE_ACK="offline_ack",l.CALL_RESPONSE="call_response",l.QUERY_RESULT="query_result",l.PRESENCE_STATE="presence_state",l.PRESENCE_JOIN="presence_join",l.PRESENCE_LEAVE="presence_leave",l))(Se||{});function te(o){let e=[];for(let[t,r]of Object.entries(o))if(typeof r=="string"){let n=r.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(n){let[,i,s]=n;e.push({field:t,op:i,value:ue(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 ue(o){if(!isNaN(Number(o)))return Number(o);if(o==="true")return true;if(o==="false")return false;if(o==="null")return null;if(o!=="undefined")return o}var D=class{constructor(e,t,r){this.client=e;this.collection=t;this.docIdFromRef=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.docIdFromRef)return this.docIdFromRef;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 f('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',d.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,n)=>{let i=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(i(),r(s.data));});setTimeout(()=>{i(),n(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 re=class{constructor(e,t,r){this.client=e;this.collection=t;this.id=r;}async get(){return new D(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 updateAndGet(e){return await this.update(e),this.get()}async setAndGet(e){return await this.set(e),this.get()}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,n=>{n.type==="snapshot"&&(e(n),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})}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})}},U=re;var ne=class o{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(r,n,i)=>{if(typeof n=="string"&&!(n in r)&&this.client.hasQueryPreset(n))return (a={})=>r.with(n,a);let s=Reflect.get(r,n,i);return typeof s=="function"?s.bind(r):s}})}sq={};promise;doc(e){return new U(this.client,this.collection,e)}clone(e){let t=new o(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 te(e).map(t=>this.normalizeFilter(t))}appendOperatorFilter(e,t,r,n){return this.appendFilters([this.normalizeFilter({field:e,op:t,value:r})],n)}appendAndFilters(e){return this.clone({where:[...this.sq.where??[],...e]})}toOrNode(e){return {or:e}}toAndNode(e){return {and:e}}isLeafFilter(e){return !("or"in e)&&!("and"in e)}isIdentityGuard(e){return this.isLeafFilter(e)?(e.field==="id"||e.field==="_id")&&e.op==="==":false}splitIdentityGuards(e){let t=[],r=[];for(let n of e){if(this.isIdentityGuard(n)){t.push(n);continue}r.push(n);}return {guards:t,rest:r}}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 c=r;return this.clone({where:[{or:[...c.or,...e]}]})}let{guards:i,rest:s}=this.splitIdentityGuards(t);if(i.length>0){let c=s.length===0?void 0:s.length===1?s[0]:{and:s},h=c?[{or:[c,...e]}]:[{or:[...e]}];return this.clone({where:[...i,...h]})}let a=t.length===1?t[0]:{and:t};return this.clone({where:[{or:[a,...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"}]})}newest(){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 n={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(n.where=t.where),Array.isArray(t?.orderBy)&&(n.orderBy=t.orderBy),typeof t?.limit=="number"&&(n.limit=t.limit),typeof t?.offset=="number"&&(n.offset=t.offset),t?.startAt&&(n.startAt=t.startAt),t?.startAfter&&(n.startAfter=t.startAfter),t?.endAt&&(n.endAt=t.endAt),t?.endBefore&&(n.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(n.aggregate=t.aggregate),t?.groupBy&&(n.groupBy=t.groupBy),Array.isArray(t?.having)&&(n.having=t.having),t?.vectorSearch&&(n.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(n.select=t.select),typeof t?.distinctField=="string"&&(n.distinctField=t.distinctField),Array.isArray(t?.joins)&&(n.joins=t.joins.map(i=>this.buildStructuredJoin(String(i?.collection??""),i))),n}cloneStructuredJoin(e){let t={...e};return Array.isArray(e.where)&&(t.where=e.where.map(r=>({...r}))),Array.isArray(e.orderBy)&&(t.orderBy=e.orderBy.map(r=>({...r}))),Array.isArray(e.aggregate)&&(t.aggregate=e.aggregate.map(r=>({...r}))),Array.isArray(e.having)&&(t.having=e.having.map(r=>({...r}))),Array.isArray(e.select)&&(t.select=[...e.select]),e.groupBy?.fields&&(t.groupBy={fields:[...e.groupBy.fields]}),e.startAt?.values&&(t.startAt={values:[...e.startAt.values]}),e.startAfter?.values&&(t.startAfter={values:[...e.startAfter.values]}),e.endAt?.values&&(t.endAt={values:[...e.endAt.values]}),e.endBefore?.values&&(t.endBefore={values:[...e.endBefore.values]}),Array.isArray(e.joins)&&(t.joins=e.joins.map(r=>this.cloneStructuredJoin(r))),t}appendNestedJoinByAlias(e,t,r){for(let n of e){if(n.as===t)return n.joins=[...n.joins??[],r],true;if(Array.isArray(n.joins)&&this.appendNestedJoinByAlias(n.joins,t,r))return true}return false}parseRelationRef(e){let r=String(e??"").trim().match(/^([A-Za-z0-9_.]+)\s*->\s*([A-Za-z0-9_]+)\.([A-Za-z0-9_.]+)(?:\s+as\s+([A-Za-z0-9_]+))?$/i);if(!r)throw new Error(`Invalid relation format: "${e}". Expected "source.path->collection.target"`);return {source:r[1],collection:r[2],target:r[3],alias:r[4]}}join(e,t){let r=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],r]})}joinNested(e,t,r){let n=String(e??"").trim();if(!n)throw new Error("joinNested requires parentAlias");let i=(this.sq.joins??[]).map(a=>this.cloneStructuredJoin(a));if(i.length===0)throw new Error(`joinNested parent alias "${n}" not found`);let s=this.buildStructuredJoin(t,r);if(!this.appendNestedJoinByAlias(i,n,s))throw new Error(`joinNested parent alias "${n}" not found`);return this.clone({joins:i})}Join(e,t){return this.join(e,t)}JoinNested(e,t,r){return this.joinNested(e,t,r)}withRelation(e,t={}){let r=this.parseRelationRef(e);return this.join(r.collection,{...t,source:r.source,target:r.target,as:t.as??r.alias??r.collection})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}getRawQuery(){let e={...this.sq};return Array.isArray(this.sq.where)&&(e.where=this.sq.where.map(t=>({...t}))),Array.isArray(this.sq.orderBy)&&(e.orderBy=this.sq.orderBy.map(t=>({...t}))),Array.isArray(this.sq.aggregate)&&(e.aggregate=this.sq.aggregate.map(t=>({...t}))),Array.isArray(this.sq.having)&&(e.having=this.sq.having.map(t=>({...t}))),Array.isArray(this.sq.select)&&(e.select=[...this.sq.select]),Array.isArray(this.sq.joins)&&(e.joins=this.sq.joins.map(t=>this.cloneStructuredJoin(t))),this.sq.groupBy?.fields&&(e.groupBy={fields:[...this.sq.groupBy.fields]}),this.sq.startAt?.values&&(e.startAt={values:[...this.sq.startAt.values]}),this.sq.startAfter?.values&&(e.startAfter={values:[...this.sq.startAfter.values]}),this.sq.endAt?.values&&(e.endAt={values:[...this.sq.endAt.values]}),this.sq.endBefore?.values&&(e.endBefore={values:[...this.sq.endBefore.values]}),{collection:this.collection,query:e}}async get(){return this._execute()}async first(){let e=await this._execute();return e.length>0?e[0]:null}async last(){let e=await this._execute();return e.length>0?e[e.length-1]:null}_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 this.client.query(this.collection,this.sq)}async _executeSubscribe(){let e=uuid2(18);return new Promise((t,r)=>{let n=Object.keys(this.sq).length>0?this.sq:void 0,i=this.client.subscribe(e,this.collection,void 0,n,s=>{s.type==="snapshot"&&(i(),t(s.data));});setTimeout(()=>{i(),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,n=(()=>{});return n=this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="snapshot"&&(e(i),n());}),n}stream(e={}){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0,n=new Set,i=[],s=new Map,a=Math.max(0,Number(e.flushMs??24)),c=Math.max(1,Number(e.maxBatchSize??200)),h=e.insertAt??"end",g=typeof e.maxDocs=="number"&&e.maxDocs>0?Math.floor(e.maxDocs):void 0,u=String(e.idField??"id"),l=[],S=false,p=false,y=0,m,T=()=>{s.clear();for(let b=0;b<l.length;b+=1){let F=A(l[b]);F&&s.set(F,b);}},A=(b,F)=>{if(F)return F;if(b==null)return;if(typeof e.getId=="function"){let j=e.getId(b);if(typeof j=="string"&&j.length>0)return j}let E=b?.[u]??b?._id??b?.docId;if(typeof E=="string"&&E.length>0)return E},P=()=>{g==null||l.length<=g||(l=l.slice(0,g));},B=()=>{typeof e.sort=="function"&&(l=l.slice().sort(e.sort));},I=(b,F)=>{y+=1;let E=l.slice(),j={reason:b,batchSize:F,version:y,ready:p};for(let q of Array.from(n))try{q(E,j);}catch{}},C=()=>{m!=null&&(clearTimeout(m),m=void 0);},k=b=>{if(b.operation==="delete"){let q=s.get(b.docId);if(q==null)return;l.splice(q,1),T();return}let F=b.data;if(F==null)return;let E=A(F,b.docId);if(!E)return;let j=s.get(E);if(typeof j=="number"){l[j]=F;return}h==="start"?l.unshift(F):l.push(F),P(),T();},Q=()=>{if(S||i.length===0)return;C();let b=i.splice(0,i.length);for(let F of b)k(F);B(),T(),I("change-batch",b.length);},v=()=>{S||m!=null||(m=setTimeout(Q,a));},w=this.client.subscribe(t,this.collection,void 0,r,b=>{if(!S){if(b.type==="snapshot"){l=Array.isArray(b.data)?[...b.data]:[],p=true,C(),i.length=0,B(),P(),T(),I("snapshot",0);return}if(i.push(b),i.length>=c){Q();return}v();}}),_={subscribe(b,F=true){if(n.add(b),F){let E={reason:p?"change-batch":"snapshot",batchSize:0,version:y,ready:p};try{b(l.slice(),E);}catch{}}return ()=>{n.delete(b);}},getSnapshot(){return l.slice()},isReady(){return p},getVersion(){return y},close:()=>{S||(S=true,C(),i.length=0,n.clear(),w());},onError(b){return w.onError(b),_},onPermissionDenied(b){return w.onPermissionDenied(b),_}};return _}asStore(e={}){let t=this.stream(e);return {subscribe:r=>t.subscribe(()=>{r();},false),getSnapshot:()=>t.getSnapshot(),getServerSnapshot:()=>[],stream:t,destroy:()=>{t.close();}}}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,n=>{n.type==="change"&&n.operation==="insert"&&n.data!=null&&e(n.data,n.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,n=>{n.type==="change"&&(n.operation==="update"||n.operation==="replace")&&n.data!=null&&e(n.data,n.docId);},{skipSnapshot:true})}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,n=>{n.type==="change"&&n.operation==="delete"&&e(n.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,n=>{n.type==="change"&&e(n.data??null,n.docId,n.operation);},{skipSnapshot:true})}ensureBulkOptions(e){let t=Number(e?.batchSize??250),r=Number(e?.concurrency??1);return {...e,batchSize:Number.isFinite(t)&&t>0?Math.floor(t):250,concurrency:Number.isFinite(r)&&r>0?Math.floor(r):1,continueOnError:e?.continueOnError===true}}toPercent(e,t){if(!(typeof t!="number"||t<=0))return Math.round(e/t*100)}emitBulkProgress(e,t,r){r&&r({operation:e,...t,percent:this.toPercent(t.processed,t.total)});}async*chunkIterable(e,t){let r=[];for await(let n of e)r.push(n),r.length>=t&&(yield r,r=[]);r.length>0&&(yield r);}assertBulkSignal(e){if(e?.aborted)throw new Error("Bulk write aborted")}async runChunkWorkers(e,t,r,n,i,s,a=false,c){let h=0,g,u=async()=>{for(;h<t.length;){this.assertBulkSignal(c);let S=h;h+=1;let p=t[S];try{let y=await n(p);i.succeeded+=1,i.processed+=1,this.emitBulkProgress(e,{processed:i.processed,succeeded:i.succeeded,failed:i.failed,total:i.total,lastDocId:y.docId},s);}catch(y){if(i.failed+=1,i.processed+=1,this.emitBulkProgress(e,{processed:i.processed,succeeded:i.succeeded,failed:i.failed,total:i.total,lastError:y},s),!a)throw y;g==null&&(g=y);}}},l=Math.max(1,Math.min(r,t.length));if(await Promise.all(Array.from({length:l},()=>u())),!a&&g!=null)throw g}async runBulkWrite(e,t,r,n){let i=this.ensureBulkOptions(n);this.assertBulkSignal(i.signal);let s={processed:0,succeeded:0,failed:0,total:Array.isArray(t)?t.length:void 0};this.emitBulkProgress(e,{processed:s.processed,succeeded:s.succeeded,failed:s.failed,total:s.total},i.onProgress);for await(let c of this.chunkIterable(t,i.batchSize))this.assertBulkSignal(i.signal),await this.runChunkWorkers(e,c,i.concurrency,r,s,i.onProgress,i.continueOnError,i.signal);return {operation:e,processed:s.processed,succeeded:s.succeeded,failed:s.failed,total:s.total}}async add(e){let t=uuid2(18),r=this.doc(t);return await r.set(e),r}async addMany(e,t){return this.runBulkWrite("addMany",e,async r=>{let n=uuid2(18);return await this.client.send("write",{collection:this.collection,docId:n,data:r,merge:false}),{docId:n}},t)}async updateMany(e,t){return this.runBulkWrite("updateMany",e,async r=>(await this.client.send("write",{collection:this.collection,docId:r.id,data:r.data,merge:true}),{docId:r.id}),t)}async deleteMany(e,t){return this.runBulkWrite("deleteMany",e,async r=>(await this.client.send("delete",{collection:this.collection,docId:r}),{docId:r}),t)}update(e){return new D(this.client,this.collection).update(e)}delete(){return new D(this.client,this.collection).delete()}},ie=ne;var H=o=>new Function("s","return import(s)")(o);async function Te(o){let e=o.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 i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",r.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function we(o,e){let t=await Te(e),r=new TextEncoder().encode(JSON.stringify(o)),i=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,r),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(i))):Buffer.from(i).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var K=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(n){this.log("Send error",n),this.messageQueue.push(e);}};this.options.publicKey?we(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 Re={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},le={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},J=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 n=e,i=typeof n?.error=="string"&&n.error.length>0?n.error:r,s=typeof n?.message=="string"&&n.message.length>0?n.message:t;throw new f(s,i,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n]=r;});else if(Array.isArray(e))for(let[r,n]of e)t[String(r)]=String(n);else for(let[r,n]of Object.entries(e))t[String(r)]=String(n);return t}redactHeaders(e){let t={...e};for(let r of Object.keys(t)){let n=r.toLowerCase();(n==="authorization"||n==="x-flare-csrf"||n==="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(n=>this.stableStringify(n)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(n=>`${n}:${this.stableStringify(t[n])}`).join(",")}}`}buildHttpCacheKey(e,t,r,n,i){let a=Object.entries(r).map(([h,g])=>[h.toLowerCase(),g]).sort(([h],[g])=>h.localeCompare(g)).map(([h,g])=>`${h}:${g}`).join("|"),c=this.stableStringify(n);return `${e}|${t}|${i??""}|${a}|${c}`}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,n,i,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:a=>{let c=a.toLowerCase();for(let[h,g]of Object.entries(e.headers))if(h.toLowerCase()===c)return String(g);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:r,networkMs:s,method:n,url:i}}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[n,i]of Object.entries(t))r.set(n,i);return r}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(Re[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(le[t]?le[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(n=>this.normalizeOutboundData(n));if(!e||typeof e!="object")return e;let t=e,r={};for(let[n,i]of Object.entries(t))r[this.toWireField(n)]=this.normalizeOutboundData(i);return r}normalizeInboundData(e){if(Array.isArray(e))return e.map(n=>this.normalizeInboundData(n));if(!e||typeof e!="object")return e;let t=e,r={};for(let[n,i]of Object.entries(t))r[this.fromWireField(n)]=this.normalizeInboundData(i);return r}getDataMapper(e){let t=this.config.dataMapper;if(!t||typeof t!="object")return null;let r=t[e];return typeof r=="function"?r:null}runMapper(e,t){let r=this.getDataMapper(e);if(!r||t==null||typeof t!="object")return t;try{return r(t)}catch(n){return this.log(`dataMapper for "${e}" failed`,n),t}}applyJoinAliasMappers(e,t){if(!e||typeof e!="object"||!Array.isArray(t)||t.length===0)return e;let r=e;for(let n of t){let i=String(n?.as??"").trim();if(!i)continue;let s=Array.isArray(n?.joins)?n.joins:[],a=r[i],c=a;Array.isArray(a)?c=a.map(h=>this.applyJoinAliasMappers(h,s)):a&&typeof a=="object"&&(c=this.applyJoinAliasMappers(a,s)),c=Array.isArray(c)?c.map(h=>this.runMapper(i,h)):this.runMapper(i,c),c!==a&&(r===e&&(r={...r}),r[i]=c);}return r}mapInboundResult(e,t,r){let n=Array.isArray(r?.joins)?r.joins:[],i=s=>{let a=this.applyJoinAliasMappers(s,n);return this.runMapper(e,a)};return Array.isArray(t)?t.map(s=>i(s)):i(t)}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||typeof e!="object")return e;let t=e,r={...t},n=i=>{let s={...i};return s.localField=this.toWireField(String(i?.localField??"")),s.foreignField=this.toWireField(String(i?.foreignField??"")),Array.isArray(i.where)&&(s.where=i.where.map(a=>this.normalizeOutboundAnyFilter(a))),Array.isArray(i.orderBy)&&(s.orderBy=i.orderBy.map(a=>({...a,field:this.toWireField(String(a?.field??""))}))),i.groupBy&&typeof i.groupBy=="object"&&Array.isArray(i.groupBy.fields)&&(s.groupBy={...i.groupBy,fields:i.groupBy.fields.map(a=>this.toWireField(String(a??"")))}),Array.isArray(i.having)&&(s.having=i.having.map(a=>({...a,field:this.toWireField(String(a?.field??""))}))),Array.isArray(i.select)&&(s.select=i.select.map(a=>this.toWireField(String(a??"")))),typeof i.distinctField=="string"&&(s.distinctField=this.toWireField(i.distinctField)),i.vectorSearch&&typeof i.vectorSearch=="object"&&(s.vectorSearch={...i.vectorSearch,field:this.toWireField(String(i.vectorSearch.field??""))}),Array.isArray(i.joins)&&(s.joins=i.joins.map(a=>n(a))),s};return Array.isArray(t.where)&&(r.where=t.where.map(i=>this.normalizeOutboundAnyFilter(i))),Array.isArray(t.orderBy)&&(r.orderBy=t.orderBy.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(r.groupBy={...t.groupBy,fields:t.groupBy.fields.map(i=>this.toWireField(String(i??"")))}),Array.isArray(t.having)&&(r.having=t.having.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),Array.isArray(t.select)&&(r.select=t.select.map(i=>this.toWireField(String(i??"")))),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(i=>n(i))),r}async timedFetch(e,t,r){let n=++this.requestTraceSeq,i=this.nowMs(),s=String(r?.method??"GET").toUpperCase(),a=this.normalizeHeaders(r?.headers),c=this.redactHeaders(a),h=r?.body,g=this.buildHttpCacheKey(s,t,a,h,r?.credentials),u=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${n} ${e} start`,{method:s,url:t,headers:c,hasBody:!!r?.body});try{if(u){let C=this.httpResponseCache.get(g);if(C)return this.logHttpTiming(`#${n} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(C,n,i,s,t,0)}let l=this.httpInFlight.get(g);if(l){let C=await l,k=this.nowMs()-i;return this.logHttpTiming(`#${n} ${e} deduped`,{method:s,url:t,networkMs:Number(k.toFixed(2))}),this.createTimedFetchTrace(C,n,i,s,t,k)}let S=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(n)}),p=this.normalizeHeaders(S),y=this.redactHeaders(p),m={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:p,withCredentials:r?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${n} ${e} request`,{method:s,url:t,headers:y,hasBody:!!r?.body});let T=s.toUpperCase(),P=(async()=>{let C=T==="GET"?await withGet(t,m):T==="PUT"?await withPut(t,h,m):T==="PATCH"?await withPatch(t,h,m):await withPost(t,h,m),k={status:Number(C?.status??0),headers:Object.fromEntries(Object.entries(C?.headers??{}).map(([Q,v])=>[Q,String(v)])),data:C?.data??{}};return u&&this.rememberHttpResponse(g,k),k})();this.httpInFlight.set(g,P);let B=await P.finally(()=>{this.httpInFlight.delete(g);}),I=this.nowMs()-i;return this.logHttpTiming(`#${n} ${e} response`,{status:B.status,networkMs:Number(I.toFixed(2))}),this.createTimedFetchTrace(B,n,i,s,t,I)}catch(l){let S=this.nowMs()-i;throw this.logHttpTiming(`#${n} ${e} failed`,{networkMs:Number(S.toFixed(2)),message:l?.message??String(l)}),l}}async parseJsonWithTiming(e,t){let r=this.nowMs(),n=await t.response.json().catch(()=>({})),i=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(i.toFixed(2)),totalMs:Number(s.toFixed(2))}),n}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:n}=new URL(this.config.endpoint),i=n==="https:",s=i?"wss":"ws",a=r||(i?"443":"80"),g=`/${String(this.config.wsPath??"/").trim().replace(/^\/+/,"").replace(/\/+$/,"")}`,u=`${s}://${t}:${a}${g}?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new K({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 ie(this,e)}generateFlareId(){return crypto.randomUUID().replace(/-/g,"").substring(0,20)}registerQueryPreset(e,t){let r=String(e??"").trim();if(!r)throw new f("Preset name is required",d.QueryFailed);if(typeof t!="function")throw new f(`Query preset "${r}" handler must be a function`,d.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 n=String(t??"").trim(),i=this.queryPresets.get(n);if(!i)throw new f(`Unknown query preset "${n}"`,d.QueryFailed);let s=i(e,r??{});if(!s||typeof s.get!="function")throw new f(`Query preset "${n}" must return a CollectionReference`,d.QueryFailed);return s}doc(e,t){let r=t??this.generateFlareId(),n=new U(this,e,r);return n.id=r,n}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.ok??r.success))throw new f(r.error??`CALL "${e}" failed`,d.QueryFailed);return r.data??r.result}async trackAnalytics(e,t={}){let r=String(e??"").trim();if(!r)throw new f("Analytics event is required",d.QueryFailed);await this.call("analytics.track",{event:r,...t});}async query(e,t={}){let r=this.normalizeOutboundQuery(t);if(typeof process<"u"&&process.versions?.node&&this.config.grpcUrl&&this.config.transport!=="ws"&&this.config.transport!=="http")try{let{runGrpcQuery:s}=await H("./grpc"),a=await s(this.config,e,r);if(a)return this.mapInboundResult(e,a,t)??[]}catch(s){this.log("gRPC query fallback to websocket",s);}let n=await this.send("query",{collection:e,query:r});return this.mapInboundResult(e,n.data,t)??[]}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 n={...t};for(let[i,s]of r){let a=n[i];if(typeof a=="string"){let c=s.embed??this.embedder;if(!c){this.log(`[vector] No embedder for field "${i}" \u2014 storing raw text`);continue}n[i]=await c(a);}}return n}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(n=>n!==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(n=>n!==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(n=>n!==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 n=e.find(i=>i.id===r.operationId);n&&this.offlineQueue.push(n);}));}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*(.*)$/),n=r?.[1],i=(r?.[2]??t).trim()||t,s=n===d.PermissionDenied||t.includes(d.PermissionDenied);return {code:n,message:i,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let r=this.subscriptionErrorHandlers.get(e);if(r)for(let n of r)try{n(t);}catch(i){this.log("Subscription error callback failed",i);}if(t.permissionDenied){let n=this.subscriptionPermissionHandlers.get(e);if(n)for(let i of n)try{i(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let 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,n,i,s={}){this.log("Creating subscription",e,t,r);let a={baseId:e,liveId:e,collection:t,docId:r,query:n,callback:i,options:s};this.activeSubscriptions.set(e,a),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(a).catch(g=>{this.log("Subscription activation failed",g);});let c=()=>{let u=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",u),this.activeSubscriptions.delete(e),this.subscriptions.delete(u),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:u}).catch(l=>this.log("Unsubscribe failed",l));},h=c;return h.unsubscribe=c,h.onError=g=>{this.subscriptionErrorHandlers.get(e)?.add(g);let u=this.subscriptionLastErrors.get(e);if(u)try{g(u);}catch(l){this.log("Subscription error callback failed",l);}return h},h.onPermissionDenied=g=>{this.subscriptionPermissionHandlers.get(e)?.add(g);let u=this.subscriptionLastErrors.get(e);if(u?.permissionDenied)try{g(u);}catch(l){this.log("Subscription permission callback failed",l);}return h},h.catch=g=>h.onError(g),h}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,n)=>{let i=uuid2(18),s={id:i,type:e,ts:Date.now(),...t};this.pendingAcks.set(i,a=>{a.type==="error"?n(new Error(`[${a.code}] ${a.message}`)):r(a);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),n(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(i)&&(this.pendingAcks.delete(i),n(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(n=>{try{n(t);}catch(i){this.log("Error listener error",i);}});let r=Array.from(this.activeSubscriptions.values()).find(n=>n.liveId===e.correlationId||n.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===d.PermissionDenied,raw:e}),e.correlationId){let n=this.pendingAcks.get(e.correlationId);n&&(n(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=Array.from(this.activeSubscriptions.values()).find(a=>a.liveId===e.subscriptionId),n=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),i=this.mapInboundResult(String(e.collection??r?.collection??""),n,r?.query),s={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(i)?i:[]};try{t(s);}catch(a){this.log("Subscription callback error",a);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r=Array.from(this.activeSubscriptions.values()).find(a=>a.liveId===e.subscriptionId),n=e.operation==="delete"?null:this.normalizeInboundData(e.data),i=e.operation==="delete"?null:this.mapInboundResult(String(e.collection??r?.collection??""),n,r?.query),s={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:i};try{t(s);}catch(a){this.log("Subscription callback error",a);}}}}};var xe=(n=>(n.Upload="upload",n.Download="download",n.Delete="delete",n.Edit="edit",n))(xe||{}),Fe=o=>o==="guest"?"auth == null":o==="auth"?"auth != null":"true",Be=(o,e)=>{let t=String(e??"").trim();return t?o==="true"?t:`(${o}) && (${t})`:o},Oe=o=>{let e=String(o??"").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:de(t[1]),condition:t[2].trim()};let r=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return r?{auth:de(r[1]),condition:r[2].trim()}:{auth:"any",condition:e}},de=o=>{let e=String(o??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},Kt=o=>{let e={};for(let t of o){let r=String(t.collection||"").trim();if(!r)continue;let n=r==="any"?"*":r,i=Be(Fe(t.auth),t.condition);e[n]={".read":t.permissions.includes("read")?i:"false",".create":t.permissions.includes("create")?i:"false",".update":t.permissions.includes("update")?i:"false",".delete":t.permissions.includes("delete")?i:"false"};}return e},Jt=o=>Object.entries(o).map(([e,t],r)=>{let n=t?.[".read"],i=t?.[".create"],s=t?.[".update"],a=t?.[".delete"],c=t?.[".write"],h=[];typeof n=="string"&&n.trim()!=="false"&&h.push("read");let g=typeof i=="string"&&i.trim()!=="false"||typeof c=="string"&&c.trim()!=="false",u=typeof s=="string"&&s.trim()!=="false"||typeof c=="string"&&c.trim()!=="false",l=typeof a=="string"&&a.trim()!=="false"||typeof c=="string"&&c.trim()!=="false";g&&h.push("create"),u&&h.push("update"),l&&h.push("delete");let p=Oe(n||i||s||a||c);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:p.auth,collection:e==="*"?"any":e,condition:p.condition,permissions:h}});var Ee=4*1024*1024;function se(o){return String(o??"").trim().replace(/^\/+|\/+$/g,"")}function Me(...o){return o.map(se).filter(e=>e.length>0).join("/")}var G=class{concurrency;running=0;queue=[];constructor(e){this.concurrency=Math.max(1,Math.floor(e||1));}run(e){return new Promise((t,r)=>{let n=()=>{this.running+=1,e().then(t).catch(r).finally(()=>{this.running-=1;let i=this.queue.shift();i&&i();});};this.running<this.concurrency?n():this.queue.push(n);})}};function z(o){if(typeof Buffer<"u")return Buffer.from(o).toString("base64");let e="";for(let t=0;t<o.length;t++)e+=String.fromCharCode(o[t]);return btoa(e)}async function je(o){if(o===void 0)return "";if(typeof o=="string")return z(new TextEncoder().encode(o));if(o instanceof Uint8Array)return z(o);if(o instanceof ArrayBuffer)return z(new Uint8Array(o));let e=await o.arrayBuffer();return z(new Uint8Array(e))}function De(o){let e=o.trim().replace(/\s+/g,"");if(!e)return 0;let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.max(0,Math.floor(e.length*3/4)-t)}function he(o){return o===void 0?0:typeof o=="string"?new TextEncoder().encode(o).length:o instanceof Uint8Array||o instanceof ArrayBuffer?o.byteLength:o.size}async function Ne(o,e,t,r,n){let i={};if(r&&r.trim()&&(i["Content-Type"]=r),n&&typeof XMLHttpRequest<"u")return new Promise((h,g)=>{let u=new XMLHttpRequest;u.open(e,o);for(let[S,p]of Object.entries(i))u.setRequestHeader(S,p);let l=he(t);u.upload.onprogress=S=>{let p=S.lengthComputable?S.loaded:0,y=S.lengthComputable?S.total:l;n({loaded:p,total:y,percent:y>0?Math.round(p/y*100):0});},u.onload=()=>{let S={};if(u.responseText)try{S=JSON.parse(u.responseText);}catch{g(new f("Failed to parse signed upload response",d.WriteFailed));return}if(u.status>=400){let p=String(S.error_description??S.message??S.error??`HTTP ${u.status}`);g(new f(p,d.WriteFailed,S));return}n({loaded:l,total:l,percent:100}),h(S);},u.onerror=()=>g(new f("Network error during signed upload",d.WriteFailed)),u.send(t);});let s=await fetch(o,{method:e,headers:i,body:t}),a=await s.text(),c={};if(a)try{c=JSON.parse(a);}catch{throw new f("Failed to parse signed upload response",d.WriteFailed)}if(!s.ok){let h=String(c.error_description??c.message??c.error??`HTTP ${s.status}`);throw new f(h,d.WriteFailed,c)}return c}function Qe(o){return btoa?btoa(String(o)):Buffer.from(String(o)).toString("base64")}function Ue(o){try{let e=typeof atob<"u"?atob(o):Buffer.from(o,"base64").toString(),t=parseInt(e,10);return isNaN(t)?0:t}catch{return 0}}var L=class{_t;_transferEnabled;_uploadLimiter;_downloadLimiter;_bucketCache=new Map;_bucketListLoaded=false;_bucketListPromise=null;constructor(e){this._t=e;let t=e.transferManager;this._transferEnabled=t?.enabled!==false,this._uploadLimiter=new G(t?.uploadConcurrency??1),this._downloadLimiter=new G(t?.downloadConcurrency??1);}_scheduleUpload(e){return this._transferEnabled?this._uploadLimiter.run(e):e()}_scheduleDownload(e){return this._transferEnabled?this._downloadLimiter.run(e):e()}_normalizeBucketName(e){let t=String(e??"").trim();if(!t||t==="undefined"||t==="null")throw new f("bucket name is required",d.WriteFailed);if(t.includes("/"))throw new f(`Invalid bucket name "${t}". Bucket names must not contain '/'. Use a stable bucket name (for example "taskboard") and put board/task folders in key (for example "${this._t.appId}/attachments/file.png").`,d.WriteFailed);return t}_storageHomeBucket(){return se(this._t.storageRulesHomeBucket??"")||void 0}_resolveStorageBucketName(e){let t=this._normalizeBucketName(e),r=this._storageHomeBucket();return !r||t===r?t:r}_storageObjectPath(e,t){let r=se(t),n=this._storageHomeBucket(),i=this._normalizeBucketName(e);return !n||i===n?r:Me(i,r)}async _ensureBuckets(){if(!this._bucketListLoaded)return this._bucketListPromise||(this._bucketListPromise=this._loadBuckets().then(()=>{this._bucketListLoaded=true;}).catch(e=>{throw this._bucketListPromise=null,e}).finally(()=>{this._bucketListPromise=null;})),this._bucketListPromise}async _loadBuckets(){let e=await this.listBuckets();for(let t of e)this._bucketCache.set(t.bucket,t.id);}_invalidateBucketCache(){this._bucketCache.clear(),this._bucketListLoaded=false,this._bucketListPromise=null;}async _resolveBucketId(e,t){let r=this._normalizeBucketName(e),n=this._resolveStorageBucketName(r),i=this._bucketCache.get(n);if(i)return i;if(t){try{await this._ensureBuckets();let c=this._bucketCache.get(n);if(c)return c}catch{}return (await this.createBucket(n)).id}await this._ensureBuckets();let s=this._bucketCache.get(n);if(s)return s;throw new f(`Bucket "${r}" not found. Create it first with createBucket("${r}").`,d.NotFound)}_appPath(e){return `/system/apps/${encodeURIComponent(this._t.appId)}${e}`}_bucketStreamCollection(){return "storage.buckets"}_objectStreamCollection(e){return `storage.objects.${e}`}_subscribeStorage(e,t,r={skipSnapshot:true}){let n=uuid2(18);return this._t.subscribe(n,e,void 0,void 0,t,r)}async createBucket(e,t={}){let r=this._normalizeBucketName(e),n=this._bucketCache.get(r);if(n)return {id:n,name:r,bucket:r,kind:t.kind??"managed",prefix:t.prefix};let i={name:r,kind:t.kind??"managed",bucket:r,prefix:t.prefix??"",region:t.region,endpoint:t.endpoint,accessKey:t.accessKey,secretKey:t.secretKey,dataDir:t.dataDir,forcePathStyle:t.forcePathStyle},s;try{s=await this._t.call("storage.bucket.create",i);}catch(c){if((c instanceof Error?c.message:String(c)).includes("bucket_conflict")){this._invalidateBucketCache();let u=(await this._listBucketsRaw()).find(l=>l.bucket===r||l.name===r);if(u)return this._bucketCache.set(r,u.id),u}throw c}let a={id:String(s.serverId??""),name:r,bucket:r,kind:t.kind??"managed",prefix:t.prefix};return this._bucketCache.set(r,a.id),a}async _listBucketsRaw(){let e=await this._t.call("storage.bucket.list");return (Array.isArray(e.servers)?e.servers:[]).map(r=>({id:String(r.id??r._id??""),name:String(r.name??r.bucket??""),bucket:String(r.bucket??""),kind:String(r.kind??"managed"),region:r.region?String(r.region):void 0,endpoint:r.endpoint?String(r.endpoint):void 0,prefix:r.prefix?String(r.prefix):void 0,frozen:!!r.frozen,readOnly:!!r.readOnly,createdAt:r.createdAt,updatedAt:r.updatedAt}))}async listBuckets(){let e=await this._listBucketsRaw();this._bucketCache.clear();for(let t of e)this._bucketCache.set(t.bucket,t.id);return this._bucketListLoaded=true,e}async deleteBucket(e){let t=await this._resolveBucketId(e,false),r=await this._t.call("storage.bucket.delete",{serverId:t});return this._bucketCache.delete(e),{ok:!!(r.ok??true),removedObjects:Number(r.removedObjects??0)}}async deleteBuckets(e){let t=[],r={};return await Promise.all(e.map(async n=>{try{await this.deleteBucket(n),t.push(n);}catch(i){r[n]=i instanceof Error?i.message:String(i);}})),{ok:Object.keys(r).length===0,deleted:t,errors:r}}async getBucketLocation(e){let r=(await this.listBuckets()).find(n=>n.bucket===e||n.name===e);if(!r)throw new f(`Bucket "${e}" not found`,d.NotFound);return {bucket:r.bucket,kind:r.kind,region:r.region,endpoint:r.endpoint}}onBucketAdded(e){return this._subscribeStorage(this._bucketStreamCollection(),t=>{if(t?.type==="change"&&t.operation==="insert"&&t.data){let r=t.data;e({id:String(r.id??t.docId??""),name:String(r.name??r.bucket??""),bucket:String(r.bucket??""),kind:String(r.kind??"managed"),prefix:r.prefix?String(r.prefix):void 0},String(t.docId??r.id??""));}})}onBucketUpdated(e){return this._subscribeStorage(this._bucketStreamCollection(),t=>{if(t?.type==="change"&&(t.operation==="update"||t.operation==="replace")&&t.data){let r=t.data;e({id:String(r.id??t.docId??""),name:String(r.name??r.bucket??""),bucket:String(r.bucket??""),kind:String(r.kind??"managed"),prefix:r.prefix?String(r.prefix):void 0,region:r.region?String(r.region):void 0,endpoint:r.endpoint?String(r.endpoint):void 0,frozen:!!r.frozen,readOnly:!!r.readOnly},String(t.docId??r.id??""));}})}onBucketDeleted(e){return this._subscribeStorage(this._bucketStreamCollection(),t=>{t?.type==="change"&&t.operation==="delete"&&e(String(t.docId??""));})}async putBucketPolicy(e){let t=await this._t.doPost("putBucketPolicy",this._appPath(""),{settings:{...e.rules?{storageRules:e.rules}:{},...typeof e.rulesDsl=="string"?{storageRulesDsl:e.rulesDsl}:{},...e.rulesHistoryPolicy?{storageRulesHistoryPolicy:e.rulesHistoryPolicy}:{}}});return {id:String(t.id??this._t.appId)}}async getBucketPolicy(){return {rulesDsl:void 0,rules:void 0,policy:(await this._t.doGet("getBucketPolicy",this._appPath("/storage/rules/history"))).policy??{}}}async putBucketCors(e,t){return {ok:true}}setBucketCors=this.putBucketCors;async rulesHistory(){let e=await this._t.doGet("rulesHistory",this._appPath("/storage/rules/history"));return {history:Array.isArray(e.history)?e.history:[],policy:e.policy??{maxEntries:30,maxAgeDays:365},restoreEvents:Array.isArray(e.restoreEvents)?e.restoreEvents:[]}}async putObject(e){return this._scheduleUpload(async()=>{let t=await this._resolveBucketId(e.bucket,true),r=this._storageObjectPath(e.bucket,e.key),n=e.encrypt??false,i=e.access??"public",s=typeof e.base64MaxBytes=="number"&&e.base64MaxBytes>0?Math.floor(e.base64MaxBytes):Ee,a=he(e.body),c=e.contentBase64?De(e.contentBase64):0,h=e.contentBase64?c:a,g=!!e.contentBase64||e.base64===true&&e.body!==void 0&&h<=s,u;if(g){let l;if(e.contentBase64)l=e.contentBase64;else if(e.body!==void 0)l=await je(e.body);else throw new f("putObject: body or contentBase64 is required",d.WriteFailed);let S={serverId:t,path:r,contentBase64:l,contentType:e.contentType,access:i,encrypt:n};u=e.onProgress?await this._t.doPostWithProgress("putObject",this._appPath("/storage/object/upload"),S,e.onProgress):await this._t.doPost("putObject",this._appPath("/storage/object/upload"),S);}else {if(e.body===void 0)throw new f("putObject: body is required for raw upload path",d.WriteFailed);let l=await this.createSignedUrl({bucket:e.bucket,key:r,action:"upload",sizeBytes:h,contentType:e.contentType,access:i,encrypt:n});u=await Ne(l.url,l.method||"PUT",e.body,e.contentType,e.onProgress);}return {ok:!!(u.ok??true),bucket:e.bucket,key:String(u.path??r),access:String(u.access??i),type:typeof u.type=="string"?u.type:typeof u.contentType=="string"?u.contentType:e.contentType,contentType:typeof u.contentType=="string"?u.contentType:typeof u.type=="string"?u.type:e.contentType,url:typeof u.url=="string"?u.url:void 0,size:Number(u.size??0),encrypted:!!u.encrypted}})}async getObject(e){return this._scheduleDownload(async()=>{let t=await this._resolveBucketId(e.bucket,false),r=this._storageObjectPath(e.bucket,e.key),n=await this._t.doPost("getObject",this._appPath("/storage/object/download"),{serverId:t,path:r,decrypt:e.decrypt});return {ok:!!(n.ok??true),bucket:e.bucket,key:String(n.path??r),contentBase64:String(n.contentBase64??""),contentType:String(n.contentType??"application/octet-stream"),size:Number(n.size??0),encrypted:!!n.encrypted}})}async getObjectUrl(e){return (await this.createSignedUrl({bucket:e.bucket,key:this._storageObjectPath(e.bucket,e.key),action:"download",decrypt:e.decrypt,expiresInSeconds:e.expiresInSeconds,forceDownload:e.forceDownload,allowedOrigins:e.allowedOrigins,embedOnly:e.embedOnly})).url}async downloadObject(e){let t=e.forceDownload??true,r=await this.getObjectUrl({...e,forceDownload:t}),n=e.filename??String(e.key??"").split("/").pop()??"download";if(typeof document>"u")return {ok:true,url:r,filename:n,triggered:false};let i=document.createElement("a");return i.href=r,e.openInNewTab?i.target="_blank":i.download=n,i.rel="noopener noreferrer",document.body.appendChild(i),i.click(),i.remove(),{ok:true,url:r,filename:n,triggered:true}}async headObject(e){let t=await this._resolveBucketId(e.bucket,false),r=this._storageObjectPath(e.bucket,e.key),n=await this._t.doPost("headObject",this._appPath("/storage/object/head"),{serverId:t,path:r});return {bucket:e.bucket,key:String(n.path??r),size:Number(n.size??0),contentType:String(n.contentType??"application/octet-stream"),access:typeof n.access=="string"?n.access:void 0,url:typeof n.url=="string"?n.url:void 0,encrypted:!!n.encrypted,createdAt:n.createdAt,updatedAt:n.updatedAt}}async headObjects(e){return Promise.all(e.keys.map(t=>this.headObject({bucket:e.bucket,key:t})))}async listObjects(e){let t=await this._resolveBucketId(e.bucket,false),r=this._storageObjectPath(e.bucket,e.prefix??""),n=e.cursor?Ue(e.cursor):0,i=Math.max(1,Math.min(e.limit??100,1e3)),s=await this._t.doPost("listObjects",this._appPath("/storage/object/list"),{serverId:t,prefix:r,limit:i,skip:n}),a=Array.isArray(s.objects)?s.objects:[],c=!!s.hasMore,h=Number(s.count??a.length),g=n+a.length;return {bucket:e.bucket,objects:a.map(u=>({bucket:e.bucket,key:String(u.path??u.key??""),size:Number(u.size??0),contentType:String(u.contentType??"application/octet-stream"),access:typeof u.access=="string"?u.access:void 0,url:typeof u.url=="string"?u.url:void 0,encrypted:!!u.encrypted,createdAt:u.createdAt,updatedAt:u.updatedAt})),count:h,hasMore:c,cursor:c?Qe(g):void 0}}async copyObject(e){let[t,r]=await Promise.all([this._resolveBucketId(e.sourceBucket,false),this._resolveBucketId(e.destBucket,true)]);return {ok:!!((await this._t.doPost("copyObject",this._appPath("/storage/object/copy"),{serverId:t,path:this._storageObjectPath(e.sourceBucket,e.sourceKey),destServerId:r,destPath:this._storageObjectPath(e.destBucket,e.destKey)})).ok??true)}}async copyObjects(e){let t={};return await Promise.all(e.map(async r=>{try{await this.copyObject(r);}catch(n){let i=`${r.sourceBucket}/${r.sourceKey}`;t[i]=n instanceof Error?n.message:String(n);}})),{ok:Object.keys(t).length===0,errors:t}}async deleteObject(e){let t=await this._resolveBucketId(e.bucket,false);return {ok:!!((await this._t.doPost("deleteObject",this._appPath("/storage/object/delete"),{serverId:t,path:this._storageObjectPath(e.bucket,e.key)})).ok??true)}}async deleteObjects(e){let t=await this._resolveBucketId(e.bucket,false),r=await this._t.doPost("deleteObjects",this._appPath("/storage/object/delete-many"),{serverId:t,paths:e.keys.map(s=>this._storageObjectPath(e.bucket,s))}),n=Array.isArray(r.deleted)?r.deleted:e.keys,i=r.errors??{};return {ok:!!(r.ok??true),deleted:n,errors:i}}onObjectAdded(e,t){return this._subscribeStorage(this._objectStreamCollection(e),r=>{if(r?.type==="change"&&r.operation==="insert"&&r.data){let n=r.data,i=String(n.key??n.path??r.docId??"");t({bucket:e,key:i,size:Number(n.size??0),contentType:String(n.contentType??"application/octet-stream"),encrypted:!!n.encrypted,createdAt:n.createdAt,updatedAt:n.updatedAt},i);}})}onObjectUpdated(e,t){return this._subscribeStorage(this._objectStreamCollection(e),r=>{if(r?.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data){let n=r.data,i=String(n.key??n.path??r.docId??"");t({bucket:e,key:i,size:Number(n.size??0),contentType:String(n.contentType??"application/octet-stream"),encrypted:!!n.encrypted,createdAt:n.createdAt,updatedAt:n.updatedAt},i);}})}onObjectDeleted(e,t){return this._subscribeStorage(this._objectStreamCollection(e),r=>{r?.type==="change"&&r.operation==="delete"&&t(String(r.docId??""));})}async createSignedUrl(e){let t=await this._resolveBucketId(e.bucket,false);return await this._t.doPost("createSignedUrl",this._appPath("/storage/signed-url"),{serverId:t,path:this._storageObjectPath(e.bucket,e.key),action:e.action,expiresInSeconds:e.expiresInSeconds,sizeBytes:e.sizeBytes,contentType:e.contentType,access:e.access,encrypt:e.encrypt,decrypt:e.decrypt,forceDownload:e.forceDownload,allowedOrigins:e.allowedOrigins,embedOnly:e.embedOnly})}};var V=class o extends J{static AUTH_TRACE_STORAGE_KEY="zuzjs.flare.auth.trace";pushServiceWorkerInitPromise;userId;authToken;authTicket;authConfig;authStateListeners=[];authConfigListeners=[];authSession=null;currentProfile=void 0;authBootstrapAttempted=false;authBootstrapPromise;socketAuthSyncPromise;authGuard;csrfToken;csrfBootstrapAttempted=false;csrfInitPromise;_storageService=null;isAuthTraceEnabled(){let e=globalThis?.__FLARE_AUTH_TRACE__;if(e===true||e===false)return e;if(typeof window<"u")try{let r=window.localStorage.getItem(o.AUTH_TRACE_STORAGE_KEY);if(r==="1"||r==="true")return !0;if(r==="0"||r==="false")return !1}catch{}let t=globalThis?.process?.env?.FLARE_AUTH_TRACE;return t==="1"||t==="true"}traceAuth(e,t){if(!this.isAuthTraceEnabled()||typeof console>"u")return;let r={event:e,appId:this.config.appId,ts:Date.now(),uid:this.authSession?.uid??this.userId??null,hasAccessToken:!!this.authSession?.accessToken,hasRefreshToken:!!this.authSession?.refreshToken,...t??{}};console.info("[FLARE_AUTH_TRACE]",r);}setAuthTrace(e,t=true){if(globalThis.__FLARE_AUTH_TRACE__=e,t&&typeof window<"u")try{window.localStorage.setItem(o.AUTH_TRACE_STORAGE_KEY,e?"1":"0");}catch{}}async fetchAuthMe(e){let t=this.getHttpBase(),r=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&r.set("apiKey",this.config.apiKey);let n=`${t}/auth/me?${r.toString()}`,i=await this.timedFetch("fetchAuthMe",n,{credentials:"include",headers:{...e?{Authorization:`Bearer ${e}`}:{},...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",d.QueryFailed),s}isBootstrapAttempted(){return this.authBootstrapAttempted}async hydrateAuthState(e,t){let r=t?.source??"hydrateAuthState";if(!e){this.setAuthSession(null,`${r}.clear`);return}let n=e.uid??e.id??e?.sub??null;if(!n||typeof n!="string"){this.traceAuth("hydrateAuthState.skipped",{source:r,reason:"missing_uid"});return}let i={...this.currentProfile??{},...e.profile??{},...e,uid:n,id:n};this.currentProfile=i,t?.markBootstrapAttempted!==false&&(this.authBootstrapAttempted=true),typeof e.ticket=="string"&&e.ticket.length>0&&(this.authTicket=e.ticket,this.traceAuth("hydrateAuthState.ticket_captured",{source:r}),await this.syncSocketAuth(this.authTicket).catch(()=>{}),this.traceAuth("hydrateAuthState.completed",{source:r,uid:n}),this.emitAuthState());typeof e.accessToken=="string"&&e.accessToken.length>0;this.getAuthTicket();await this.syncSocketAuth(null);}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()}`,n=await this.timedFetch("loadAuthConfig",r,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("loadAuthConfig",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to load auth config",d.QueryFailed),this.authConfig=i,this.csrfToken=this.extractCsrfToken(i,n.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(a){this.log("Auth config listener error",a);}}),this.authConfig}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.config.authBootstrapMode??"refresh",r=(()=>{try{return !!this.getHttpBase()}catch{return false}})(),n=()=>{try{let a=this.authSession?{...this.authSession,...this.currentProfile??{}}:this.currentProfile&&typeof this.currentProfile.uid=="string"?this.currentProfile:null;e(a);}catch(a){this.log("Auth state listener error during initialization",a);}},i=t==="refresh"&&!this.authSession&&!this.authBootstrapAttempted&&typeof window<"u"&&typeof document<"u"&&r,s=!this.authSession&&!!this.authBootstrapPromise;return i?(this.traceAuth("onAuthStateChanged.bootstrap.start",{listenerCount:this.authStateListeners.length}),this.authBootstrapAttempted=true,this.authBootstrapPromise||(this.authBootstrapPromise=this.refreshAuthSession().catch(()=>null).then(()=>{}).finally(()=>{this.authBootstrapPromise=void 0;})),this.authBootstrapPromise.finally(()=>{this.authStateListeners.includes(e)&&(this.traceAuth("onAuthStateChanged.bootstrap.done",{hasSession:!!this.authSession}),this.authSession||n());})):s?(this.traceAuth("onAuthStateChanged.bootstrap.wait",{listenerCount:this.authStateListeners.length}),this.authBootstrapPromise?.finally(()=>{this.authStateListeners.includes(e)&&(this.authSession||n());})):n(),()=>{this.authStateListeners=this.authStateListeners.filter(a=>a!==e);}}getCurrentUser(){return this.currentProfile}getAuthTicket(){return this.authTicket}consumeAuthTicket(){let e=this.authTicket;return this.authTicket=void 0,e}getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}extractCsrfToken(e,t){let r=e,n=typeof r?.csrfToken=="string"?String(r.csrfToken):typeof r?.csrf_token=="string"?String(r.csrf_token):void 0;if(n)return n;if(!t)return;let i=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof i=="string"&&i.length>0?i:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return getCookie(this.getCsrfCookieName())??this.csrfToken??null}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()}));}setAuthSession(e,t="unknown"){let r=this.authSession?.uid??this.userId??null;this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid,this.traceAuth("setAuthSession",{source:t,nextUid:e.uid,previousUid:r,mode:"set"})):(this.traceAuth("setAuthSession",{source:t,nextUid:null,previousUid:r,mode:"clear"}),this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear()),this.emitAuthState();}emitAuthState(){let e=this.authSession?{...this.authSession,...this.currentProfile??{}}:this.currentProfile&&typeof this.currentProfile.uid=="string"?this.currentProfile:null;this.authStateListeners.forEach(t=>{try{t(e);}catch(r){this.log("Auth state listener error",r);}});}setProfile(e){this.currentProfile=e;}async ensureSessionForSocketAuth(e){if(this.authSession?.accessToken&&this.authSession?.uid)return true;if(this.isConnected&&this.getAuthTicket())try{if(await this.syncSocketAuth(null),this.socketAuthUid!=="anon")return this.traceAuth("ensureSessionForSocketAuth.ticket",{reason:e,socketAuthUid:this.socketAuthUid}),!0}catch{}let t=(()=>{try{return !!this.getHttpBase()}catch{return false}})(),r=this.currentProfile?.uid;if(!t||!r)return false;this.traceAuth("ensureSessionForSocketAuth.start",{reason:e,hasInFlightBootstrap:!!this.authBootstrapPromise,profileUid:r}),this.authBootstrapPromise||(this.authBootstrapPromise=this.refreshAuthSession().catch(()=>null).then(()=>{}).finally(()=>{this.authBootstrapPromise=void 0;})),await this.authBootstrapPromise;let n=!!(this.authSession?.accessToken&&this.authSession?.uid);return this.traceAuth("ensureSessionForSocketAuth.done",{reason:e,hasSession:n,sessionUid:this.authSession?.uid??null}),n}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection(),this.traceAuth("refreshAuthSession.start",{providedRefreshToken:!!e,hasSessionBefore:!!this.authSession});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}:{}})}),n=await this.parseJsonWithTiming("refreshAuthSession",r);if(!r.response.ok){if(r.response.status===401)return this.traceAuth("refreshAuthSession.response",{status:r.response.status,ok:false,reason:"unauthorized"}),this.setAuthSession(null,"refreshAuthSession.401"),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(n,"Failed to refresh auth session",d.AuthenticationFailed);}let i=String(n.access_token??"");if(!i)throw new f("Refresh succeeded but no access token was returned",d.ParseError);let s=await this.fetchAuthMe(i).catch(()=>null),a={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:i,refreshToken:n.refresh_token?String(n.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.traceAuth("refreshAuthSession.response",{status:r.response.status,ok:true,nextUid:a.uid,hasProfile:!!s}),this.setAuthSession(a,"refreshAuthSession.success"),typeof window<"u"&&await this.syncSocketAuth(i).catch(()=>{}),a}async updateSocketIdentity(e,t=false){let r=typeof e=="string"&&e.length>0?e:"anon",n=r!==this.socketAuthUid;this.socketAuthUid=r,(n||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async waitUntilConnected(){if(!this.transport.connected)return new Promise(e=>{let t=setInterval(()=>{this.transport.connected&&(clearInterval(t),e());},50);})}async syncSocketAuth(e){let t=e||this.authTicket||this.authSession?.accessToken;if(t)return this.socketAuthSyncPromise?this.socketAuthSyncPromise:(this.socketAuthSyncPromise=(async()=>{try{await this.waitUntilConnected(),this.log("Executing socket auth with credential type:",e||this.authTicket?"ticket":"token");let r=await this.send("auth",{token:t});if(r.type!=="auth_ok")throw new f("Socket auth sync failed",d.AuthenticationFailed);if(!t||r.uid==="anon"){this.authToken=void 0,this.userId=void 0,this.authTicket=void 0,await this.updateSocketIdentity("anon");return}this.consumeAuthTicket(),this.currentProfile=r.profile,this.setAuthSession({uid:r.uid,accessToken:r.token,refreshToken:this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:this.currentProfile?.email??this.authSession?.email??null,emailVerified:typeof this.currentProfile?.email_verified=="boolean"?this.currentProfile.email_verified:this.authSession?.emailVerified},"syncSocketAuth.ticket_or_token"),await this.updateSocketIdentity(r.uid);}finally{this.socketAuthSyncPromise=void 0;}})(),this.socketAuthSyncPromise)}async beforeActivateSubscription(e){!this.isConnected||this.socketAuthUid!=="anon"||(this.authSession?.accessToken||this.getAuthTicket())&&(await this.syncSocketAuth(this.authSession?.accessToken??null).catch(()=>{}),this.socketAuthUid!=="anon")||!await this.ensureSessionForSocketAuth("beforeActivateSubscription")||this.authSession?.accessToken&&this.socketAuthUid==="anon"&&await this.syncSocketAuth(this.authSession.accessToken).catch(()=>{});}async fetchFreshTicket(){try{let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/ticket?${t.toString()}`,n=await this.timedFetch("fetchFreshTicket",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("fetchFreshTicket",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to fetch fresh ticket",d.QueryFailed),this.authTicket=i.ticket,i.ticket}catch(e){return this.log("Error fetching fresh ticket",e),null}}onConnected(){super.onConnected(),(this.authSession?.accessToken||this.getAuthTicket())&&this.syncSocketAuth(this.authSession?.accessToken??null).catch(e=>{this.log("Socket auth sync failed after connect",e);});}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4),n=t+r,i=atob(n),s=new Uint8Array(i.length);for(let a=0;a<i.length;a+=1)s[a]=i.charCodeAt(a);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),r=String(t.endpoint??"").trim(),n=String(t.keys?.p256dh??"").trim(),i=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:r,p256dh:n,auth:i});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/push/config?${t.toString()}`,n=await this.timedFetch("fetchPushSetupConfig",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("fetchPushSetupConfig",n);n.response.ok||this.throwFetchFlareError(i,"Failed to fetch push setup config",d.QueryFailed);let s=String(i.vapidPublicKey??"").trim(),a=String(i.serviceWorkerPath??"").trim();if(a.startsWith("/"))try{let h=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");h&&h!=="/"&&!a.startsWith(`${h}/`)&&(a=`${h}${a}`);}catch{}if(!s||!a)throw new f("Push setup response is missing vapidPublicKey or serviceWorkerPath",d.ParseError,i);return {vapidPublicKey:s,serviceWorkerPath:a}}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 f("Service worker URL must be same-origin with the app",d.WriteFailed);let r=t.pathname.replace(/\/[^/]*$/,"/")||"/";return await navigator.serviceWorker.register(t.pathname+t.search,{scope:r})})().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 f("Push permission can only be requested in browser runtime",d.WriteFailed);if(Notification.permission==="granted")return "granted";let e=await Notification.requestPermission();if(e!=="granted")throw new f(`Push permission is ${e}`,d.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new f("Push token acquisition can only run in browser runtime",d.WriteFailed);if(!("serviceWorker"in navigator))throw new f("Service worker is not supported in this browser",d.WriteFailed);if(!("PushManager"in window))throw new f("Push manager is not supported in this browser",d.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),r=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,n=e.subscription??await r.pushManager.getSubscription();if(e.forceResubscribe&&n&&(await n.unsubscribe().catch(()=>{}),n=null),!n){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new f("No VAPID public key available for push subscription",d.WriteFailed);n=await r.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(n),subscription:n}}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 f("Push token is required",d.WriteFailed);let n=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}:{}})}),i=await this.parseJsonWithTiming("registerPushToken",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to register push token",d.WriteFailed),{registered:!!i.registered,appId:String(i.appId??this.config.appId),uid:String(i.uid??this.authSession?.uid??""),token:String(i.token??r),...typeof i.platform=="string"?{platform:i.platform}:{}}}async unregisterPushToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=String(e??"").trim();if(!n)throw new f("Push token is required",d.WriteFailed);let i=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:n,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",d.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??n),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})}),n=await this.parseJsonWithTiming("sendPushNotification",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to send push notification",d.WriteFailed),{sent:!!n.sent,appId:String(n.appId??this.config.appId),targetCount:Number(n.targetCount??0),successCount:Number(n.successCount??0),failureCount:Number(n.failureCount??0),invalidatedTokenCount:Number(n.invalidatedTokenCount??0),dryRun:!!n.dryRun}}storage(){return this._storageService||(this._storageService=new L(this._buildStorageTransport())),this._storageService}_buildStorageTransport(){let e=this;function t(p){let y=p.includes("?"),m=new URLSearchParams;return m.set("appId",e.config.appId),e.config.apiKey&&m.set("apiKey",e.config.apiKey),`${p}${y?"&":"?"}${m.toString()}`}async function r(p=8e3){e.isConnected||(e.connect(),await new Promise((y,m)=>{if(e.isConnected){y();return}let T=e.onConnectionStateChange(P=>{P==="connected"&&(clearTimeout(A),T(),y());}),A=setTimeout(()=>{T(),m(new f("Storage bucket metadata requires an active socket connection",d.QueryFailed));},p);}));}async function n(p,y={}){if(await r(),e.socketAuthUid==="anon"&&((e.authSession?.accessToken||e.getAuthTicket())&&await e.syncSocketAuth(e.authSession?.accessToken??null).catch(()=>{}),e.socketAuthUid==="anon"&&await e.ensureSessionForSocketAuth(`storage:${p}`).catch(()=>false)&&e.authSession?.accessToken&&await e.syncSocketAuth(e.authSession.accessToken).catch(()=>{})),e.socketAuthUid==="anon")throw new f("Storage operations require an authenticated socket session",d.AuthenticationFailed);return await e.call(p,y)??{}}function i(p){try{let y=p.split(".");if(y.length<2)return null;let m=y[1].replace(/-/g,"+").replace(/_/g,"/"),T=m+"=".repeat((4-m.length%4)%4);if(typeof atob=="function")return JSON.parse(atob(T));let A=globalThis?.Buffer;return A?JSON.parse(A.from(T,"base64").toString("utf8")):null}catch{return null}}function s(p){if(!p)return false;let m=i(p)?.sid;return typeof m=="string"&&m.trim().length>0}function a(){let p=e.authSession?.accessToken;if(s(p))return p;let y=e.authConfig?.cookie?.accessTokenName??`__flare_at_${e.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`,m=getCookie(y);return s(m)?m:null}function c(){let p=a();return {...e.getCsrfHeaders(),...p?{Authorization:`Bearer ${p}`}:{}}}function h(p,y){if(y!==401)return false;let m=String(p.error??"").toLowerCase();return m==="session_expired"||m==="invalid_token"||m==="missing_token"}async function g(){return !!(await e.refreshAuthSession().catch(()=>null))?.accessToken}async function u(p,y,m){let T=e.getHttpBase();await e.ensureCsrfProtection();let A=async()=>{let I=await e.timedFetch(p,`${T}${t(y)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...c()},body:m!==null?JSON.stringify(m):void 0}),C=await e.parseJsonWithTiming(p,I);return {trace:I,json:C}},{trace:P,json:B}=await A();if(!P.response.ok&&h(B,P.response.status)&&await g()){let C=await A();P=C.trace,B=C.json;}return P.response.ok||e.throwFetchFlareError(B,`Storage ${p} failed`,d.WriteFailed),B}async function l(p,y){let m=e.getHttpBase();await e.ensureCsrfProtection();let T=async()=>{let B=await e.timedFetch(p,`${m}${t(y)}`,{method:"GET",credentials:"include",headers:c()}),I=await e.parseJsonWithTiming(p,B);return {trace:B,json:I}},{trace:A,json:P}=await T();if(!A.response.ok&&h(P,A.response.status)&&await g()){let I=await T();A=I.trace,P=I.json;}return A.response.ok||e.throwFetchFlareError(P,`Storage ${p} failed`,d.QueryFailed),P}async function S(p,y,m,T){if(typeof XMLHttpRequest>"u")return u(p,y,m);let A=e.getHttpBase();await e.ensureCsrfProtection();let P=JSON.stringify(m);return new Promise((B,I)=>{let C=new TextEncoder().encode(P).length,k=Q=>{let v=new XMLHttpRequest;v.open("POST",`${A}${t(y)}`),v.withCredentials=true,v.setRequestHeader("Content-Type","application/json");for(let[w,N]of Object.entries(c()))v.setRequestHeader(w,N);v.upload.onprogress=w=>{let N=w.lengthComputable?w.loaded:0,_=w.lengthComputable?w.total:C;T({loaded:N,total:_,percent:_>0?Math.round(N/_*100):0});},v.onload=()=>{let w={};try{w=v.responseText?JSON.parse(v.responseText):{};}catch{I(new f("Failed to parse storage response",d.WriteFailed));return}if(v.status>=400){if(Q===0&&h(w,v.status)){g().then(_=>{if(_)k(1);else {let b=String(w.error_description??w.message??w.error??`HTTP ${v.status}`);I(new f(b,d.WriteFailed));}}).catch(()=>{let _=String(w.error_description??w.message??w.error??`HTTP ${v.status}`);I(new f(_,d.WriteFailed));});return}let N=String(w.error_description??w.message??w.error??`HTTP ${v.status}`);I(new f(N,d.WriteFailed));return}T({loaded:C,total:C,percent:100}),B(w);},v.onerror=()=>I(new f("Network error during storage upload",d.WriteFailed)),v.send(P);};k(0);})}return {appId:this.config.appId,get storageRulesHomeBucket(){return e.authConfig?.storageRulesHomeBucket??void 0},transferManager:typeof this.config.storage=="object"&&this.config.storage?.transferManager?this.config.storage.transferManager:void 0,call:(p,y)=>n(p,y),subscribe:(p,y,m,T,A,P)=>e.subscribe(p,y,m,T,A,P??{}),doPost:(p,y,m)=>u(p,y,m),doGet:(p,y)=>l(p,y),doPostWithProgress:S}}putObject(e){return this.storage().putObject(e)}getObject(e){return this.storage().getObject(e)}getObjectUrl(e){return this.storage().getObjectUrl(e)}downloadObject(e){return this.storage().downloadObject(e)}headObject(e){return this.storage().headObject(e)}headObjects(e){return this.storage().headObjects(e)}listObjects(e){return this.storage().listObjects(e)}copyObject(e){return this.storage().copyObject(e)}copyObjects(e){return this.storage().copyObjects(e)}deleteObject(e){return this.storage().deleteObject(e)}deleteObjects(e){return this.storage().deleteObjects(e)}createBucket(e,t){return this.storage().createBucket(e,t)}listBuckets(){return this.storage().listBuckets()}deleteBucket(e){return this.storage().deleteBucket(e)}deleteBuckets(e){return this.storage().deleteBuckets(e)}getBucketLocation(e){return this.storage().getBucketLocation(e)}createSignedUrl(e){return this.storage().createSignedUrl(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 n=await this.fetchAuthMe(r).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:r,refreshToken:this.authSession?.refreshToken??null,email:n?.email??null,emailVerified:n?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new f("Authentication failed",d.AuthenticationFailed)}getAuthRequestContentType(){return this.config.authRequestContentType??"application/json"}buildAuthRequestBody(e){let t=this.getAuthRequestContentType();if(t==="application/json"){let n={};for(let[i,s]of Object.entries(e))s!==void 0&&(n[i]=s);return {contentType:t,body:JSON.stringify(n)}}let r=new URLSearchParams;for(let[n,i]of Object.entries(e))i!==void 0&&r.set(n,i);return {contentType:t,body:r.toString()}}async requestEmailPasswordToken(e,t,r){if(typeof process<"u"&&process.versions?.node&&this.config.grpcUrl&&this.config.transport!=="ws"&&this.config.transport!=="http")try{let{runGrpcLogin:u}=await H("./grpc"),l=await u(this.config,e,t);if(l)return {kind:"response.ok",access_token:l.token,refresh_token:l.refreshToken,expires_in:null,token_type:"Bearer",scope:r?.join(" ")??null,profile:null,provider:"credentials"}}catch(u){this.log("gRPC auth login fallback to HTTP",u);}let n=this.getHttpBase();await this.ensureCsrfProtection();let{contentType:i,body:s}=this.buildAuthRequestBody({appId:this.config.appId,client_id:this.config.apiKey??"",grant_type:"password",email:e,password:t,scope:r?.length?r.join(" "):void 0}),a=await this.timedFetch("requestEmailPasswordToken",`${n}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":i,...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:s}),c=await this.parseJsonWithTiming("requestEmailPasswordToken",a),h=typeof c.error=="string"&&c.error.trim().length>0;return (!a.response.ok||h)&&this.throwFetchFlareError(c,"Sign-in with email/password failed",d.AuthenticationFailed),{kind:typeof c.kind=="string"&&c.kind.trim().length>0?c.kind:"response.ok",access_token:String(c.access_token??""),refresh_token:c.refresh_token?String(c.refresh_token):null,expires_in:c.expires_in?Number(c.expires_in):null,token_type:String(c.token_type??"Bearer"),scope:c.scope?String(c.scope):null,profile:null,provider:"credentials"}}async signInWithEmailAndPassword(e,t,r){try{let n=await this.requestEmailPasswordToken(e,t,r?.scope),i=await this.auth(n.access_token),s=await this.fetchAuthMe(n.access_token).catch(()=>null);return this.setAuthSession({uid:i.uid,accessToken:n.access_token,refreshToken:n.refresh_token,provider:n.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",i.uid),{...i,kind:n.kind,accessToken:n.access_token,refreshToken:n.refresh_token,authToken:n}}catch(n){let i=/invalid_email|user.not.found|no user/i.test(n?.message??"");if(r?.createIfMissing&&i){let s=await this.createUserWithEmail(e,t,{scope:r.scope,signInIfAllowed:true});if(s.verification_required)throw new f("Email verification required before sign-in",d.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw n instanceof f?n:new f(n.message??"Sign-in with email/password failed",n.error??n.code??d.AuthenticationFailed,n)}}async signInWithEmail(e,t,r){return this.signInWithEmailAndPassword(e,t,r)}async createUserWithEmail(e,t,r){let n=await this.registerWithEmail(e,t,r);if(n.verification_required)return {kind:n.kind,verificationRequired:true,verification_required:true,emailSent:!!n.email_sent,email_sent:!!n.email_sent,message:typeof n.message=="string"?n.message:void 0,preview:n.preview};let i=String(n.access_token??"");if(!i)throw new f("User created but no access token returned",d.AuthenticationFailed);let s={access_token:i,refresh_token:n.refresh_token?String(n.refresh_token):null,expires_in:n.expires_in?Number(n.expires_in):null,token_type:String(n.token_type??"Bearer"),scope:n.scope?String(n.scope):null,profile:null,provider:"credentials"},a=await this.auth(i),c=await this.fetchAuthMe(i).catch(()=>null);return this.setAuthSession({uid:a.uid,accessToken:i,refreshToken:s.refresh_token,provider:"credentials",email:c?.email??e,emailVerified:c?.email_verified}),{...a,kind:typeof n.kind=="string"?n.kind:void 0,accessToken:i,access_token:i,token_type:s.token_type,expires_in:s.expires_in,refreshToken:s.refresh_token,refresh_token:s.refresh_token,scope:s.scope,expires_at:n.expires_at,sid:n.sid,authToken:s,auth_token:s,verificationRequired:false,verification_required:false,emailSent:!!n.email_sent,email_sent:!!n.email_sent,preview:n.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(n){if(!/invalid_email|user.not.found|no user/i.test(n?.message??""))throw n;let s=await this.createUserWithEmail(e,t,{scope:r?.scope,additionalParams:r?.additionalParams,signInIfAllowed:true});return s.verification_required?{kind:s.kind,verificationRequired:true,created:true,emailSent:s.emailSent,preview:s.preview}:{uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,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})}),n=await this.parseJsonWithTiming("sendEmailVerification",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to send verification email",d.AuthenticationFailed),n}async verifyEmailWithCode(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("verifyEmailWithCode",n);return n.response.ok||this.throwFetchFlareError(i,"Email verification failed",d.AuthenticationFailed),i}async confirmEmailLink(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("confirmEmailLink",n);return n.response.ok||this.throwFetchFlareError(i,"Email link verification failed",d.AuthenticationFailed),i}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})}),n=await this.parseJsonWithTiming("sendAccountRecovery",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to send recovery email",d.AuthenticationFailed),n}async recoverAccountWithCode(e,t,r){let n=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithCode",`${n}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:r,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",i);return i.response.ok||this.throwFetchFlareError(s,"Account recovery failed",d.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("recoverAccountWithToken",n);return n.response.ok||this.throwFetchFlareError(i,"Account recovery failed",d.AuthenticationFailed),i}async signIn(e,t,r){let n=typeof e?.signIn=="function",i=n?e:await this.getAuthGuard(),s=n?t:e,a=n?r:t;return i.signIn(s,a)}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",n=r?e:await this.getAuthGuard(),i=r?t:typeof e=="boolean"?e:false,s=await n.handleRedirect(i);if(!s||!s.access_token||!s.provider)return null;let a=await this.exchangeProviderToken(s.provider,s.access_token),c=await this.auth(a.token),h=await this.fetchAuthMe(a.token).catch(()=>null);return this.setAuthSession({uid:c.uid,accessToken:a.token,refreshToken:s.refresh_token,provider:s.provider,email:h?.email??null,emailVerified:h?.email_verified}),{...c,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let r=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("exchangeProviderToken",n);if(n.response.ok||this.throwFetchFlareError(i,"OAuth token exchange failed",d.AuthenticationFailed),!i?.token)throw new f("OAuth token exchange failed",d.ParseError,i);return {token:String(i.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.loadAuthConfig();if(!e.enabled)throw new f("Authentication is disabled for this app",d.AuthenticationFailed);let t=this.getHttpBase(),r=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,n=[],i=(s,a)=>({...a,token_url:r,tokenParams:{...a.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&n.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.google?.enabled&&e.providers.google.clientId&&n.push(i("google",Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&n.push(i("github",GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&n.push(i("facebook",Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&n.push(i("dropbox",Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&n.push(i("apple",Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&n.push(i("twitter",Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),n.length===0)throw new f("No authentication providers are enabled for this app",d.AuthenticationFailed);return this.authGuard=new AuthGuard({providers:n,redirectUri:e.redirectUri}),this.authGuard}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,"signOut.finally"),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,r){if(typeof process<"u"&&process.versions?.node&&this.config.grpcUrl&&this.config.transport!=="ws"&&this.config.transport!=="http")try{let{runGrpcRegister:h}=await H("./grpc"),g=await h(this.config,e,t);if(g)return {kind:"auth.registration",token_type:"Bearer",access_token:g.token,refresh_token:null,uid:g.userId,role:g.role,verification_required:!1,email_sent:!1}}catch(h){this.log("gRPC auth register fallback to HTTP",h);}let n=this.getHttpBase();await this.ensureCsrfProtection();let{contentType:i,body:s}=this.buildAuthRequestBody({appId:this.config.appId,client_id:this.config.apiKey??"",grant_type:"create_user",email:e,password:t,scope:r?.scope?.length?r.scope.join(" "):void 0,additional_params:r?.additionalParams?JSON.stringify(r.additionalParams):void 0}),a=await this.timedFetch("registerWithEmail",`${n}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":i,...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:s}),c=await this.parseJsonWithTiming("registerWithEmail",a);return !a.response.ok&&a.response.status!==202&&this.throwFetchFlareError(c,"User creation failed",d.WriteFailed),c}};var oe=class extends V{autoPushRegisteredIdentity;autoPushInProgress=false;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",n=String(t?.accessToken??"").trim(),i=r!=="anon"&&n?r:"anon";if(this.autoPushRegisteredIdentity!==i&&!this.autoPushInProgress){this.autoPushInProgress=true;try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=i;}catch(s){this.log("Auto push enable failed",s);}finally{this.autoPushInProgress=false;}}};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]});}},Y=oe;function ae(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Ve(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Z(o,e){let t=e.toLowerCase();for(let[r,n]of Object.entries(o??{}))if(r.toLowerCase()===t&&typeof n=="string")return n}function Ye(o){let e=Z(o,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,r]of Object.entries(o??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(r))return r.filter(n=>typeof n=="string");return []}function Ze(o,e){for(let t of o){let r=t.split(";").map(c=>c.trim()),[n]=r;if(!n)continue;let i=n.indexOf("=");if(i<=0)continue;let s=decodeURIComponent(n.slice(0,i)),a=n.slice(i+1);if(s===e)return decodeURIComponent(a)}}async function Xe(o){let e=new URL("/auth/config",o.endpoint);return e.searchParams.set("appId",o.appId),o.apiKey&&e.searchParams.set("apiKey",o.apiKey),await withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:o.apiKey?{"x-flare-api-key":o.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function ge(o){let e=await Xe(o),t=e?.data,r=e?.headers??{},n=Z(r,"x-flare-csrf")??Z(r,"x-csrf-token")??Z(r,"csrf-token");if(typeof n=="string"&&n.length>0)return {csrfToken:n,...t};let i=t?.cookie?.csrfTokenName,s=i&&i.length>0?i:Ve(o.appId),a=Ye(r),c=Ze(a,s);if(typeof c=="string"&&c.length>0)return {csrfToken:c,...t}}function fe(o,e,t){return `${encodeURIComponent(o)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function et(o){let e=o.proxyCookieName??ae(o.appId),t=o.proxyCookieMaxAge??3600;return async function(n){let i=await ge(o),s=i?.csrfToken,a=new Headers({"Content-Type":"application/json"});return s&&a.set("Set-Cookie",fe(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...i}),{status:200,headers:a})}}function tt(o){let e=o.proxyCookieName??ae(o.appId),t=o.proxyCookieMaxAge??3600;return async function(n,i){if(n.method!=="GET"&&n.method!=="HEAD"){i.status(405).json({error:"Method not allowed"});return}let a=(await ge(o))?.csrfToken;a&&i.setHeader("Set-Cookie",fe(e,a,t)),i.status(200).json({csrfToken:a??null});}}function rt(o,e,t){let r=t??ae(e);if(o instanceof Request){let s=(o.headers.get("cookie")??"").split(";").map(c=>c.trim()).find(c=>c.startsWith(`${encodeURIComponent(r)}=`)||c.startsWith(`${r}=`));if(!s)return null;let a=s.indexOf("=");return a>=0?decodeURIComponent(s.slice(a+1)):null}let{cookies:n}=o;return typeof n?.get=="function"?n.get(r)?.value??null:n&&typeof n=="object"?n[r]??null:null}function nt(o,e){let t={};return o&&(t["x-flare-csrf"]=o),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var Sr="ServerTimeStamp",Tr={$serverTimestamp:true};var ye=["updatedAt","createdAt","_updatedAt","_createdAt"],X=o=>{if(o==null)return null;if(o instanceof Date)return Number.isNaN(o.getTime())?null:o;if(typeof o=="number"){let e=new Date(o);return Number.isNaN(e.getTime())?null:e}if(typeof o=="string"){let e=new Date(o);return Number.isNaN(e.getTime())?null:e}if(typeof o=="object"&&"$date"in o){let e=o.$date;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(e&&typeof e=="object"&&typeof e.$numberLong=="string"){let t=Number(e.$numberLong);if(!Number.isFinite(t))return null;let r=new Date(t);return Number.isNaN(r.getTime())?null:r}}return null},Cr=(o,e="updatedAt")=>{if(!o)return null;let t=e?[e,...ye.filter(r=>r!==e)]:[...ye];for(let r of t){let n=o[r],i=X(n);if(i)return i}return null},Ar=(o,e,t)=>{let r=X(o);return r?new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short",...e}).format(r):""},it=(o,e=new Date)=>{let t=X(o),r=X(e);return !t||!r?null:t.getTime()-r.getTime()},Ir=(o,e=new Date)=>{let t=it(o,e);if(t==null)return "";let r=Math.abs(t),n=Math.floor(r/6e4),i=Math.floor(r/36e5),s=Math.floor(r/864e5);return r<3e4?"just now":n<60?t<0?`${n}m ago`:`in ${n}m`:i<24?t<0?`${i}h ago`:`in ${i}h`:t<0?`${s}d ago`:`in ${s}d`};var st=(u=>(u.authEmailNotVerified="auth/email-not-verified",u.authEmailAlreadyVerified="auth/email-already-verified",u.authInvalidToken="auth/invalid-token",u.authUserDisabled="auth/user-disabled",u.authUserNotFound="auth/user-not-found",u.authWrongPassword="auth/wrong-password",u.authEmailAlreadyInUse="auth/email-already-in-use",u.authInvalidEmail="auth/invalid-email",u.authWeakPassword="auth/weak-password",u.authTooManyRequests="auth/too-many-requests",u.authInternalError="auth/internal-error",u))(st||{});var ot=(k=>(k.health="health",k.authConfig="auth_config",k.authRegistration="auth/registration",k.authRegistrationVerificationRequired="auth/registration-verification-required",k.authSession="auth/session",k.authExchange="auth/exchange",k.authLogout="auth/logout",k.authSsrBridge="auth/ssr_bridge",k.authSsrVerify="auth/ssr_verify",k.accountRecovery="account/recovery",k.emailVerification="email/verification",k.verificationDispatch="verification/dispatch",k.authProfile="auth/profile",k.adminToken="admin/token",k.documentDelete="document/delete",k.documentsDelete="documents/delete",k.documents="documents",k.document="document",k.documentCreate="document/create",k.documentUpdate="document/update",k.oauthProviderResponse="oauth_provider_response",k.success="success",k.response="response",k))(ot||{});var O=null,W=null,ee=null,me=o=>new Proxy(o,{get(e,t,r){if(t==="onAuthStateChange")return e.onAuthStateChanged.bind(e);if(t==="onAuthConfigLoaded")return e.onAuthConfigLoaded.bind(e);let n=Reflect.get(e,t,r);return typeof n=="function"?n.bind(e):n}}),at=o=>JSON.stringify({endpoint:o.endpoint,grpcUrl:o.grpcUrl,transport:o.transport,wsPath:o.wsPath,appId:o.appId,apiKey:o.apiKey,authRequestContentType:o.authRequestContentType,publicKey:o.publicKey,autoReconnect:o.autoReconnect,reconnectDelay:o.reconnectDelay,maxReconnectDelay:o.maxReconnectDelay,dataMapperKeys:Object.keys(o.dataMapper??{}).sort()}),Er=o=>{let e=at(o),t=typeof window<"u"&&typeof document<"u",r=!t&&typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";return r?me(new Y(o)):(O&&ee!==e&&(O.disconnect(),O=null,W=null,ee=null),O||(O=new Y(o),ee=e,(t||!r)&&O.connect(),t&&O.setupPushServiceWorker().catch(()=>{}),W=me(O)),W??O)},Mr=()=>W??O,jr=()=>{O&&(O.disconnect(),O=null,W=null,ee=null);};var Dr=Y;
|
|
1
|
+
import {Credentials,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,getCookie,withGet,withPut,withPatch,withPost}from'@zuzjs/core';var f=class extends Error{constructor(t,r,n){super(t);this.code=r;this.cause=n;this.name="ZuzFlareError";}};var be={NotFound:"404",ConnectionFailed:"CONNECTION_FAILED",ConnectionTimeout:"CONNECTION_TIMEOUT",NotConnected:"NOT_CONNECTED",AuthenticationFailed:"AUTHENTICATION_FAILED",SubscriptionFailed:"SUBSCRIPTION_FAILED",PermissionDenied:"PERMISSION_DENIED",WriteFailed:"WRITE_FAILED",DeleteFailed:"DELETE_FAILED",QueryFailed:"QUERY_FAILED",Timeout:"TIMEOUT",ParseError:"PARSE_ERROR",Unknown:"UNKNOWN"},d=be;var ke=(l=>(l.SUBSCRIBE="subscribe",l.UNSUBSCRIBE="unsubscribe",l.WRITE="write",l.DELETE="delete",l.AUTH="auth",l.PING="ping",l.OFFLINE_SYNC="offline_sync",l.CALL="call",l.QUERY="query",l.PRESENCE_JOIN="presence_join",l.PRESENCE_LEAVE="presence_leave",l.PRESENCE_HEARTBEAT="presence_heartbeat",l))(ke||{}),Se=(l=>(l.SNAPSHOT="snapshot",l.CHANGE="change",l.ERROR="error",l.ACK="ack",l.PONG="pong",l.AUTH_OK="auth_ok",l.OFFLINE_ACK="offline_ack",l.CALL_RESPONSE="call_response",l.QUERY_RESULT="query_result",l.PRESENCE_STATE="presence_state",l.PRESENCE_JOIN="presence_join",l.PRESENCE_LEAVE="presence_leave",l))(Se||{});function te(o){let e=[];for(let[t,r]of Object.entries(o))if(typeof r=="string"){let n=r.match(/^(>=|<=|!=|>|<|==)\s*(.+)$/);if(n){let[,i,s]=n;e.push({field:t,op:i,value:ue(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 ue(o){if(!isNaN(Number(o)))return Number(o);if(o==="true")return true;if(o==="false")return false;if(o==="null")return null;if(o!=="undefined")return o}var D=class{constructor(e,t,r){this.client=e;this.collection=t;this.docIdFromRef=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.docIdFromRef)return this.docIdFromRef;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 f('Document ID not specified. Use .where({ id: "..." }) or doc(collection, id)',d.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,n)=>{let i=this.client.subscribe(t,this.collection,e,void 0,s=>{s.type==="snapshot"&&(i(),r(s.data));});setTimeout(()=>{i(),n(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 re=class{constructor(e,t,r){this.client=e;this.collection=t;this.id=r;}async get(){return new D(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 updateAndGet(e){return await this.update(e),this.get()}async setAndGet(e){return await this.set(e),this.get()}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,n=>{n.type==="snapshot"&&(e(n),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})}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})}},U=re;var ne=class o{constructor(e,t){this.client=e;this.collection=t;return new Proxy(this,{get:(r,n,i)=>{if(typeof n=="string"&&!(n in r)&&this.client.hasQueryPreset(n))return (a={})=>r.with(n,a);let s=Reflect.get(r,n,i);return typeof s=="function"?s.bind(r):s}})}sq={};promise;doc(e){return new U(this.client,this.collection,e)}clone(e){let t=new o(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 te(e).map(t=>this.normalizeFilter(t))}appendOperatorFilter(e,t,r,n){return this.appendFilters([this.normalizeFilter({field:e,op:t,value:r})],n)}appendAndFilters(e){return this.clone({where:[...this.sq.where??[],...e]})}toOrNode(e){return {or:e}}toAndNode(e){return {and:e}}isLeafFilter(e){return !("or"in e)&&!("and"in e)}isIdentityGuard(e){return this.isLeafFilter(e)?(e.field==="id"||e.field==="_id")&&e.op==="==":false}splitIdentityGuards(e){let t=[],r=[];for(let n of e){if(this.isIdentityGuard(n)){t.push(n);continue}r.push(n);}return {guards:t,rest:r}}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 c=r;return this.clone({where:[{or:[...c.or,...e]}]})}let{guards:i,rest:s}=this.splitIdentityGuards(t);if(i.length>0){let c=s.length===0?void 0:s.length===1?s[0]:{and:s},h=c?[{or:[c,...e]}]:[{or:[...e]}];return this.clone({where:[...i,...h]})}let a=t.length===1?t[0]:{and:t};return this.clone({where:[{or:[a,...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"}]})}newest(){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 n={from:String(e??""),localField:String(t?.source??""),foreignField:String(t?.target??""),as:String(t?.as??""),single:t?.single};return Array.isArray(t?.where)&&(n.where=t.where),Array.isArray(t?.orderBy)&&(n.orderBy=t.orderBy),typeof t?.limit=="number"&&(n.limit=t.limit),typeof t?.offset=="number"&&(n.offset=t.offset),t?.startAt&&(n.startAt=t.startAt),t?.startAfter&&(n.startAfter=t.startAfter),t?.endAt&&(n.endAt=t.endAt),t?.endBefore&&(n.endBefore=t.endBefore),Array.isArray(t?.aggregate)&&(n.aggregate=t.aggregate),t?.groupBy&&(n.groupBy=t.groupBy),Array.isArray(t?.having)&&(n.having=t.having),t?.vectorSearch&&(n.vectorSearch=t.vectorSearch),Array.isArray(t?.select)&&(n.select=t.select),typeof t?.distinctField=="string"&&(n.distinctField=t.distinctField),Array.isArray(t?.joins)&&(n.joins=t.joins.map(i=>this.buildStructuredJoin(String(i?.collection??""),i))),n}cloneStructuredJoin(e){let t={...e};return Array.isArray(e.where)&&(t.where=e.where.map(r=>({...r}))),Array.isArray(e.orderBy)&&(t.orderBy=e.orderBy.map(r=>({...r}))),Array.isArray(e.aggregate)&&(t.aggregate=e.aggregate.map(r=>({...r}))),Array.isArray(e.having)&&(t.having=e.having.map(r=>({...r}))),Array.isArray(e.select)&&(t.select=[...e.select]),e.groupBy?.fields&&(t.groupBy={fields:[...e.groupBy.fields]}),e.startAt?.values&&(t.startAt={values:[...e.startAt.values]}),e.startAfter?.values&&(t.startAfter={values:[...e.startAfter.values]}),e.endAt?.values&&(t.endAt={values:[...e.endAt.values]}),e.endBefore?.values&&(t.endBefore={values:[...e.endBefore.values]}),Array.isArray(e.joins)&&(t.joins=e.joins.map(r=>this.cloneStructuredJoin(r))),t}appendNestedJoinByAlias(e,t,r){for(let n of e){if(n.as===t)return n.joins=[...n.joins??[],r],true;if(Array.isArray(n.joins)&&this.appendNestedJoinByAlias(n.joins,t,r))return true}return false}parseRelationRef(e){let r=String(e??"").trim().match(/^([A-Za-z0-9_.]+)\s*->\s*([A-Za-z0-9_]+)\.([A-Za-z0-9_.]+)(?:\s+as\s+([A-Za-z0-9_]+))?$/i);if(!r)throw new Error(`Invalid relation format: "${e}". Expected "source.path->collection.target"`);return {source:r[1],collection:r[2],target:r[3],alias:r[4]}}join(e,t){let r=this.buildStructuredJoin(e,t);return this.clone({joins:[...this.sq.joins??[],r]})}joinNested(e,t,r){let n=String(e??"").trim();if(!n)throw new Error("joinNested requires parentAlias");let i=(this.sq.joins??[]).map(a=>this.cloneStructuredJoin(a));if(i.length===0)throw new Error(`joinNested parent alias "${n}" not found`);let s=this.buildStructuredJoin(t,r);if(!this.appendNestedJoinByAlias(i,n,s))throw new Error(`joinNested parent alias "${n}" not found`);return this.clone({joins:i})}Join(e,t){return this.join(e,t)}JoinNested(e,t,r){return this.joinNested(e,t,r)}withRelation(e,t={}){let r=this.parseRelationRef(e);return this.join(r.collection,{...t,source:r.source,target:r.target,as:t.as??r.alias??r.collection})}select(...e){return this.clone({select:e})}distinctField(e){return this.clone({distinctField:e})}vectorSearch(e){return this.clone({vectorSearch:e})}getRawQuery(){let e={...this.sq};return Array.isArray(this.sq.where)&&(e.where=this.sq.where.map(t=>({...t}))),Array.isArray(this.sq.orderBy)&&(e.orderBy=this.sq.orderBy.map(t=>({...t}))),Array.isArray(this.sq.aggregate)&&(e.aggregate=this.sq.aggregate.map(t=>({...t}))),Array.isArray(this.sq.having)&&(e.having=this.sq.having.map(t=>({...t}))),Array.isArray(this.sq.select)&&(e.select=[...this.sq.select]),Array.isArray(this.sq.joins)&&(e.joins=this.sq.joins.map(t=>this.cloneStructuredJoin(t))),this.sq.groupBy?.fields&&(e.groupBy={fields:[...this.sq.groupBy.fields]}),this.sq.startAt?.values&&(e.startAt={values:[...this.sq.startAt.values]}),this.sq.startAfter?.values&&(e.startAfter={values:[...this.sq.startAfter.values]}),this.sq.endAt?.values&&(e.endAt={values:[...this.sq.endAt.values]}),this.sq.endBefore?.values&&(e.endBefore={values:[...this.sq.endBefore.values]}),{collection:this.collection,query:e}}async get(){return this._execute()}async first(){let e=await this._execute();return e.length>0?e[0]:null}async last(){let e=await this._execute();return e.length>0?e[e.length-1]:null}_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 this.client.query(this.collection,this.sq)}async _executeSubscribe(){let e=uuid2(18);return new Promise((t,r)=>{let n=Object.keys(this.sq).length>0?this.sq:void 0,i=this.client.subscribe(e,this.collection,void 0,n,s=>{s.type==="snapshot"&&(i(),t(s.data));});setTimeout(()=>{i(),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,n=(()=>{});return n=this.client.subscribe(t,this.collection,void 0,r,i=>{i.type==="snapshot"&&(e(i),n());}),n}stream(e={}){let t=uuid2(18),r=Object.keys(this.sq).length>0?this.sq:void 0,n=new Set,i=[],s=new Map,a=Math.max(0,Number(e.flushMs??24)),c=Math.max(1,Number(e.maxBatchSize??200)),h=e.insertAt??"end",g=typeof e.maxDocs=="number"&&e.maxDocs>0?Math.floor(e.maxDocs):void 0,u=String(e.idField??"id"),l=[],S=false,p=false,y=0,m,T=()=>{s.clear();for(let b=0;b<l.length;b+=1){let F=A(l[b]);F&&s.set(F,b);}},A=(b,F)=>{if(F)return F;if(b==null)return;if(typeof e.getId=="function"){let j=e.getId(b);if(typeof j=="string"&&j.length>0)return j}let E=b?.[u]??b?._id??b?.docId;if(typeof E=="string"&&E.length>0)return E},P=()=>{g==null||l.length<=g||(l=l.slice(0,g));},B=()=>{typeof e.sort=="function"&&(l=l.slice().sort(e.sort));},I=(b,F)=>{y+=1;let E=l.slice(),j={reason:b,batchSize:F,version:y,ready:p};for(let q of Array.from(n))try{q(E,j);}catch{}},C=()=>{m!=null&&(clearTimeout(m),m=void 0);},k=b=>{if(b.operation==="delete"){let q=s.get(b.docId);if(q==null)return;l.splice(q,1),T();return}let F=b.data;if(F==null)return;let E=A(F,b.docId);if(!E)return;let j=s.get(E);if(typeof j=="number"){l[j]=F;return}h==="start"?l.unshift(F):l.push(F),P(),T();},Q=()=>{if(S||i.length===0)return;C();let b=i.splice(0,i.length);for(let F of b)k(F);B(),T(),I("change-batch",b.length);},v=()=>{S||m!=null||(m=setTimeout(Q,a));},w=this.client.subscribe(t,this.collection,void 0,r,b=>{if(!S){if(b.type==="snapshot"){l=Array.isArray(b.data)?[...b.data]:[],p=true,C(),i.length=0,B(),P(),T(),I("snapshot",0);return}if(i.push(b),i.length>=c){Q();return}v();}}),_={subscribe(b,F=true){if(n.add(b),F){let E={reason:p?"change-batch":"snapshot",batchSize:0,version:y,ready:p};try{b(l.slice(),E);}catch{}}return ()=>{n.delete(b);}},getSnapshot(){return l.slice()},isReady(){return p},getVersion(){return y},close:()=>{S||(S=true,C(),i.length=0,n.clear(),w());},onError(b){return w.onError(b),_},onPermissionDenied(b){return w.onPermissionDenied(b),_}};return _}asStore(e={}){let t=this.stream(e);return {subscribe:r=>t.subscribe(()=>{r();},false),getSnapshot:()=>t.getSnapshot(),getServerSnapshot:()=>[],stream:t,destroy:()=>{t.close();}}}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,n=>{n.type==="change"&&n.operation==="insert"&&n.data!=null&&e(n.data,n.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,n=>{n.type==="change"&&(n.operation==="update"||n.operation==="replace")&&n.data!=null&&e(n.data,n.docId);},{skipSnapshot:true})}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,n=>{n.type==="change"&&n.operation==="delete"&&e(n.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,n=>{n.type==="change"&&e(n.data??null,n.docId,n.operation);},{skipSnapshot:true})}ensureBulkOptions(e){let t=Number(e?.batchSize??250),r=Number(e?.concurrency??1);return {...e,batchSize:Number.isFinite(t)&&t>0?Math.floor(t):250,concurrency:Number.isFinite(r)&&r>0?Math.floor(r):1,continueOnError:e?.continueOnError===true}}toPercent(e,t){if(!(typeof t!="number"||t<=0))return Math.round(e/t*100)}emitBulkProgress(e,t,r){r&&r({operation:e,...t,percent:this.toPercent(t.processed,t.total)});}async*chunkIterable(e,t){let r=[];for await(let n of e)r.push(n),r.length>=t&&(yield r,r=[]);r.length>0&&(yield r);}assertBulkSignal(e){if(e?.aborted)throw new Error("Bulk write aborted")}async runChunkWorkers(e,t,r,n,i,s,a=false,c){let h=0,g,u=async()=>{for(;h<t.length;){this.assertBulkSignal(c);let S=h;h+=1;let p=t[S];try{let y=await n(p);i.succeeded+=1,i.processed+=1,this.emitBulkProgress(e,{processed:i.processed,succeeded:i.succeeded,failed:i.failed,total:i.total,lastDocId:y.docId},s);}catch(y){if(i.failed+=1,i.processed+=1,this.emitBulkProgress(e,{processed:i.processed,succeeded:i.succeeded,failed:i.failed,total:i.total,lastError:y},s),!a)throw y;g==null&&(g=y);}}},l=Math.max(1,Math.min(r,t.length));if(await Promise.all(Array.from({length:l},()=>u())),!a&&g!=null)throw g}async runBulkWrite(e,t,r,n){let i=this.ensureBulkOptions(n);this.assertBulkSignal(i.signal);let s={processed:0,succeeded:0,failed:0,total:Array.isArray(t)?t.length:void 0};this.emitBulkProgress(e,{processed:s.processed,succeeded:s.succeeded,failed:s.failed,total:s.total},i.onProgress);for await(let c of this.chunkIterable(t,i.batchSize))this.assertBulkSignal(i.signal),await this.runChunkWorkers(e,c,i.concurrency,r,s,i.onProgress,i.continueOnError,i.signal);return {operation:e,processed:s.processed,succeeded:s.succeeded,failed:s.failed,total:s.total}}async add(e){let t=uuid2(18),r=this.doc(t);return await r.set(e),r}async addMany(e,t){return this.runBulkWrite("addMany",e,async r=>{let n=uuid2(18);return await this.client.send("write",{collection:this.collection,docId:n,data:r,merge:false}),{docId:n}},t)}async updateMany(e,t){return this.runBulkWrite("updateMany",e,async r=>(await this.client.send("write",{collection:this.collection,docId:r.id,data:r.data,merge:true}),{docId:r.id}),t)}async deleteMany(e,t){return this.runBulkWrite("deleteMany",e,async r=>(await this.client.send("delete",{collection:this.collection,docId:r}),{docId:r}),t)}update(e){return new D(this.client,this.collection).update(e)}delete(){return new D(this.client,this.collection).delete()}},ie=ne;var H=o=>new Function("s","return import(s)")(o);async function Te(o){let e=o.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 i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return (globalThis.crypto??(await import('crypto')).webcrypto).subtle.importKey("spki",r.buffer,{name:"RSA-OAEP",hash:"SHA-256"},false,["encrypt"])}async function we(o,e){let t=await Te(e),r=new TextEncoder().encode(JSON.stringify(o)),i=await(globalThis.crypto??(await import('crypto')).webcrypto).subtle.encrypt({name:"RSA-OAEP"},t,r),s=typeof btoa<"u"?btoa(String.fromCharCode(...new Uint8Array(i))):Buffer.from(i).toString("base64");return JSON.stringify({enc:"rsa",data:s})}var K=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(n){this.log("Send error",n),this.messageQueue.push(e);}};this.options.publicKey?we(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 Re={id:"_id",createdAt:"_createdAt",updatedAt:"_updatedAt"},le={_id:"id",_createdAt:"createdAt",_updatedAt:"updatedAt"},J=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 n=e,i=typeof n?.error=="string"&&n.error.length>0?n.error:r,s=typeof n?.message=="string"&&n.message.length>0?n.message:t;throw new f(s,i,e)}nowMs(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}normalizeHeaders(e){if(!e)return {};let t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n]=r;});else if(Array.isArray(e))for(let[r,n]of e)t[String(r)]=String(n);else for(let[r,n]of Object.entries(e))t[String(r)]=String(n);return t}redactHeaders(e){let t={...e};for(let r of Object.keys(t)){let n=r.toLowerCase();(n==="authorization"||n==="x-flare-csrf"||n==="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(n=>this.stableStringify(n)).join(",")}]`;let t=e;return `{${Object.keys(t).sort().map(n=>`${n}:${this.stableStringify(t[n])}`).join(",")}}`}buildHttpCacheKey(e,t,r,n,i){let a=Object.entries(r).map(([h,g])=>[h.toLowerCase(),g]).sort(([h],[g])=>h.localeCompare(g)).map(([h,g])=>`${h}:${g}`).join("|"),c=this.stableStringify(n);return `${e}|${t}|${i??""}|${a}|${c}`}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,n,i,s){return {response:{status:e.status,ok:e.status>=200&&e.status<300,headers:{get:a=>{let c=a.toLowerCase();for(let[h,g]of Object.entries(e.headers))if(h.toLowerCase()===c)return String(g);return null}},json:async()=>e.data??{}},requestId:t,startedAtMs:r,networkMs:s,method:n,url:i}}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[n,i]of Object.entries(t))r.set(n,i);return r}return Array.isArray(e)?[...e,...Object.entries(t)]:{...e,...t}}toWireField(e){let t=String(e??"").trim();return t&&(Re[t]??t)}fromWireField(e){let t=String(e??"").trim();return t&&(le[t]?le[t]:t.startsWith("_")&&!t.startsWith("__")&&t.length>1?t.slice(1):t)}normalizeOutboundData(e){if(Array.isArray(e))return e.map(n=>this.normalizeOutboundData(n));if(!e||typeof e!="object")return e;let t=e,r={};for(let[n,i]of Object.entries(t))r[this.toWireField(n)]=this.normalizeOutboundData(i);return r}normalizeInboundData(e){if(Array.isArray(e))return e.map(n=>this.normalizeInboundData(n));if(!e||typeof e!="object")return e;let t=e,r={};for(let[n,i]of Object.entries(t))r[this.fromWireField(n)]=this.normalizeInboundData(i);return r}getDataMapper(e){let t=this.config.dataMapper;if(!t||typeof t!="object")return null;let r=t[e];return typeof r=="function"?r:null}runMapper(e,t){let r=this.getDataMapper(e);if(!r||t==null||typeof t!="object")return t;try{return r(t)}catch(n){return this.log(`dataMapper for "${e}" failed`,n),t}}applyJoinAliasMappers(e,t){if(!e||typeof e!="object"||!Array.isArray(t)||t.length===0)return e;let r=e;for(let n of t){let i=String(n?.as??"").trim();if(!i)continue;let s=Array.isArray(n?.joins)?n.joins:[],a=r[i],c=a;Array.isArray(a)?c=a.map(h=>this.applyJoinAliasMappers(h,s)):a&&typeof a=="object"&&(c=this.applyJoinAliasMappers(a,s)),c=Array.isArray(c)?c.map(h=>this.runMapper(i,h)):this.runMapper(i,c),c!==a&&(r===e&&(r={...r}),r[i]=c);}return r}mapInboundResult(e,t,r){let n=Array.isArray(r?.joins)?r.joins:[],i=s=>{let a=this.applyJoinAliasMappers(s,n);return this.runMapper(e,a)};return Array.isArray(t)?t.map(s=>i(s)):i(t)}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||typeof e!="object")return e;let t=e,r={...t},n=i=>{let s={...i};return s.localField=this.toWireField(String(i?.localField??"")),s.foreignField=this.toWireField(String(i?.foreignField??"")),Array.isArray(i.where)&&(s.where=i.where.map(a=>this.normalizeOutboundAnyFilter(a))),Array.isArray(i.orderBy)&&(s.orderBy=i.orderBy.map(a=>({...a,field:this.toWireField(String(a?.field??""))}))),i.groupBy&&typeof i.groupBy=="object"&&Array.isArray(i.groupBy.fields)&&(s.groupBy={...i.groupBy,fields:i.groupBy.fields.map(a=>this.toWireField(String(a??"")))}),Array.isArray(i.having)&&(s.having=i.having.map(a=>({...a,field:this.toWireField(String(a?.field??""))}))),Array.isArray(i.select)&&(s.select=i.select.map(a=>this.toWireField(String(a??"")))),typeof i.distinctField=="string"&&(s.distinctField=this.toWireField(i.distinctField)),i.vectorSearch&&typeof i.vectorSearch=="object"&&(s.vectorSearch={...i.vectorSearch,field:this.toWireField(String(i.vectorSearch.field??""))}),Array.isArray(i.joins)&&(s.joins=i.joins.map(a=>n(a))),s};return Array.isArray(t.where)&&(r.where=t.where.map(i=>this.normalizeOutboundAnyFilter(i))),Array.isArray(t.orderBy)&&(r.orderBy=t.orderBy.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),t.groupBy&&typeof t.groupBy=="object"&&Array.isArray(t.groupBy.fields)&&(r.groupBy={...t.groupBy,fields:t.groupBy.fields.map(i=>this.toWireField(String(i??"")))}),Array.isArray(t.having)&&(r.having=t.having.map(i=>({...i,field:this.toWireField(String(i?.field??""))}))),Array.isArray(t.select)&&(r.select=t.select.map(i=>this.toWireField(String(i??"")))),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(i=>n(i))),r}async timedFetch(e,t,r){let n=++this.requestTraceSeq,i=this.nowMs(),s=String(r?.method??"GET").toUpperCase(),a=this.normalizeHeaders(r?.headers),c=this.redactHeaders(a),h=r?.body,g=this.buildHttpCacheKey(s,t,a,h,r?.credentials),u=this.shouldCacheResponse(s,t);this.logHttpTiming(`#${n} ${e} start`,{method:s,url:t,headers:c,hasBody:!!r?.body});try{if(u){let C=this.httpResponseCache.get(g);if(C)return this.logHttpTiming(`#${n} ${e} cache-hit`,{method:s,url:t}),this.createTimedFetchTrace(C,n,i,s,t,0)}let l=this.httpInFlight.get(g);if(l){let C=await l,k=this.nowMs()-i;return this.logHttpTiming(`#${n} ${e} deduped`,{method:s,url:t,networkMs:Number(k.toFixed(2))}),this.createTimedFetchTrace(C,n,i,s,t,k)}let S=this.mergeHeaders(r?.headers,{"x-flare-request-id":String(n)}),p=this.normalizeHeaders(S),y=this.redactHeaders(p),m={timeout:Math.ceil((this.config.connectionTimeout??1e4)/1e3),ignoreKind:!0,headers:p,withCredentials:r?.credentials==="include",returnRawResponse:!0,appendCookiesToBody:!1,appendTimestamp:!1};this.logHttpTiming(`#${n} ${e} request`,{method:s,url:t,headers:y,hasBody:!!r?.body});let T=s.toUpperCase(),P=(async()=>{let C=T==="GET"?await withGet(t,m):T==="PUT"?await withPut(t,h,m):T==="PATCH"?await withPatch(t,h,m):await withPost(t,h,m),k={status:Number(C?.status??0),headers:Object.fromEntries(Object.entries(C?.headers??{}).map(([Q,v])=>[Q,String(v)])),data:C?.data??{}};return u&&this.rememberHttpResponse(g,k),k})();this.httpInFlight.set(g,P);let B=await P.finally(()=>{this.httpInFlight.delete(g);}),I=this.nowMs()-i;return this.logHttpTiming(`#${n} ${e} response`,{status:B.status,networkMs:Number(I.toFixed(2))}),this.createTimedFetchTrace(B,n,i,s,t,I)}catch(l){let S=this.nowMs()-i;throw this.logHttpTiming(`#${n} ${e} failed`,{networkMs:Number(S.toFixed(2)),message:l?.message??String(l)}),l}}async parseJsonWithTiming(e,t){let r=this.nowMs(),n=await t.response.json().catch(()=>({})),i=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(i.toFixed(2)),totalMs:Number(s.toFixed(2))}),n}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:n}=new URL(this.config.endpoint),i=n==="https:",s=i?"wss":"ws",a=r||(i?"443":"80"),g=`/${String(this.config.wsPath??"/").trim().replace(/^\/+/,"").replace(/\/+$/,"")}`,u=`${s}://${t}:${a}${g}?appId=${this.config.appId}${this.config.apiKey?`&apiKey=${this.config.apiKey}`:""}`;this.transport=new K({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 ie(this,e)}generateFlareId(){return crypto.randomUUID().replace(/-/g,"").substring(0,24)}registerQueryPreset(e,t){let r=String(e??"").trim();if(!r)throw new f("Preset name is required",d.QueryFailed);if(typeof t!="function")throw new f(`Query preset "${r}" handler must be a function`,d.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 n=String(t??"").trim(),i=this.queryPresets.get(n);if(!i)throw new f(`Unknown query preset "${n}"`,d.QueryFailed);let s=i(e,r??{});if(!s||typeof s.get!="function")throw new f(`Query preset "${n}" must return a CollectionReference`,d.QueryFailed);return s}doc(e,t){let r=t??this.generateFlareId(),n=new U(this,e,r);return n.id=r,n}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.ok??r.success))throw new f(r.error??`CALL "${e}" failed`,d.QueryFailed);return r.data??r.result}async trackAnalytics(e,t={}){let r=String(e??"").trim();if(!r)throw new f("Analytics event is required",d.QueryFailed);await this.call("analytics.track",{event:r,...t});}async query(e,t={}){let r=this.normalizeOutboundQuery(t);if(typeof process<"u"&&process.versions?.node&&this.config.grpcUrl&&this.config.transport!=="ws"&&this.config.transport!=="http")try{let{runGrpcQuery:s}=await H("./grpc"),a=await s(this.config,e,r);if(a)return this.mapInboundResult(e,a,t)??[]}catch(s){this.log("gRPC query fallback to websocket",s);}let n=await this.send("query",{collection:e,query:r});return this.mapInboundResult(e,n.data,t)??[]}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 n={...t};for(let[i,s]of r){let a=n[i];if(typeof a=="string"){let c=s.embed??this.embedder;if(!c){this.log(`[vector] No embedder for field "${i}" \u2014 storing raw text`);continue}n[i]=await c(a);}}return n}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(n=>n!==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(n=>n!==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(n=>n!==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 n=e.find(i=>i.id===r.operationId);n&&this.offlineQueue.push(n);}));}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*(.*)$/),n=r?.[1],i=(r?.[2]??t).trim()||t,s=n===d.PermissionDenied||t.includes(d.PermissionDenied);return {code:n,message:i,permissionDenied:s,raw:e}}emitSubscriptionError(e,t){this.subscriptionLastErrors.set(e,t);let r=this.subscriptionErrorHandlers.get(e);if(r)for(let n of r)try{n(t);}catch(i){this.log("Subscription error callback failed",i);}if(t.permissionDenied){let n=this.subscriptionPermissionHandlers.get(e);if(n)for(let i of n)try{i(t);}catch(s){this.log("Subscription permission callback failed",s);}}}async replayActiveSubscriptions(){if(!this.isConnected){this.pendingSubscriptionReplay=true;return}let e=Array.from(this.activeSubscriptions.values());if(e.length===0){this.pendingSubscriptionReplay=false;return}this.pendingSubscriptionReplay=false,this.subscriptionReplayPromise=this.subscriptionReplayPromise.then(async()=>{for(let t of e){if(!this.activeSubscriptions.has(t.baseId))continue;let 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,n,i,s={}){this.log("Creating subscription",e,t,r);let a={baseId:e,liveId:e,collection:t,docId:r,query:n,callback:i,options:s};this.activeSubscriptions.set(e,a),this.subscriptionErrorHandlers.has(e)||this.subscriptionErrorHandlers.set(e,new Set),this.subscriptionPermissionHandlers.has(e)||this.subscriptionPermissionHandlers.set(e,new Set),this.activateSubscription(a).catch(g=>{this.log("Subscription activation failed",g);});let c=()=>{let u=this.activeSubscriptions.get(e)?.liveId??e;this.log("Unsubscribing",u),this.activeSubscriptions.delete(e),this.subscriptions.delete(u),this.subscriptionErrorHandlers.delete(e),this.subscriptionPermissionHandlers.delete(e),this.subscriptionLastErrors.delete(e),this.isConnected&&this.send("unsubscribe",{subscriptionId:u}).catch(l=>this.log("Unsubscribe failed",l));},h=c;return h.unsubscribe=c,h.onError=g=>{this.subscriptionErrorHandlers.get(e)?.add(g);let u=this.subscriptionLastErrors.get(e);if(u)try{g(u);}catch(l){this.log("Subscription error callback failed",l);}return h},h.onPermissionDenied=g=>{this.subscriptionPermissionHandlers.get(e)?.add(g);let u=this.subscriptionLastErrors.get(e);if(u?.permissionDenied)try{g(u);}catch(l){this.log("Subscription permission callback failed",l);}return h},h.catch=g=>h.onError(g),h}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,n)=>{let i=uuid2(18),s={id:i,type:e,ts:Date.now(),...t};this.pendingAcks.set(i,a=>{a.type==="error"?n(new Error(`[${a.code}] ${a.message}`)):r(a);}),this.isConnected?this.transport.send(s):(this.log("Queueing message for offline",s),this.offlineQueue.push(s),n(new Error("Not connected - message queued"))),setTimeout(()=>{this.pendingAcks.has(i)&&(this.pendingAcks.delete(i),n(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(n=>{try{n(t);}catch(i){this.log("Error listener error",i);}});let r=Array.from(this.activeSubscriptions.values()).find(n=>n.liveId===e.correlationId||n.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===d.PermissionDenied,raw:e}),e.correlationId){let n=this.pendingAcks.get(e.correlationId);n&&(n(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=Array.from(this.activeSubscriptions.values()).find(a=>a.liveId===e.subscriptionId),n=this.normalizeInboundData(Array.isArray(e.data)?e.data:e.data!=null?[e.data]:[]),i=this.mapInboundResult(String(e.collection??r?.collection??""),n,r?.query),s={type:"snapshot",subscriptionId:e.subscriptionId,collection:e.collection,data:Array.isArray(i)?i:[]};try{t(s);}catch(a){this.log("Subscription callback error",a);}}return}if(e.type==="change"){let t=this.subscriptions.get(e.subscriptionId);if(t){let r=Array.from(this.activeSubscriptions.values()).find(a=>a.liveId===e.subscriptionId),n=e.operation==="delete"?null:this.normalizeInboundData(e.data),i=e.operation==="delete"?null:this.mapInboundResult(String(e.collection??r?.collection??""),n,r?.query),s={type:"change",subscriptionId:e.subscriptionId,collection:e.collection,docId:e.docId,operation:e.operation,data:i};try{t(s);}catch(a){this.log("Subscription callback error",a);}}}}};var xe=(n=>(n.Upload="upload",n.Download="download",n.Delete="delete",n.Edit="edit",n))(xe||{}),Fe=o=>o==="guest"?"auth == null":o==="auth"?"auth != null":"true",Be=(o,e)=>{let t=String(e??"").trim();return t?o==="true"?t:`(${o}) && (${t})`:o},Oe=o=>{let e=String(o??"").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:de(t[1]),condition:t[2].trim()};let r=e.match(/^(auth != null|auth == null|true)\s*&&\s*(.+)$/);return r?{auth:de(r[1]),condition:r[2].trim()}:{auth:"any",condition:e}},de=o=>{let e=String(o??"").trim();return e==="auth == null"?"guest":e==="auth != null"?"auth":"any"},Kt=o=>{let e={};for(let t of o){let r=String(t.collection||"").trim();if(!r)continue;let n=r==="any"?"*":r,i=Be(Fe(t.auth),t.condition);e[n]={".read":t.permissions.includes("read")?i:"false",".create":t.permissions.includes("create")?i:"false",".update":t.permissions.includes("update")?i:"false",".delete":t.permissions.includes("delete")?i:"false"};}return e},Jt=o=>Object.entries(o).map(([e,t],r)=>{let n=t?.[".read"],i=t?.[".create"],s=t?.[".update"],a=t?.[".delete"],c=t?.[".write"],h=[];typeof n=="string"&&n.trim()!=="false"&&h.push("read");let g=typeof i=="string"&&i.trim()!=="false"||typeof c=="string"&&c.trim()!=="false",u=typeof s=="string"&&s.trim()!=="false"||typeof c=="string"&&c.trim()!=="false",l=typeof a=="string"&&a.trim()!=="false"||typeof c=="string"&&c.trim()!=="false";g&&h.push("create"),u&&h.push("update"),l&&h.push("delete");let p=Oe(n||i||s||a||c);return {id:`${e}-${r}`,name:e==="*"?"All Collections":e,auth:p.auth,collection:e==="*"?"any":e,condition:p.condition,permissions:h}});var Ee=4*1024*1024;function se(o){return String(o??"").trim().replace(/^\/+|\/+$/g,"")}function Me(...o){return o.map(se).filter(e=>e.length>0).join("/")}var G=class{concurrency;running=0;queue=[];constructor(e){this.concurrency=Math.max(1,Math.floor(e||1));}run(e){return new Promise((t,r)=>{let n=()=>{this.running+=1,e().then(t).catch(r).finally(()=>{this.running-=1;let i=this.queue.shift();i&&i();});};this.running<this.concurrency?n():this.queue.push(n);})}};function z(o){if(typeof Buffer<"u")return Buffer.from(o).toString("base64");let e="";for(let t=0;t<o.length;t++)e+=String.fromCharCode(o[t]);return btoa(e)}async function je(o){if(o===void 0)return "";if(typeof o=="string")return z(new TextEncoder().encode(o));if(o instanceof Uint8Array)return z(o);if(o instanceof ArrayBuffer)return z(new Uint8Array(o));let e=await o.arrayBuffer();return z(new Uint8Array(e))}function De(o){let e=o.trim().replace(/\s+/g,"");if(!e)return 0;let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.max(0,Math.floor(e.length*3/4)-t)}function he(o){return o===void 0?0:typeof o=="string"?new TextEncoder().encode(o).length:o instanceof Uint8Array||o instanceof ArrayBuffer?o.byteLength:o.size}async function Ne(o,e,t,r,n){let i={};if(r&&r.trim()&&(i["Content-Type"]=r),n&&typeof XMLHttpRequest<"u")return new Promise((h,g)=>{let u=new XMLHttpRequest;u.open(e,o);for(let[S,p]of Object.entries(i))u.setRequestHeader(S,p);let l=he(t);u.upload.onprogress=S=>{let p=S.lengthComputable?S.loaded:0,y=S.lengthComputable?S.total:l;n({loaded:p,total:y,percent:y>0?Math.round(p/y*100):0});},u.onload=()=>{let S={};if(u.responseText)try{S=JSON.parse(u.responseText);}catch{g(new f("Failed to parse signed upload response",d.WriteFailed));return}if(u.status>=400){let p=String(S.error_description??S.message??S.error??`HTTP ${u.status}`);g(new f(p,d.WriteFailed,S));return}n({loaded:l,total:l,percent:100}),h(S);},u.onerror=()=>g(new f("Network error during signed upload",d.WriteFailed)),u.send(t);});let s=await fetch(o,{method:e,headers:i,body:t}),a=await s.text(),c={};if(a)try{c=JSON.parse(a);}catch{throw new f("Failed to parse signed upload response",d.WriteFailed)}if(!s.ok){let h=String(c.error_description??c.message??c.error??`HTTP ${s.status}`);throw new f(h,d.WriteFailed,c)}return c}function Qe(o){return btoa?btoa(String(o)):Buffer.from(String(o)).toString("base64")}function Ue(o){try{let e=typeof atob<"u"?atob(o):Buffer.from(o,"base64").toString(),t=parseInt(e,10);return isNaN(t)?0:t}catch{return 0}}var L=class{_t;_transferEnabled;_uploadLimiter;_downloadLimiter;_bucketCache=new Map;_bucketListLoaded=false;_bucketListPromise=null;constructor(e){this._t=e;let t=e.transferManager;this._transferEnabled=t?.enabled!==false,this._uploadLimiter=new G(t?.uploadConcurrency??1),this._downloadLimiter=new G(t?.downloadConcurrency??1);}_scheduleUpload(e){return this._transferEnabled?this._uploadLimiter.run(e):e()}_scheduleDownload(e){return this._transferEnabled?this._downloadLimiter.run(e):e()}_normalizeBucketName(e){let t=String(e??"").trim();if(!t||t==="undefined"||t==="null")throw new f("bucket name is required",d.WriteFailed);if(t.includes("/"))throw new f(`Invalid bucket name "${t}". Bucket names must not contain '/'. Use a stable bucket name (for example "taskboard") and put board/task folders in key (for example "${this._t.appId}/attachments/file.png").`,d.WriteFailed);return t}_storageHomeBucket(){return se(this._t.storageRulesHomeBucket??"")||void 0}_resolveStorageBucketName(e){let t=this._normalizeBucketName(e),r=this._storageHomeBucket();return !r||t===r?t:r}_storageObjectPath(e,t){let r=se(t),n=this._storageHomeBucket(),i=this._normalizeBucketName(e);return !n||i===n?r:Me(i,r)}async _ensureBuckets(){if(!this._bucketListLoaded)return this._bucketListPromise||(this._bucketListPromise=this._loadBuckets().then(()=>{this._bucketListLoaded=true;}).catch(e=>{throw this._bucketListPromise=null,e}).finally(()=>{this._bucketListPromise=null;})),this._bucketListPromise}async _loadBuckets(){let e=await this.listBuckets();for(let t of e)this._bucketCache.set(t.bucket,t.id);}_invalidateBucketCache(){this._bucketCache.clear(),this._bucketListLoaded=false,this._bucketListPromise=null;}async _resolveBucketId(e,t){let r=this._normalizeBucketName(e),n=this._resolveStorageBucketName(r),i=this._bucketCache.get(n);if(i)return i;if(t){try{await this._ensureBuckets();let c=this._bucketCache.get(n);if(c)return c}catch{}return (await this.createBucket(n)).id}await this._ensureBuckets();let s=this._bucketCache.get(n);if(s)return s;throw new f(`Bucket "${r}" not found. Create it first with createBucket("${r}").`,d.NotFound)}_appPath(e){return `/system/apps/${encodeURIComponent(this._t.appId)}${e}`}_bucketStreamCollection(){return "storage.buckets"}_objectStreamCollection(e){return `storage.objects.${e}`}_subscribeStorage(e,t,r={skipSnapshot:true}){let n=uuid2(18);return this._t.subscribe(n,e,void 0,void 0,t,r)}async createBucket(e,t={}){let r=this._normalizeBucketName(e),n=this._bucketCache.get(r);if(n)return {id:n,name:r,bucket:r,kind:t.kind??"managed",prefix:t.prefix};let i={name:r,kind:t.kind??"managed",bucket:r,prefix:t.prefix??"",region:t.region,endpoint:t.endpoint,accessKey:t.accessKey,secretKey:t.secretKey,dataDir:t.dataDir,forcePathStyle:t.forcePathStyle},s;try{s=await this._t.call("storage.bucket.create",i);}catch(c){if((c instanceof Error?c.message:String(c)).includes("bucket_conflict")){this._invalidateBucketCache();let u=(await this._listBucketsRaw()).find(l=>l.bucket===r||l.name===r);if(u)return this._bucketCache.set(r,u.id),u}throw c}let a={id:String(s.serverId??""),name:r,bucket:r,kind:t.kind??"managed",prefix:t.prefix};return this._bucketCache.set(r,a.id),a}async _listBucketsRaw(){let e=await this._t.call("storage.bucket.list");return (Array.isArray(e.servers)?e.servers:[]).map(r=>({id:String(r.id??r._id??""),name:String(r.name??r.bucket??""),bucket:String(r.bucket??""),kind:String(r.kind??"managed"),region:r.region?String(r.region):void 0,endpoint:r.endpoint?String(r.endpoint):void 0,prefix:r.prefix?String(r.prefix):void 0,frozen:!!r.frozen,readOnly:!!r.readOnly,createdAt:r.createdAt,updatedAt:r.updatedAt}))}async listBuckets(){let e=await this._listBucketsRaw();this._bucketCache.clear();for(let t of e)this._bucketCache.set(t.bucket,t.id);return this._bucketListLoaded=true,e}async deleteBucket(e){let t=await this._resolveBucketId(e,false),r=await this._t.call("storage.bucket.delete",{serverId:t});return this._bucketCache.delete(e),{ok:!!(r.ok??true),removedObjects:Number(r.removedObjects??0)}}async deleteBuckets(e){let t=[],r={};return await Promise.all(e.map(async n=>{try{await this.deleteBucket(n),t.push(n);}catch(i){r[n]=i instanceof Error?i.message:String(i);}})),{ok:Object.keys(r).length===0,deleted:t,errors:r}}async getBucketLocation(e){let r=(await this.listBuckets()).find(n=>n.bucket===e||n.name===e);if(!r)throw new f(`Bucket "${e}" not found`,d.NotFound);return {bucket:r.bucket,kind:r.kind,region:r.region,endpoint:r.endpoint}}onBucketAdded(e){return this._subscribeStorage(this._bucketStreamCollection(),t=>{if(t?.type==="change"&&t.operation==="insert"&&t.data){let r=t.data;e({id:String(r.id??t.docId??""),name:String(r.name??r.bucket??""),bucket:String(r.bucket??""),kind:String(r.kind??"managed"),prefix:r.prefix?String(r.prefix):void 0},String(t.docId??r.id??""));}})}onBucketUpdated(e){return this._subscribeStorage(this._bucketStreamCollection(),t=>{if(t?.type==="change"&&(t.operation==="update"||t.operation==="replace")&&t.data){let r=t.data;e({id:String(r.id??t.docId??""),name:String(r.name??r.bucket??""),bucket:String(r.bucket??""),kind:String(r.kind??"managed"),prefix:r.prefix?String(r.prefix):void 0,region:r.region?String(r.region):void 0,endpoint:r.endpoint?String(r.endpoint):void 0,frozen:!!r.frozen,readOnly:!!r.readOnly},String(t.docId??r.id??""));}})}onBucketDeleted(e){return this._subscribeStorage(this._bucketStreamCollection(),t=>{t?.type==="change"&&t.operation==="delete"&&e(String(t.docId??""));})}async putBucketPolicy(e){let t=await this._t.doPost("putBucketPolicy",this._appPath(""),{settings:{...e.rules?{storageRules:e.rules}:{},...typeof e.rulesDsl=="string"?{storageRulesDsl:e.rulesDsl}:{},...e.rulesHistoryPolicy?{storageRulesHistoryPolicy:e.rulesHistoryPolicy}:{}}});return {id:String(t.id??this._t.appId)}}async getBucketPolicy(){return {rulesDsl:void 0,rules:void 0,policy:(await this._t.doGet("getBucketPolicy",this._appPath("/storage/rules/history"))).policy??{}}}async putBucketCors(e,t){return {ok:true}}setBucketCors=this.putBucketCors;async rulesHistory(){let e=await this._t.doGet("rulesHistory",this._appPath("/storage/rules/history"));return {history:Array.isArray(e.history)?e.history:[],policy:e.policy??{maxEntries:30,maxAgeDays:365},restoreEvents:Array.isArray(e.restoreEvents)?e.restoreEvents:[]}}async putObject(e){return this._scheduleUpload(async()=>{let t=await this._resolveBucketId(e.bucket,true),r=this._storageObjectPath(e.bucket,e.key),n=e.encrypt??false,i=e.access??"public",s=typeof e.base64MaxBytes=="number"&&e.base64MaxBytes>0?Math.floor(e.base64MaxBytes):Ee,a=he(e.body),c=e.contentBase64?De(e.contentBase64):0,h=e.contentBase64?c:a,g=!!e.contentBase64||e.base64===true&&e.body!==void 0&&h<=s,u;if(g){let l;if(e.contentBase64)l=e.contentBase64;else if(e.body!==void 0)l=await je(e.body);else throw new f("putObject: body or contentBase64 is required",d.WriteFailed);let S={serverId:t,path:r,contentBase64:l,contentType:e.contentType,access:i,encrypt:n};u=e.onProgress?await this._t.doPostWithProgress("putObject",this._appPath("/storage/object/upload"),S,e.onProgress):await this._t.doPost("putObject",this._appPath("/storage/object/upload"),S);}else {if(e.body===void 0)throw new f("putObject: body is required for raw upload path",d.WriteFailed);let l=await this.createSignedUrl({bucket:e.bucket,key:r,action:"upload",sizeBytes:h,contentType:e.contentType,access:i,encrypt:n});u=await Ne(l.url,l.method||"PUT",e.body,e.contentType,e.onProgress);}return {ok:!!(u.ok??true),bucket:e.bucket,key:String(u.path??r),access:String(u.access??i),type:typeof u.type=="string"?u.type:typeof u.contentType=="string"?u.contentType:e.contentType,contentType:typeof u.contentType=="string"?u.contentType:typeof u.type=="string"?u.type:e.contentType,url:typeof u.url=="string"?u.url:void 0,size:Number(u.size??0),encrypted:!!u.encrypted}})}async getObject(e){return this._scheduleDownload(async()=>{let t=await this._resolveBucketId(e.bucket,false),r=this._storageObjectPath(e.bucket,e.key),n=await this._t.doPost("getObject",this._appPath("/storage/object/download"),{serverId:t,path:r,decrypt:e.decrypt});return {ok:!!(n.ok??true),bucket:e.bucket,key:String(n.path??r),contentBase64:String(n.contentBase64??""),contentType:String(n.contentType??"application/octet-stream"),size:Number(n.size??0),encrypted:!!n.encrypted}})}async getObjectUrl(e){return (await this.createSignedUrl({bucket:e.bucket,key:this._storageObjectPath(e.bucket,e.key),action:"download",decrypt:e.decrypt,expiresInSeconds:e.expiresInSeconds,forceDownload:e.forceDownload,allowedOrigins:e.allowedOrigins,embedOnly:e.embedOnly})).url}async downloadObject(e){let t=e.forceDownload??true,r=await this.getObjectUrl({...e,forceDownload:t}),n=e.filename??String(e.key??"").split("/").pop()??"download";if(typeof document>"u")return {ok:true,url:r,filename:n,triggered:false};let i=document.createElement("a");return i.href=r,e.openInNewTab?i.target="_blank":i.download=n,i.rel="noopener noreferrer",document.body.appendChild(i),i.click(),i.remove(),{ok:true,url:r,filename:n,triggered:true}}async headObject(e){let t=await this._resolveBucketId(e.bucket,false),r=this._storageObjectPath(e.bucket,e.key),n=await this._t.doPost("headObject",this._appPath("/storage/object/head"),{serverId:t,path:r});return {bucket:e.bucket,key:String(n.path??r),size:Number(n.size??0),contentType:String(n.contentType??"application/octet-stream"),access:typeof n.access=="string"?n.access:void 0,url:typeof n.url=="string"?n.url:void 0,encrypted:!!n.encrypted,createdAt:n.createdAt,updatedAt:n.updatedAt}}async headObjects(e){return Promise.all(e.keys.map(t=>this.headObject({bucket:e.bucket,key:t})))}async listObjects(e){let t=await this._resolveBucketId(e.bucket,false),r=this._storageObjectPath(e.bucket,e.prefix??""),n=e.cursor?Ue(e.cursor):0,i=Math.max(1,Math.min(e.limit??100,1e3)),s=await this._t.doPost("listObjects",this._appPath("/storage/object/list"),{serverId:t,prefix:r,limit:i,skip:n}),a=Array.isArray(s.objects)?s.objects:[],c=!!s.hasMore,h=Number(s.count??a.length),g=n+a.length;return {bucket:e.bucket,objects:a.map(u=>({bucket:e.bucket,key:String(u.path??u.key??""),size:Number(u.size??0),contentType:String(u.contentType??"application/octet-stream"),access:typeof u.access=="string"?u.access:void 0,url:typeof u.url=="string"?u.url:void 0,encrypted:!!u.encrypted,createdAt:u.createdAt,updatedAt:u.updatedAt})),count:h,hasMore:c,cursor:c?Qe(g):void 0}}async copyObject(e){let[t,r]=await Promise.all([this._resolveBucketId(e.sourceBucket,false),this._resolveBucketId(e.destBucket,true)]);return {ok:!!((await this._t.doPost("copyObject",this._appPath("/storage/object/copy"),{serverId:t,path:this._storageObjectPath(e.sourceBucket,e.sourceKey),destServerId:r,destPath:this._storageObjectPath(e.destBucket,e.destKey)})).ok??true)}}async copyObjects(e){let t={};return await Promise.all(e.map(async r=>{try{await this.copyObject(r);}catch(n){let i=`${r.sourceBucket}/${r.sourceKey}`;t[i]=n instanceof Error?n.message:String(n);}})),{ok:Object.keys(t).length===0,errors:t}}async deleteObject(e){let t=await this._resolveBucketId(e.bucket,false);return {ok:!!((await this._t.doPost("deleteObject",this._appPath("/storage/object/delete"),{serverId:t,path:this._storageObjectPath(e.bucket,e.key)})).ok??true)}}async deleteObjects(e){let t=await this._resolveBucketId(e.bucket,false),r=await this._t.doPost("deleteObjects",this._appPath("/storage/object/delete-many"),{serverId:t,paths:e.keys.map(s=>this._storageObjectPath(e.bucket,s))}),n=Array.isArray(r.deleted)?r.deleted:e.keys,i=r.errors??{};return {ok:!!(r.ok??true),deleted:n,errors:i}}onObjectAdded(e,t){return this._subscribeStorage(this._objectStreamCollection(e),r=>{if(r?.type==="change"&&r.operation==="insert"&&r.data){let n=r.data,i=String(n.key??n.path??r.docId??"");t({bucket:e,key:i,size:Number(n.size??0),contentType:String(n.contentType??"application/octet-stream"),encrypted:!!n.encrypted,createdAt:n.createdAt,updatedAt:n.updatedAt},i);}})}onObjectUpdated(e,t){return this._subscribeStorage(this._objectStreamCollection(e),r=>{if(r?.type==="change"&&(r.operation==="update"||r.operation==="replace")&&r.data){let n=r.data,i=String(n.key??n.path??r.docId??"");t({bucket:e,key:i,size:Number(n.size??0),contentType:String(n.contentType??"application/octet-stream"),encrypted:!!n.encrypted,createdAt:n.createdAt,updatedAt:n.updatedAt},i);}})}onObjectDeleted(e,t){return this._subscribeStorage(this._objectStreamCollection(e),r=>{r?.type==="change"&&r.operation==="delete"&&t(String(r.docId??""));})}async createSignedUrl(e){let t=await this._resolveBucketId(e.bucket,false);return await this._t.doPost("createSignedUrl",this._appPath("/storage/signed-url"),{serverId:t,path:this._storageObjectPath(e.bucket,e.key),action:e.action,expiresInSeconds:e.expiresInSeconds,sizeBytes:e.sizeBytes,contentType:e.contentType,access:e.access,encrypt:e.encrypt,decrypt:e.decrypt,forceDownload:e.forceDownload,allowedOrigins:e.allowedOrigins,embedOnly:e.embedOnly})}};var V=class o extends J{static AUTH_TRACE_STORAGE_KEY="zuzjs.flare.auth.trace";pushServiceWorkerInitPromise;userId;authToken;authTicket;authConfig;authStateListeners=[];authConfigListeners=[];authSession=null;currentProfile=void 0;authBootstrapAttempted=false;authBootstrapPromise;socketAuthSyncPromise;authGuard;csrfToken;csrfBootstrapAttempted=false;csrfInitPromise;_storageService=null;isAuthTraceEnabled(){let e=globalThis?.__FLARE_AUTH_TRACE__;if(e===true||e===false)return e;if(typeof window<"u")try{let r=window.localStorage.getItem(o.AUTH_TRACE_STORAGE_KEY);if(r==="1"||r==="true")return !0;if(r==="0"||r==="false")return !1}catch{}let t=globalThis?.process?.env?.FLARE_AUTH_TRACE;return t==="1"||t==="true"}traceAuth(e,t){if(!this.isAuthTraceEnabled()||typeof console>"u")return;let r={event:e,appId:this.config.appId,ts:Date.now(),uid:this.authSession?.uid??this.userId??null,hasAccessToken:!!this.authSession?.accessToken,hasRefreshToken:!!this.authSession?.refreshToken,...t??{}};console.info("[FLARE_AUTH_TRACE]",r);}setAuthTrace(e,t=true){if(globalThis.__FLARE_AUTH_TRACE__=e,t&&typeof window<"u")try{window.localStorage.setItem(o.AUTH_TRACE_STORAGE_KEY,e?"1":"0");}catch{}}async fetchAuthMe(e){let t=this.getHttpBase(),r=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&r.set("apiKey",this.config.apiKey);let n=`${t}/auth/me?${r.toString()}`,i=await this.timedFetch("fetchAuthMe",n,{credentials:"include",headers:{...e?{Authorization:`Bearer ${e}`}:{},...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}}),s=await this.parseJsonWithTiming("fetchAuthMe",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to fetch profile",d.QueryFailed),s}isBootstrapAttempted(){return this.authBootstrapAttempted}async hydrateAuthState(e,t){let r=t?.source??"hydrateAuthState";if(!e){this.setAuthSession(null,`${r}.clear`);return}let n=e.uid??e.id??e?.sub??null;if(!n||typeof n!="string"){this.traceAuth("hydrateAuthState.skipped",{source:r,reason:"missing_uid"});return}let i={...this.currentProfile??{},...e.profile??{},...e,uid:n,id:n};this.currentProfile=i,t?.markBootstrapAttempted!==false&&(this.authBootstrapAttempted=true),typeof e.ticket=="string"&&e.ticket.length>0&&(this.authTicket=e.ticket,this.traceAuth("hydrateAuthState.ticket_captured",{source:r}),await this.syncSocketAuth(this.authTicket).catch(()=>{}),this.traceAuth("hydrateAuthState.completed",{source:r,uid:n}),this.emitAuthState());typeof e.accessToken=="string"&&e.accessToken.length>0;this.getAuthTicket();await this.syncSocketAuth(null);}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()}`,n=await this.timedFetch("loadAuthConfig",r,{credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("loadAuthConfig",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to load auth config",d.QueryFailed),this.authConfig=i,this.csrfToken=this.extractCsrfToken(i,n.response)??this.csrfToken,this.authConfigListeners.forEach(s=>{try{s(this.authConfig);}catch(a){this.log("Auth config listener error",a);}}),this.authConfig}onAuthConfigLoaded(e){return this.authConfigListeners.push(e),this.authConfig&&e(this.authConfig),()=>{this.authConfigListeners=this.authConfigListeners.filter(t=>t!==e);}}onAuthStateChanged(e){this.authStateListeners.push(e);let t=this.config.authBootstrapMode??"refresh",r=(()=>{try{return !!this.getHttpBase()}catch{return false}})(),n=()=>{try{let a=this.authSession?{...this.authSession,...this.currentProfile??{}}:this.currentProfile&&typeof this.currentProfile.uid=="string"?this.currentProfile:null;e(a);}catch(a){this.log("Auth state listener error during initialization",a);}},i=t==="refresh"&&!this.authSession&&!this.authBootstrapAttempted&&typeof window<"u"&&typeof document<"u"&&r,s=!this.authSession&&!!this.authBootstrapPromise;return i?(this.traceAuth("onAuthStateChanged.bootstrap.start",{listenerCount:this.authStateListeners.length}),this.authBootstrapAttempted=true,this.authBootstrapPromise||(this.authBootstrapPromise=this.refreshAuthSession().catch(()=>null).then(()=>{}).finally(()=>{this.authBootstrapPromise=void 0;})),this.authBootstrapPromise.finally(()=>{this.authStateListeners.includes(e)&&(this.traceAuth("onAuthStateChanged.bootstrap.done",{hasSession:!!this.authSession}),this.authSession||n());})):s?(this.traceAuth("onAuthStateChanged.bootstrap.wait",{listenerCount:this.authStateListeners.length}),this.authBootstrapPromise?.finally(()=>{this.authStateListeners.includes(e)&&(this.authSession||n());})):n(),()=>{this.authStateListeners=this.authStateListeners.filter(a=>a!==e);}}getCurrentUser(){return this.currentProfile}getAuthTicket(){return this.authTicket}consumeAuthTicket(){let e=this.authTicket;return this.authTicket=void 0,e}getDefaultCsrfCookieName(){return `__flare_csrf_${this.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`}extractCsrfToken(e,t){let r=e,n=typeof r?.csrfToken=="string"?String(r.csrfToken):typeof r?.csrf_token=="string"?String(r.csrf_token):void 0;if(n)return n;if(!t)return;let i=t.headers.get("x-flare-csrf")??t.headers.get("x-csrf-token")??t.headers.get("csrf-token");return typeof i=="string"&&i.length>0?i:void 0}getCsrfHeaders(){let e=this.getCsrfToken();return e?{"x-flare-csrf":e}:{}}getCsrfCookieName(){return this.authConfig?.cookie?.csrfTokenName??this.getDefaultCsrfCookieName()}getCsrfToken(){return getCookie(this.getCsrfCookieName())??this.csrfToken??null}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()}));}setAuthSession(e,t="unknown"){let r=this.authSession?.uid??this.userId??null;this.authSession=e,e?(this.authToken=e.accessToken,this.userId=e.uid,this.traceAuth("setAuthSession",{source:t,nextUid:e.uid,previousUid:r,mode:"set"})):(this.traceAuth("setAuthSession",{source:t,nextUid:null,previousUid:r,mode:"clear"}),this.authToken=void 0,this.userId=void 0,this.currentProfile=void 0,this.httpResponseCache.clear(),this.httpInFlight.clear()),this.emitAuthState();}emitAuthState(){let e=this.authSession?{...this.authSession,...this.currentProfile??{}}:this.currentProfile&&typeof this.currentProfile.uid=="string"?this.currentProfile:null;this.authStateListeners.forEach(t=>{try{t(e);}catch(r){this.log("Auth state listener error",r);}});}setProfile(e){this.currentProfile=e;}async ensureSessionForSocketAuth(e){if(this.authSession?.accessToken&&this.authSession?.uid)return true;if(this.isConnected&&this.getAuthTicket())try{if(await this.syncSocketAuth(null),this.socketAuthUid!=="anon")return this.traceAuth("ensureSessionForSocketAuth.ticket",{reason:e,socketAuthUid:this.socketAuthUid}),!0}catch{}let t=(()=>{try{return !!this.getHttpBase()}catch{return false}})(),r=this.currentProfile?.uid;if(!t||!r)return false;this.traceAuth("ensureSessionForSocketAuth.start",{reason:e,hasInFlightBootstrap:!!this.authBootstrapPromise,profileUid:r}),this.authBootstrapPromise||(this.authBootstrapPromise=this.refreshAuthSession().catch(()=>null).then(()=>{}).finally(()=>{this.authBootstrapPromise=void 0;})),await this.authBootstrapPromise;let n=!!(this.authSession?.accessToken&&this.authSession?.uid);return this.traceAuth("ensureSessionForSocketAuth.done",{reason:e,hasSession:n,sessionUid:this.authSession?.uid??null}),n}async refreshAuthSession(e){let t=this.getHttpBase();await this.ensureCsrfProtection(),this.traceAuth("refreshAuthSession.start",{providedRefreshToken:!!e,hasSessionBefore:!!this.authSession});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}:{}})}),n=await this.parseJsonWithTiming("refreshAuthSession",r);if(!r.response.ok){if(r.response.status===401)return this.traceAuth("refreshAuthSession.response",{status:r.response.status,ok:false,reason:"unauthorized"}),this.setAuthSession(null,"refreshAuthSession.401"),await this.syncSocketAuth(null).catch(()=>{}),null;this.throwFetchFlareError(n,"Failed to refresh auth session",d.AuthenticationFailed);}let i=String(n.access_token??"");if(!i)throw new f("Refresh succeeded but no access token was returned",d.ParseError);let s=await this.fetchAuthMe(i).catch(()=>null),a={uid:String(s?.id??this.authSession?.uid??this.userId??""),accessToken:i,refreshToken:n.refresh_token?String(n.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.traceAuth("refreshAuthSession.response",{status:r.response.status,ok:true,nextUid:a.uid,hasProfile:!!s}),this.setAuthSession(a,"refreshAuthSession.success"),typeof window<"u"&&await this.syncSocketAuth(i).catch(()=>{}),a}async updateSocketIdentity(e,t=false){let r=typeof e=="string"&&e.length>0?e:"anon",n=r!==this.socketAuthUid;this.socketAuthUid=r,(n||t||this.pendingSubscriptionReplay)&&this.activeSubscriptions.size>0&&await this.replayActiveSubscriptions();}async waitUntilConnected(){if(!this.transport.connected)return new Promise(e=>{let t=setInterval(()=>{this.transport.connected&&(clearInterval(t),e());},50);})}async syncSocketAuth(e){let t=e||this.authTicket||this.authSession?.accessToken;if(t)return this.socketAuthSyncPromise?this.socketAuthSyncPromise:(this.socketAuthSyncPromise=(async()=>{try{await this.waitUntilConnected(),this.log("Executing socket auth with credential type:",e||this.authTicket?"ticket":"token");let r=await this.send("auth",{token:t});if(r.type!=="auth_ok")throw new f("Socket auth sync failed",d.AuthenticationFailed);if(!t||r.uid==="anon"){this.authToken=void 0,this.userId=void 0,this.authTicket=void 0,await this.updateSocketIdentity("anon");return}this.consumeAuthTicket(),this.currentProfile=r.profile,this.setAuthSession({uid:r.uid,accessToken:r.token,refreshToken:this.authSession?.refreshToken??null,provider:this.authSession?.provider,email:this.currentProfile?.email??this.authSession?.email??null,emailVerified:typeof this.currentProfile?.email_verified=="boolean"?this.currentProfile.email_verified:this.authSession?.emailVerified},"syncSocketAuth.ticket_or_token"),await this.updateSocketIdentity(r.uid);}finally{this.socketAuthSyncPromise=void 0;}})(),this.socketAuthSyncPromise)}async beforeActivateSubscription(e){!this.isConnected||this.socketAuthUid!=="anon"||(this.authSession?.accessToken||this.getAuthTicket())&&(await this.syncSocketAuth(this.authSession?.accessToken??null).catch(()=>{}),this.socketAuthUid!=="anon")||!await this.ensureSessionForSocketAuth("beforeActivateSubscription")||this.authSession?.accessToken&&this.socketAuthUid==="anon"&&await this.syncSocketAuth(this.authSession.accessToken).catch(()=>{});}async fetchFreshTicket(){try{let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/ticket?${t.toString()}`,n=await this.timedFetch("fetchFreshTicket",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("fetchFreshTicket",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to fetch fresh ticket",d.QueryFailed),this.authTicket=i.ticket,i.ticket}catch(e){return this.log("Error fetching fresh ticket",e),null}}onConnected(){super.onConnected(),(this.authSession?.accessToken||this.getAuthTicket())&&this.syncSocketAuth(this.authSession?.accessToken??null).catch(e=>{this.log("Socket auth sync failed after connect",e);});}toUint8ArrayFromBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4),n=t+r,i=atob(n),s=new Uint8Array(i.length);for(let a=0;a<i.length;a+=1)s[a]=i.charCodeAt(a);return s}encodePushTokenFromSubscription(e){let t=e.toJSON(),r=String(t.endpoint??"").trim(),n=String(t.keys?.p256dh??"").trim(),i=String(t.keys?.auth??"").trim(),s=JSON.stringify({endpoint:r,p256dh:n,auth:i});return `webpush:${btoa(s)}`}async fetchPushSetupConfig(){let e=this.getHttpBase(),t=new URLSearchParams({appId:this.config.appId});this.config.apiKey&&t.set("apiKey",this.config.apiKey);let r=`${e}/push/config?${t.toString()}`,n=await this.timedFetch("fetchPushSetupConfig",r,{method:"GET",credentials:"include",headers:this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}}),i=await this.parseJsonWithTiming("fetchPushSetupConfig",n);n.response.ok||this.throwFetchFlareError(i,"Failed to fetch push setup config",d.QueryFailed);let s=String(i.vapidPublicKey??"").trim(),a=String(i.serviceWorkerPath??"").trim();if(a.startsWith("/"))try{let h=new URL(e,typeof window<"u"?window.location.origin:"http://localhost").pathname.replace(/\/+$/,"");h&&h!=="/"&&!a.startsWith(`${h}/`)&&(a=`${h}${a}`);}catch{}if(!s||!a)throw new f("Push setup response is missing vapidPublicKey or serviceWorkerPath",d.ParseError,i);return {vapidPublicKey:s,serviceWorkerPath:a}}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 f("Service worker URL must be same-origin with the app",d.WriteFailed);let r=t.pathname.replace(/\/[^/]*$/,"/")||"/";return await navigator.serviceWorker.register(t.pathname+t.search,{scope:r})})().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 f("Push permission can only be requested in browser runtime",d.WriteFailed);if(Notification.permission==="granted")return "granted";let e=await Notification.requestPermission();if(e!=="granted")throw new f(`Push permission is ${e}`,d.PermissionDenied);return e}async acquireBrowserPushToken(e={}){if(typeof window>"u"||typeof navigator>"u")throw new f("Push token acquisition can only run in browser runtime",d.WriteFailed);if(!("serviceWorker"in navigator))throw new f("Service worker is not supported in this browser",d.WriteFailed);if(!("PushManager"in window))throw new f("Push manager is not supported in this browser",d.WriteFailed);await this.requestPushPermission();let t=e.applicationServerKey?null:await this.fetchPushSetupConfig(),r=e.serviceWorkerRegistration??await this.setupPushServiceWorker()??await navigator.serviceWorker.ready,n=e.subscription??await r.pushManager.getSubscription();if(e.forceResubscribe&&n&&(await n.unsubscribe().catch(()=>{}),n=null),!n){let s=e.applicationServerKey??t?.vapidPublicKey;if(!s)throw new f("No VAPID public key available for push subscription",d.WriteFailed);n=await r.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.toUint8ArrayFromBase64Url(s)});}return {token:this.encodePushTokenFromSubscription(n),subscription:n}}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 f("Push token is required",d.WriteFailed);let n=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}:{}})}),i=await this.parseJsonWithTiming("registerPushToken",n);return n.response.ok||this.throwFetchFlareError(i,"Failed to register push token",d.WriteFailed),{registered:!!i.registered,appId:String(i.appId??this.config.appId),uid:String(i.uid??this.authSession?.uid??""),token:String(i.token??r),...typeof i.platform=="string"?{platform:i.platform}:{}}}async unregisterPushToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=String(e??"").trim();if(!n)throw new f("Push token is required",d.WriteFailed);let i=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:n,...t?{authAppId:t}:{}})}),s=await this.parseJsonWithTiming("unregisterPushToken",i);return i.response.ok||this.throwFetchFlareError(s,"Failed to unregister push token",d.WriteFailed),{unregistered:!!s.unregistered,appId:String(s.appId??this.config.appId),token:String(s.token??n),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})}),n=await this.parseJsonWithTiming("sendPushNotification",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to send push notification",d.WriteFailed),{sent:!!n.sent,appId:String(n.appId??this.config.appId),targetCount:Number(n.targetCount??0),successCount:Number(n.successCount??0),failureCount:Number(n.failureCount??0),invalidatedTokenCount:Number(n.invalidatedTokenCount??0),dryRun:!!n.dryRun}}storage(){return this._storageService||(this._storageService=new L(this._buildStorageTransport())),this._storageService}_buildStorageTransport(){let e=this;function t(p){let y=p.includes("?"),m=new URLSearchParams;return m.set("appId",e.config.appId),e.config.apiKey&&m.set("apiKey",e.config.apiKey),`${p}${y?"&":"?"}${m.toString()}`}async function r(p=8e3){e.isConnected||(e.connect(),await new Promise((y,m)=>{if(e.isConnected){y();return}let T=e.onConnectionStateChange(P=>{P==="connected"&&(clearTimeout(A),T(),y());}),A=setTimeout(()=>{T(),m(new f("Storage bucket metadata requires an active socket connection",d.QueryFailed));},p);}));}async function n(p,y={}){if(await r(),e.socketAuthUid==="anon"&&((e.authSession?.accessToken||e.getAuthTicket())&&await e.syncSocketAuth(e.authSession?.accessToken??null).catch(()=>{}),e.socketAuthUid==="anon"&&await e.ensureSessionForSocketAuth(`storage:${p}`).catch(()=>false)&&e.authSession?.accessToken&&await e.syncSocketAuth(e.authSession.accessToken).catch(()=>{})),e.socketAuthUid==="anon")throw new f("Storage operations require an authenticated socket session",d.AuthenticationFailed);return await e.call(p,y)??{}}function i(p){try{let y=p.split(".");if(y.length<2)return null;let m=y[1].replace(/-/g,"+").replace(/_/g,"/"),T=m+"=".repeat((4-m.length%4)%4);if(typeof atob=="function")return JSON.parse(atob(T));let A=globalThis?.Buffer;return A?JSON.parse(A.from(T,"base64").toString("utf8")):null}catch{return null}}function s(p){if(!p)return false;let m=i(p)?.sid;return typeof m=="string"&&m.trim().length>0}function a(){let p=e.authSession?.accessToken;if(s(p))return p;let y=e.authConfig?.cookie?.accessTokenName??`__flare_at_${e.config.appId.replace(/[^a-zA-Z0-9_-]/g,"_")}`,m=getCookie(y);return s(m)?m:null}function c(){let p=a();return {...e.getCsrfHeaders(),...p?{Authorization:`Bearer ${p}`}:{}}}function h(p,y){if(y!==401)return false;let m=String(p.error??"").toLowerCase();return m==="session_expired"||m==="invalid_token"||m==="missing_token"}async function g(){return !!(await e.refreshAuthSession().catch(()=>null))?.accessToken}async function u(p,y,m){let T=e.getHttpBase();await e.ensureCsrfProtection();let A=async()=>{let I=await e.timedFetch(p,`${T}${t(y)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...c()},body:m!==null?JSON.stringify(m):void 0}),C=await e.parseJsonWithTiming(p,I);return {trace:I,json:C}},{trace:P,json:B}=await A();if(!P.response.ok&&h(B,P.response.status)&&await g()){let C=await A();P=C.trace,B=C.json;}return P.response.ok||e.throwFetchFlareError(B,`Storage ${p} failed`,d.WriteFailed),B}async function l(p,y){let m=e.getHttpBase();await e.ensureCsrfProtection();let T=async()=>{let B=await e.timedFetch(p,`${m}${t(y)}`,{method:"GET",credentials:"include",headers:c()}),I=await e.parseJsonWithTiming(p,B);return {trace:B,json:I}},{trace:A,json:P}=await T();if(!A.response.ok&&h(P,A.response.status)&&await g()){let I=await T();A=I.trace,P=I.json;}return A.response.ok||e.throwFetchFlareError(P,`Storage ${p} failed`,d.QueryFailed),P}async function S(p,y,m,T){if(typeof XMLHttpRequest>"u")return u(p,y,m);let A=e.getHttpBase();await e.ensureCsrfProtection();let P=JSON.stringify(m);return new Promise((B,I)=>{let C=new TextEncoder().encode(P).length,k=Q=>{let v=new XMLHttpRequest;v.open("POST",`${A}${t(y)}`),v.withCredentials=true,v.setRequestHeader("Content-Type","application/json");for(let[w,N]of Object.entries(c()))v.setRequestHeader(w,N);v.upload.onprogress=w=>{let N=w.lengthComputable?w.loaded:0,_=w.lengthComputable?w.total:C;T({loaded:N,total:_,percent:_>0?Math.round(N/_*100):0});},v.onload=()=>{let w={};try{w=v.responseText?JSON.parse(v.responseText):{};}catch{I(new f("Failed to parse storage response",d.WriteFailed));return}if(v.status>=400){if(Q===0&&h(w,v.status)){g().then(_=>{if(_)k(1);else {let b=String(w.error_description??w.message??w.error??`HTTP ${v.status}`);I(new f(b,d.WriteFailed));}}).catch(()=>{let _=String(w.error_description??w.message??w.error??`HTTP ${v.status}`);I(new f(_,d.WriteFailed));});return}let N=String(w.error_description??w.message??w.error??`HTTP ${v.status}`);I(new f(N,d.WriteFailed));return}T({loaded:C,total:C,percent:100}),B(w);},v.onerror=()=>I(new f("Network error during storage upload",d.WriteFailed)),v.send(P);};k(0);})}return {appId:this.config.appId,get storageRulesHomeBucket(){return e.authConfig?.storageRulesHomeBucket??void 0},transferManager:typeof this.config.storage=="object"&&this.config.storage?.transferManager?this.config.storage.transferManager:void 0,call:(p,y)=>n(p,y),subscribe:(p,y,m,T,A,P)=>e.subscribe(p,y,m,T,A,P??{}),doPost:(p,y,m)=>u(p,y,m),doGet:(p,y)=>l(p,y),doPostWithProgress:S}}putObject(e){return this.storage().putObject(e)}getObject(e){return this.storage().getObject(e)}getObjectUrl(e){return this.storage().getObjectUrl(e)}downloadObject(e){return this.storage().downloadObject(e)}headObject(e){return this.storage().headObject(e)}headObjects(e){return this.storage().headObjects(e)}listObjects(e){return this.storage().listObjects(e)}copyObject(e){return this.storage().copyObject(e)}copyObjects(e){return this.storage().copyObjects(e)}deleteObject(e){return this.storage().deleteObject(e)}deleteObjects(e){return this.storage().deleteObjects(e)}createBucket(e,t){return this.storage().createBucket(e,t)}listBuckets(){return this.storage().listBuckets()}deleteBucket(e){return this.storage().deleteBucket(e)}deleteBuckets(e){return this.storage().deleteBuckets(e)}getBucketLocation(e){return this.storage().getBucketLocation(e)}createSignedUrl(e){return this.storage().createSignedUrl(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 n=await this.fetchAuthMe(r).catch(()=>null);return this.setAuthSession({uid:t.uid??t.id,accessToken:r,refreshToken:this.authSession?.refreshToken??null,email:n?.email??null,emailVerified:n?.email_verified}),await this.updateSocketIdentity(t.uid),this.log("Authentication successful",t.uid),{uid:t.uid,token:t.token??e}}throw new f("Authentication failed",d.AuthenticationFailed)}getAuthRequestContentType(){return this.config.authRequestContentType??"application/json"}buildAuthRequestBody(e){let t=this.getAuthRequestContentType();if(t==="application/json"){let n={};for(let[i,s]of Object.entries(e))s!==void 0&&(n[i]=s);return {contentType:t,body:JSON.stringify(n)}}let r=new URLSearchParams;for(let[n,i]of Object.entries(e))i!==void 0&&r.set(n,i);return {contentType:t,body:r.toString()}}async requestEmailPasswordToken(e,t,r){if(typeof process<"u"&&process.versions?.node&&this.config.grpcUrl&&this.config.transport!=="ws"&&this.config.transport!=="http")try{let{runGrpcLogin:u}=await H("./grpc"),l=await u(this.config,e,t);if(l)return {kind:"response.ok",access_token:l.token,refresh_token:l.refreshToken,expires_in:null,token_type:"Bearer",scope:r?.join(" ")??null,profile:null,provider:"credentials"}}catch(u){this.log("gRPC auth login fallback to HTTP",u);}let n=this.getHttpBase();await this.ensureCsrfProtection();let{contentType:i,body:s}=this.buildAuthRequestBody({appId:this.config.appId,client_id:this.config.apiKey??"",grant_type:"password",email:e,password:t,scope:r?.length?r.join(" "):void 0}),a=await this.timedFetch("requestEmailPasswordToken",`${n}/auth/token?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":i,...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:s}),c=await this.parseJsonWithTiming("requestEmailPasswordToken",a),h=typeof c.error=="string"&&c.error.trim().length>0;return (!a.response.ok||h)&&this.throwFetchFlareError(c,"Sign-in with email/password failed",d.AuthenticationFailed),{kind:typeof c.kind=="string"&&c.kind.trim().length>0?c.kind:"response.ok",access_token:String(c.access_token??""),refresh_token:c.refresh_token?String(c.refresh_token):null,expires_in:c.expires_in?Number(c.expires_in):null,token_type:String(c.token_type??"Bearer"),scope:c.scope?String(c.scope):null,profile:null,provider:"credentials"}}async signInWithEmailAndPassword(e,t,r){try{let n=await this.requestEmailPasswordToken(e,t,r?.scope),i=await this.auth(n.access_token),s=await this.fetchAuthMe(n.access_token).catch(()=>null);return this.setAuthSession({uid:i.uid,accessToken:n.access_token,refreshToken:n.refresh_token,provider:n.provider,email:s?.email??e,emailVerified:s?.email_verified}),this.log("Credentials sign-in successful",i.uid),{...i,kind:n.kind,accessToken:n.access_token,refreshToken:n.refresh_token,authToken:n}}catch(n){let i=/invalid_email|user.not.found|no user/i.test(n?.message??"");if(r?.createIfMissing&&i){let s=await this.createUserWithEmail(e,t,{scope:r.scope,signInIfAllowed:true});if(s.verification_required)throw new f("Email verification required before sign-in",d.AuthenticationFailed);return {uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,created:true}}throw n instanceof f?n:new f(n.message??"Sign-in with email/password failed",n.error??n.code??d.AuthenticationFailed,n)}}async signInWithEmail(e,t,r){return this.signInWithEmailAndPassword(e,t,r)}async createUserWithEmail(e,t,r){let n=await this.registerWithEmail(e,t,r);if(n.verification_required)return {kind:n.kind,verificationRequired:true,verification_required:true,emailSent:!!n.email_sent,email_sent:!!n.email_sent,message:typeof n.message=="string"?n.message:void 0,preview:n.preview};let i=String(n.access_token??"");if(!i)throw new f("User created but no access token returned",d.AuthenticationFailed);let s={access_token:i,refresh_token:n.refresh_token?String(n.refresh_token):null,expires_in:n.expires_in?Number(n.expires_in):null,token_type:String(n.token_type??"Bearer"),scope:n.scope?String(n.scope):null,profile:null,provider:"credentials"},a=await this.auth(i),c=await this.fetchAuthMe(i).catch(()=>null);return this.setAuthSession({uid:a.uid,accessToken:i,refreshToken:s.refresh_token,provider:"credentials",email:c?.email??e,emailVerified:c?.email_verified}),{...a,kind:typeof n.kind=="string"?n.kind:void 0,accessToken:i,access_token:i,token_type:s.token_type,expires_in:s.expires_in,refreshToken:s.refresh_token,refresh_token:s.refresh_token,scope:s.scope,expires_at:n.expires_at,sid:n.sid,authToken:s,auth_token:s,verificationRequired:false,verification_required:false,emailSent:!!n.email_sent,email_sent:!!n.email_sent,preview:n.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(n){if(!/invalid_email|user.not.found|no user/i.test(n?.message??""))throw n;let s=await this.createUserWithEmail(e,t,{scope:r?.scope,additionalParams:r?.additionalParams,signInIfAllowed:true});return s.verification_required?{kind:s.kind,verificationRequired:true,created:true,emailSent:s.emailSent,preview:s.preview}:{uid:s.uid,token:s.token,accessToken:s.accessToken,refreshToken:s.refreshToken,authToken:s.authToken,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})}),n=await this.parseJsonWithTiming("sendEmailVerification",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to send verification email",d.AuthenticationFailed),n}async verifyEmailWithCode(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("verifyEmailWithCode",n);return n.response.ok||this.throwFetchFlareError(i,"Email verification failed",d.AuthenticationFailed),i}async confirmEmailLink(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("confirmEmailLink",n);return n.response.ok||this.throwFetchFlareError(i,"Email link verification failed",d.AuthenticationFailed),i}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})}),n=await this.parseJsonWithTiming("sendAccountRecovery",r);return r.response.ok||this.throwFetchFlareError(n,"Failed to send recovery email",d.AuthenticationFailed),n}async recoverAccountWithCode(e,t,r){let n=this.getHttpBase();await this.ensureCsrfProtection();let i=await this.timedFetch("recoverAccountWithCode",`${n}/auth/recover/confirm?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:JSON.stringify({email:e,code:t,newPassword:r,appId:this.config.appId,apiKey:this.config.apiKey})}),s=await this.parseJsonWithTiming("recoverAccountWithCode",i);return i.response.ok||this.throwFetchFlareError(s,"Account recovery failed",d.AuthenticationFailed),s}async recoverAccountWithToken(e,t){let r=this.getHttpBase();await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("recoverAccountWithToken",n);return n.response.ok||this.throwFetchFlareError(i,"Account recovery failed",d.AuthenticationFailed),i}async signIn(e,t,r){let n=typeof e?.signIn=="function",i=n?e:await this.getAuthGuard(),s=n?t:e,a=n?r:t;return i.signIn(s,a)}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",n=r?e:await this.getAuthGuard(),i=r?t:typeof e=="boolean"?e:false,s=await n.handleRedirect(i);if(!s||!s.access_token||!s.provider)return null;let a=await this.exchangeProviderToken(s.provider,s.access_token),c=await this.auth(a.token),h=await this.fetchAuthMe(a.token).catch(()=>null);return this.setAuthSession({uid:c.uid,accessToken:a.token,refreshToken:s.refresh_token,provider:s.provider,email:h?.email??null,emailVerified:h?.email_verified}),{...c,authToken:s,provider:s.provider}}async exchangeProviderToken(e,t){let r=`${this.getHttpBase()}/auth/exchange`;await this.ensureCsrfProtection();let n=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})}),i=await this.parseJsonWithTiming("exchangeProviderToken",n);if(n.response.ok||this.throwFetchFlareError(i,"OAuth token exchange failed",d.AuthenticationFailed),!i?.token)throw new f("OAuth token exchange failed",d.ParseError,i);return {token:String(i.token)}}async getAuthGuard(){if(this.authGuard)return this.authGuard;let e=await this.loadAuthConfig();if(!e.enabled)throw new f("Authentication is disabled for this app",d.AuthenticationFailed);let t=this.getHttpBase(),r=`${t}/auth/oauth/token?appId=${encodeURIComponent(this.config.appId)}`,n=[],i=(s,a)=>({...a,token_url:r,tokenParams:{...a.tokenParams??{},provider:s}});if(e.providers.credentials?.enabled&&n.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.google?.enabled&&e.providers.google.clientId&&n.push(i("google",Google({clientId:e.providers.google.clientId,scopes:e.providers.google.scopes}))),e.providers.github?.enabled&&e.providers.github.clientId&&n.push(i("github",GitHub({clientId:e.providers.github.clientId,scopes:e.providers.github.scopes}))),e.providers.facebook?.enabled&&e.providers.facebook.clientId&&n.push(i("facebook",Facebook({clientId:e.providers.facebook.clientId,scopes:e.providers.facebook.scopes}))),e.providers.dropbox?.enabled&&e.providers.dropbox.clientId&&n.push(i("dropbox",Dropbox({clientId:e.providers.dropbox.clientId,scopes:e.providers.dropbox.scopes}))),e.providers.apple?.enabled&&e.providers.apple.clientId&&n.push(i("apple",Apple({clientId:e.providers.apple.clientId,scopes:e.providers.apple.scopes}))),e.providers.twitter?.enabled&&e.providers.twitter.clientId&&n.push(i("twitter",Twitter({clientId:e.providers.twitter.clientId,scopes:e.providers.twitter.scopes}))),n.length===0)throw new f("No authentication providers are enabled for this app",d.AuthenticationFailed);return this.authGuard=new AuthGuard({providers:n,redirectUri:e.redirectUri}),this.authGuard}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,"signOut.finally"),await this.syncSocketAuth(null).catch(()=>{});}this.log("Signed out");}async registerWithEmail(e,t,r){if(typeof process<"u"&&process.versions?.node&&this.config.grpcUrl&&this.config.transport!=="ws"&&this.config.transport!=="http")try{let{runGrpcRegister:h}=await H("./grpc"),g=await h(this.config,e,t);if(g)return {kind:"auth.registration",token_type:"Bearer",access_token:g.token,refresh_token:null,uid:g.userId,role:g.role,verification_required:!1,email_sent:!1}}catch(h){this.log("gRPC auth register fallback to HTTP",h);}let n=this.getHttpBase();await this.ensureCsrfProtection();let{contentType:i,body:s}=this.buildAuthRequestBody({appId:this.config.appId,client_id:this.config.apiKey??"",grant_type:"create_user",email:e,password:t,scope:r?.scope?.length?r.scope.join(" "):void 0,additional_params:r?.additionalParams?JSON.stringify(r.additionalParams):void 0}),a=await this.timedFetch("registerWithEmail",`${n}/auth/register?appId=${encodeURIComponent(this.config.appId)}`,{method:"POST",credentials:"include",headers:{"Content-Type":i,...this.getCsrfHeaders(),...this.config.apiKey?{"x-flare-api-key":this.config.apiKey}:{}},body:s}),c=await this.parseJsonWithTiming("registerWithEmail",a);return !a.response.ok&&a.response.status!==202&&this.throwFetchFlareError(c,"User creation failed",d.WriteFailed),c}};var oe=class extends V{autoPushRegisteredIdentity;autoPushInProgress=false;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",n=String(t?.accessToken??"").trim(),i=r!=="anon"&&n?r:"anon";if(this.autoPushRegisteredIdentity!==i&&!this.autoPushInProgress){this.autoPushInProgress=true;try{await this.autoEnablePushNotifications(),this.autoPushRegisteredIdentity=i;}catch(s){this.log("Auto push enable failed",s);}finally{this.autoPushInProgress=false;}}};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]});}},Y=oe;function ae(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Ve(o){return `__flare_csrf_${o.replace(/[^a-zA-Z0-9_-]/g,"_")}`}function Z(o,e){let t=e.toLowerCase();for(let[r,n]of Object.entries(o??{}))if(r.toLowerCase()===t&&typeof n=="string")return n}function Ye(o){let e=Z(o,"set-cookie");if(typeof e=="string"&&e.length>0)return [e];for(let[t,r]of Object.entries(o??{}))if(t.toLowerCase()==="set-cookie"&&Array.isArray(r))return r.filter(n=>typeof n=="string");return []}function Ze(o,e){for(let t of o){let r=t.split(";").map(c=>c.trim()),[n]=r;if(!n)continue;let i=n.indexOf("=");if(i<=0)continue;let s=decodeURIComponent(n.slice(0,i)),a=n.slice(i+1);if(s===e)return decodeURIComponent(a)}}async function Xe(o){let e=new URL("/auth/config",o.endpoint);return e.searchParams.set("appId",o.appId),o.apiKey&&e.searchParams.set("apiKey",o.apiKey),await withGet(e.toString(),{ignoreKind:true,withCredentials:true,returnRawResponse:true,headers:o.apiKey?{"x-flare-api-key":o.apiKey}:{},appendCookiesToBody:false,appendTimestamp:false}).catch(()=>null)}async function ge(o){let e=await Xe(o),t=e?.data,r=e?.headers??{},n=Z(r,"x-flare-csrf")??Z(r,"x-csrf-token")??Z(r,"csrf-token");if(typeof n=="string"&&n.length>0)return {csrfToken:n,...t};let i=t?.cookie?.csrfTokenName,s=i&&i.length>0?i:Ve(o.appId),a=Ye(r),c=Ze(a,s);if(typeof c=="string"&&c.length>0)return {csrfToken:c,...t}}function fe(o,e,t){return `${encodeURIComponent(o)}=${encodeURIComponent(e)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${t}`}function et(o){let e=o.proxyCookieName??ae(o.appId),t=o.proxyCookieMaxAge??3600;return async function(n){let i=await ge(o),s=i?.csrfToken,a=new Headers({"Content-Type":"application/json"});return s&&a.set("Set-Cookie",fe(e,s,t)),new Response(JSON.stringify({csrfToken:s??null,...i}),{status:200,headers:a})}}function tt(o){let e=o.proxyCookieName??ae(o.appId),t=o.proxyCookieMaxAge??3600;return async function(n,i){if(n.method!=="GET"&&n.method!=="HEAD"){i.status(405).json({error:"Method not allowed"});return}let a=(await ge(o))?.csrfToken;a&&i.setHeader("Set-Cookie",fe(e,a,t)),i.status(200).json({csrfToken:a??null});}}function rt(o,e,t){let r=t??ae(e);if(o instanceof Request){let s=(o.headers.get("cookie")??"").split(";").map(c=>c.trim()).find(c=>c.startsWith(`${encodeURIComponent(r)}=`)||c.startsWith(`${r}=`));if(!s)return null;let a=s.indexOf("=");return a>=0?decodeURIComponent(s.slice(a+1)):null}let{cookies:n}=o;return typeof n?.get=="function"?n.get(r)?.value??null:n&&typeof n=="object"?n[r]??null:null}function nt(o,e){let t={};return o&&(t["x-flare-csrf"]=o),e?.accessToken&&(t.Authorization=`Bearer ${e.accessToken}`),e?.apiKey&&(t["x-flare-api-key"]=e.apiKey),t}var Sr="ServerTimeStamp",Tr={$serverTimestamp:true};var ye=["updatedAt","createdAt","_updatedAt","_createdAt"],X=o=>{if(o==null)return null;if(o instanceof Date)return Number.isNaN(o.getTime())?null:o;if(typeof o=="number"){let e=new Date(o);return Number.isNaN(e.getTime())?null:e}if(typeof o=="string"){let e=new Date(o);return Number.isNaN(e.getTime())?null:e}if(typeof o=="object"&&"$date"in o){let e=o.$date;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(e&&typeof e=="object"&&typeof e.$numberLong=="string"){let t=Number(e.$numberLong);if(!Number.isFinite(t))return null;let r=new Date(t);return Number.isNaN(r.getTime())?null:r}}return null},Cr=(o,e="updatedAt")=>{if(!o)return null;let t=e?[e,...ye.filter(r=>r!==e)]:[...ye];for(let r of t){let n=o[r],i=X(n);if(i)return i}return null},Ar=(o,e,t)=>{let r=X(o);return r?new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short",...e}).format(r):""},it=(o,e=new Date)=>{let t=X(o),r=X(e);return !t||!r?null:t.getTime()-r.getTime()},Ir=(o,e=new Date)=>{let t=it(o,e);if(t==null)return "";let r=Math.abs(t),n=Math.floor(r/6e4),i=Math.floor(r/36e5),s=Math.floor(r/864e5);return r<3e4?"just now":n<60?t<0?`${n}m ago`:`in ${n}m`:i<24?t<0?`${i}h ago`:`in ${i}h`:t<0?`${s}d ago`:`in ${s}d`};var st=(u=>(u.authEmailNotVerified="auth/email-not-verified",u.authEmailAlreadyVerified="auth/email-already-verified",u.authInvalidToken="auth/invalid-token",u.authUserDisabled="auth/user-disabled",u.authUserNotFound="auth/user-not-found",u.authWrongPassword="auth/wrong-password",u.authEmailAlreadyInUse="auth/email-already-in-use",u.authInvalidEmail="auth/invalid-email",u.authWeakPassword="auth/weak-password",u.authTooManyRequests="auth/too-many-requests",u.authInternalError="auth/internal-error",u))(st||{});var ot=(k=>(k.health="health",k.authConfig="auth_config",k.authRegistration="auth/registration",k.authRegistrationVerificationRequired="auth/registration-verification-required",k.authSession="auth/session",k.authExchange="auth/exchange",k.authLogout="auth/logout",k.authSsrBridge="auth/ssr_bridge",k.authSsrVerify="auth/ssr_verify",k.accountRecovery="account/recovery",k.emailVerification="email/verification",k.verificationDispatch="verification/dispatch",k.authProfile="auth/profile",k.adminToken="admin/token",k.documentDelete="document/delete",k.documentsDelete="documents/delete",k.documents="documents",k.document="document",k.documentCreate="document/create",k.documentUpdate="document/update",k.oauthProviderResponse="oauth_provider_response",k.success="success",k.response="response",k))(ot||{});var O=null,W=null,ee=null,me=o=>new Proxy(o,{get(e,t,r){if(t==="onAuthStateChange")return e.onAuthStateChanged.bind(e);if(t==="onAuthConfigLoaded")return e.onAuthConfigLoaded.bind(e);let n=Reflect.get(e,t,r);return typeof n=="function"?n.bind(e):n}}),at=o=>JSON.stringify({endpoint:o.endpoint,grpcUrl:o.grpcUrl,transport:o.transport,wsPath:o.wsPath,appId:o.appId,apiKey:o.apiKey,authRequestContentType:o.authRequestContentType,publicKey:o.publicKey,autoReconnect:o.autoReconnect,reconnectDelay:o.reconnectDelay,maxReconnectDelay:o.maxReconnectDelay,dataMapperKeys:Object.keys(o.dataMapper??{}).sort()}),Er=o=>{let e=at(o),t=typeof window<"u"&&typeof document<"u",r=!t&&typeof process<"u"&&typeof process.env?.NEXT_RUNTIME=="string";return r?me(new Y(o)):(O&&ee!==e&&(O.disconnect(),O=null,W=null,ee=null),O||(O=new Y(o),ee=e,(t||!r)&&O.connect(),t&&O.setupPushServiceWorker().catch(()=>{}),W=me(O)),W??O)},Mr=()=>W??O,jr=()=>{O&&(O.disconnect(),O=null,W=null,ee=null);};var Dr=Y;
|
|
2
2
|
export{ie as CollectionReference,D as DocumentQueryBuilder,U as DocumentReference,ke as FlareAction,Y as FlareClient,f as FlareError,st as FlareErrors,Se as FlareEvent,ot as FlareResponseCodes,L as FlareStorage,xe as FlareStorageSignedAction,Sr as ServerTimeStamp,Tr as ServerTimeStampField,nt as buildFlareHeaders,Er as connectApp,et as createCsrfProxy,tt as createCsrfProxyHandler,Dr as default,it as diffMs,jr as disconnectFlare,rt as extractCsrfFromRequest,Kt as flareRulesToSecurityMap,Ar as formatLocalDateTime,Cr as getDocumentTimestamp,Mr as getFlare,ue as parseValue,te as parseWhereCondition,Jt as securityMapToFlareRules,Ir as timeAgo,X as toDate};
|
package/dist/react.d.cts
CHANGED
package/dist/react.d.ts
CHANGED