diff --git a/CHANGELOG.md b/CHANGELOG.md index 3216d1f..bd04e85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 0.21.4 + +- Fixed the `requestKey` handling in `authWithOAuth2({...})` to allow manually cancelling the entire OAuth2 pending request flow using `pb.cancelRequest(requestKey)`. + _Due to the [`window.close` caveats](https://developer.mozilla.org/en-US/docs/Web/API/Window/close) note that the OAuth2 popup window may still remain open depending on which stage of the OAuth2 flow the cancellation has been invoked._ + + ## 0.21.3 - Enforce temporary the `atob` polyfill for ReactNative until [Expo 51+ and React Native v0.74+ `atob` fix get released](https://github.com/reactwg/react-native-releases/issues/287). diff --git a/dist/pocketbase.cjs.d.ts b/dist/pocketbase.cjs.d.ts index 2353cb1..5f07fd6 100644 --- a/dist/pocketbase.cjs.d.ts +++ b/dist/pocketbase.cjs.d.ts @@ -776,10 +776,31 @@ declare class RecordService extends CrudService { * }) * ``` * - * _Site-note_: when creating the OAuth2 app in the provider dashboard + * Note1: When creating the OAuth2 app in the provider dashboard * you have to configure `https://yourdomain.com/api/oauth2-redirect` * as redirect URL. * + * Note2: Safari may block the default `urlCallback` popup because + * it doesn't allow `window.open` calls as part of an `async` click functions. + * To workaround this you can either change your click handler to not be marked as `async` + * OR manually call `window.open` before your `async` function and use the + * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061). + * For example: + * ```js + * + * ... + * document.getElementById("btn").addEventListener("click", () => { + * pb.collection("users").authWithOAuth2({ + * provider: "gitlab", + * }).then((authData) => { + * console.log(authData) + * }).catch((err) => { + * console.log(err, err.originalError); + * }); + * }) + * ``` + * + * * @throws {ClientResponseError} */ authWithOAuth2(options: OAuth2AuthConfig): Promise>; diff --git a/dist/pocketbase.cjs.js b/dist/pocketbase.cjs.js index 2fd4270..a0f4a3b 100644 --- a/dist/pocketbase.cjs.js +++ b/dist/pocketbase.cjs.js @@ -1,2 +1,2 @@ -"use strict";class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,s,i){const n=Object.assign({},i||{}),r=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const o=r(s);if(o&&!e.test(o))throw new TypeError("argument val is invalid");let a=t+"="+o;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}const t="undefined"!=typeof navigator&&"ReactNative"===navigator.product||"undefined"!=typeof global&&global.HermesInternal;let s;function getTokenPayload(e){if(e)try{const t=decodeURIComponent(s(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let s=getTokenPayload(e);return!(Object.keys(s).length>0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}async authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{},s=(await this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!s)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const i=this.client.buildUrl("/api/oauth2-redirect"),n=new RealtimeService(this.client);let r=null;function cleanup(){r?.close(),n.unsubscribe()}return t.urlCallback||(r=openBrowserPopup(void 0)),new Promise((async(e,o)=>{try{await n.subscribe("@oauth2",(async r=>{const a=n.clientId;try{if(!r.state||a!==r.state)throw new Error("State parameters don't match.");if(r.error||!r.code)throw new Error("OAuth2 redirect error or missing code: "+r.error);const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const o=await this.authWithOAuth2Code(s.name,r.code,s.codeVerifier,i,t.createData,n);e(o)}catch(e){o(new ClientResponseError(e))}cleanup()}));const a={state:n.clientId};t.scopes?.length&&(a.scope=t.scopes.join(" "));const c=this._replaceQueryParams(s.authUrl+i,a);let l=t.urlCallback||function(e){r?r.location.href=e:r=openBrowserPopup(e)};await l(c)}catch(e){cleanup(),o(new ClientResponseError(e))}}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}module.exports=class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}; +"use strict";class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,s,i){const n=Object.assign({},i||{}),r=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const o=r(s);if(o&&!e.test(o))throw new TypeError("argument val is invalid");let a=t+"="+o;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}const t="undefined"!=typeof navigator&&"ReactNative"===navigator.product||"undefined"!=typeof global&&global.HermesInternal;let s;function getTokenPayload(e){if(e)try{const t=decodeURIComponent(s(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let s=getTokenPayload(e);return!(Object.keys(s).length>0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{};let s=null;t.urlCallback||(s=openBrowserPopup(void 0));const i=new RealtimeService(this.client);function cleanup(){s?.close(),i.unsubscribe()}const n={},r=t.requestKey;return r&&(n.requestKey=r),this.listAuthMethods(n).then((e=>{const n=e.authProviders.find((e=>e.name===t.provider));if(!n)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const o=this.client.buildUrl("/api/oauth2-redirect"),a=r?this.client.cancelControllers?.[r]:void 0;return a&&(a.signal.onabort=()=>{cleanup()}),new Promise((async(e,r)=>{try{await i.subscribe("@oauth2",(async s=>{const c=i.clientId;try{if(!s.state||c!==s.state)throw new Error("State parameters don't match.");if(s.error||!s.code)throw new Error("OAuth2 redirect error or missing code: "+s.error);const i=Object.assign({},t);delete i.provider,delete i.scopes,delete i.createData,delete i.urlCallback,a?.signal?.onabort&&(a.signal.onabort=null);const r=await this.authWithOAuth2Code(n.name,s.code,n.codeVerifier,o,t.createData,i);e(r)}catch(e){r(new ClientResponseError(e))}cleanup()}));const c={state:i.clientId};t.scopes?.length&&(c.scope=t.scopes.join(" "));const l=this._replaceQueryParams(n.authUrl+o,c);let h=t.urlCallback||function(e){s?s.location.href=e:s=openBrowserPopup(e)};await h(l)}catch(e){cleanup(),r(new ClientResponseError(e))}}))})).catch((e=>{throw cleanup(),e}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}module.exports=class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}; //# sourceMappingURL=pocketbase.cjs.js.map diff --git a/dist/pocketbase.cjs.js.map b/dist/pocketbase.cjs.js.map index 2d285df..1edc4a9 100644 --- a/dist/pocketbase.cjs.js.map +++ b/dist/pocketbase.cjs.js.map @@ -1 +1 @@ -{"version":3,"file":"pocketbase.cjs.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * _Site-note_: when creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n async authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n const authMethods = await this.listAuthMethods();\n\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before the async call due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieSerialize","val","options","opt","assign","encode","defaultEncode","test","TypeError","value","result","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","defaultDecode","indexOf","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","charCodeAt","slice","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","length","exp","now","atob","input","str","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","key","rawData","cookieParse","decode","index","eqIdx","endIdx","lastIndexOf","trim","undefined","_","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","find","eagerDefaultPopup","cleanup","urlCallback","openBrowserPopup","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","signal","FormData","hasBlobField","form","v","append","values","File","encodedKey"],"mappings":"aAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UA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D,IAAK,MAAMiU,KAAKE,EACZ,GACqB,oBAATlT,MAAwBgT,aAAahT,MAC5B,oBAATmT,MAAwBH,aAAaG,KAE7C,OAAO,CAGlB,CAED,OAAO,CACV,CAMO,SAAAlB,CACJrL,EACAzN,GAEAyN,EAAUA,GAAW,GACrBzN,EAAOA,EAAKkC,cAEZ,IAAK,IAAI0D,KAAO6H,EACZ,GAAI7H,EAAI1D,eAAiBlC,EACrB,OAAOyN,EAAQ7H,GAIvB,OAAO,IACV,CAKO,UAAAyT,CAAWrQ,GACf,OACIA,IAI2B,aAA1BA,EAAK9J,YAAYc,MAIO,oBAAb0Z,UAA4B1Q,aAAgB0Q,SAE/D,CAKO,oBAAAb,CAAqB1G,GACzB,MAAMnR,EAAwB,GAC9B,IAAK,MAAM4E,KAAOuM,EAAQ,CACtB,GAAoB,OAAhBA,EAAOvM,GAEP,SAGJ,MAAM7E,EAAQoR,EAAOvM,GACfqU,EAAa1X,mBAAmBqD,GAEtC,GAAIW,MAAMC,QAAQzF,GAEd,IAAK,MAAM8Y,KAAK9Y,EACZC,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBsX,SAE/C9Y,aAAiBa,KACxBZ,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBxB,EAAMuX,gBAChC,cAAVvX,GAAmC,iBAAVA,EACvCC,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBgB,KAAKoD,UAAU5F,KAEjEC,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBxB,GAEzD,CAED,OAAOC,EAAOsC,KAAK,IACtB"} \ No newline at end of file +{"version":3,"file":"pocketbase.cjs.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * Note1: When creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * Note2: Safari may block the default `urlCallback` popup because\n * it doesn't allow `window.open` calls as part of an `async` click functions.\n * To workaround this you can either change your click handler to not be marked as `async`\n * OR manually call `window.open` before your `async` function and use the\n * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061).\n * For example:\n * ```js\n * \n * ...\n * document.getElementById(\"btn\").addEventListener(\"click\", () => {\n * pb.collection(\"users\").authWithOAuth2({\n * provider: \"gitlab\",\n * }).then((authData) => {\n * console.log(authData)\n * }).catch((err) => {\n * console.log(err, err.originalError);\n * });\n * })\n * ```\n *\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before any async calls due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n const requestKeyOptions: SendOptions = {};\n const requestKey = config.requestKey\n if (requestKey) {\n requestKeyOptions.requestKey = requestKey;\n }\n\n return this.listAuthMethods(requestKeyOptions).then((authMethods) => {\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // find the AbortController associated with the current request key (if any)\n const cancelController = requestKey ? this.client['cancelControllers']?.[requestKey] : undefined;\n if (cancelController) {\n cancelController.signal.onabort = () => {\n cleanup();\n }\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n // reset the cancelController listener as it will be triggered by the next api call\n if (cancelController?.signal?.onabort) {\n cancelController.signal.onabort = null\n }\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }).catch((err) => {\n cleanup();\n throw err // rethrow\n }) as Promise>;\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieSerialize","val","options","opt","assign","encode","defaultEncode","test","TypeError","value","result","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","defaultDecode","indexOf","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","charCodeAt","slice","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","length","exp","now","atob","input","str","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","key","rawData","cookieParse","decode","index","eqIdx","endIdx","lastIndexOf","trim","undefined","_","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","eagerDefaultPopup","urlCallback","openBrowserPopup","cleanup","requestKeyOptions","authMethods","find","cancelController","signal","onabort","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","FormData","hasBlobField","form","v","append","values","File","encodedKey"],"mappings":"aAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,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,KAAK+S,EAAa,IAAM9X,mBAAmB0X,SAE/ClZ,aAAiBa,KACxBZ,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBxB,EAAM4X,gBAChC,cAAV5X,GAAmC,iBAAVA,EACvCC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBgB,KAAKoD,UAAU5F,KAEjEC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBxB,GAEzD,CAED,OAAOC,EAAOsC,KAAK,IACtB"} \ No newline at end of file diff --git a/dist/pocketbase.es.d.mts b/dist/pocketbase.es.d.mts index 10103d6..9d1c6c3 100644 --- a/dist/pocketbase.es.d.mts +++ b/dist/pocketbase.es.d.mts @@ -799,10 +799,31 @@ declare class RecordService extends CrudService { * }) * ``` * - * _Site-note_: when creating the OAuth2 app in the provider dashboard + * Note1: When creating the OAuth2 app in the provider dashboard * you have to configure `https://yourdomain.com/api/oauth2-redirect` * as redirect URL. * + * Note2: Safari may block the default `urlCallback` popup because + * it doesn't allow `window.open` calls as part of an `async` click functions. + * To workaround this you can either change your click handler to not be marked as `async` + * OR manually call `window.open` before your `async` function and use the + * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061). + * For example: + * ```js + * + * ... + * document.getElementById("btn").addEventListener("click", () => { + * pb.collection("users").authWithOAuth2({ + * provider: "gitlab", + * }).then((authData) => { + * console.log(authData) + * }).catch((err) => { + * console.log(err, err.originalError); + * }); + * }) + * ``` + * + * * @throws {ClientResponseError} */ authWithOAuth2(options: OAuth2AuthConfig): Promise>; diff --git a/dist/pocketbase.es.d.ts b/dist/pocketbase.es.d.ts index 10103d6..9d1c6c3 100644 --- a/dist/pocketbase.es.d.ts +++ b/dist/pocketbase.es.d.ts @@ -799,10 +799,31 @@ declare class RecordService extends CrudService { * }) * ``` * - * _Site-note_: when creating the OAuth2 app in the provider dashboard + * Note1: When creating the OAuth2 app in the provider dashboard * you have to configure `https://yourdomain.com/api/oauth2-redirect` * as redirect URL. * + * Note2: Safari may block the default `urlCallback` popup because + * it doesn't allow `window.open` calls as part of an `async` click functions. + * To workaround this you can either change your click handler to not be marked as `async` + * OR manually call `window.open` before your `async` function and use the + * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061). + * For example: + * ```js + * + * ... + * document.getElementById("btn").addEventListener("click", () => { + * pb.collection("users").authWithOAuth2({ + * provider: "gitlab", + * }).then((authData) => { + * console.log(authData) + * }).catch((err) => { + * console.log(err, err.originalError); + * }); + * }) + * ``` + * + * * @throws {ClientResponseError} */ authWithOAuth2(options: OAuth2AuthConfig): Promise>; diff --git a/dist/pocketbase.es.js b/dist/pocketbase.es.js index 632550d..50d69fb 100644 --- a/dist/pocketbase.es.js +++ b/dist/pocketbase.es.js @@ -1,2 +1,2 @@ -class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=cookieParse(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){const s={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},n=getTokenPayload(this.token);s.expires=n?.exp?new Date(1e3*n.exp):new Date("1970-01-01"),e=Object.assign({},s,e);const r={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let o=cookieSerialize(t,JSON.stringify(r),e);const a="undefined"!=typeof Blob?new Blob([o]).size:o.length;if(r.model&&a>4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}async authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{},s=(await this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!s)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const i=this.client.buildUrl("/api/oauth2-redirect"),n=new RealtimeService(this.client);let r=null;function cleanup(){r?.close(),n.unsubscribe()}return t.urlCallback||(r=openBrowserPopup(void 0)),new Promise((async(e,o)=>{try{await n.subscribe("@oauth2",(async r=>{const a=n.clientId;try{if(!r.state||a!==r.state)throw new Error("State parameters don't match.");if(r.error||!r.code)throw new Error("OAuth2 redirect error or missing code: "+r.error);const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const o=await this.authWithOAuth2Code(s.name,r.code,s.codeVerifier,i,t.createData,n);e(o)}catch(e){o(new ClientResponseError(e))}cleanup()}));const a={state:n.clientId};t.scopes?.length&&(a.scope=t.scopes.join(" "));const c=this._replaceQueryParams(s.authUrl+i,a);let l=t.urlCallback||function(e){r?r.location.href=e:r=openBrowserPopup(e)};await l(c)}catch(e){cleanup(),o(new ClientResponseError(e))}}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}class AsyncAuthStore extends BaseAuthStore{constructor(e){super(),this.queue=[],this.saveFunc=e.save,this.clearFunc=e.clear,this._enqueue((()=>this._loadInitial(e.initial)))}save(e,t){super.save(e,t);let s="";try{s=JSON.stringify({token:e,model:t})}catch(e){console.warn("AsyncAuthStore: failed to stringify the new state")}this._enqueue((()=>this.saveFunc(s)))}clear(){super.clear(),this.clearFunc?this._enqueue((()=>this.clearFunc())):this._enqueue((()=>this.saveFunc("")))}async _loadInitial(e){try{if(e=await e){let t;"string"==typeof e?t=JSON.parse(e)||{}:"object"==typeof e&&(t=e),this.save(t.token||"",t.model||null)}}catch(e){}}_enqueue(e){this.queue.push(e),1==this.queue.length&&this._dequeue()}_dequeue(){this.queue.length&&this.queue[0]().finally((()=>{this.queue.shift(),this.queue.length&&this._dequeue()}))}}export{AdminService,AsyncAuthStore,BaseAuthStore,ClientResponseError,CollectionService,CrudService,HealthService,LocalAuthStore,LogService,RealtimeService,RecordService,cookieParse,cookieSerialize,Client as default,getTokenPayload,isTokenExpired,normalizeUnknownQueryParams}; +class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=cookieParse(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){const s={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},n=getTokenPayload(this.token);s.expires=n?.exp?new Date(1e3*n.exp):new Date("1970-01-01"),e=Object.assign({},s,e);const r={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let o=cookieSerialize(t,JSON.stringify(r),e);const a="undefined"!=typeof Blob?new Blob([o]).size:o.length;if(r.model&&a>4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{};let s=null;t.urlCallback||(s=openBrowserPopup(void 0));const i=new RealtimeService(this.client);function cleanup(){s?.close(),i.unsubscribe()}const n={},r=t.requestKey;return r&&(n.requestKey=r),this.listAuthMethods(n).then((e=>{const n=e.authProviders.find((e=>e.name===t.provider));if(!n)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const o=this.client.buildUrl("/api/oauth2-redirect"),a=r?this.client.cancelControllers?.[r]:void 0;return a&&(a.signal.onabort=()=>{cleanup()}),new Promise((async(e,r)=>{try{await i.subscribe("@oauth2",(async s=>{const c=i.clientId;try{if(!s.state||c!==s.state)throw new Error("State parameters don't match.");if(s.error||!s.code)throw new Error("OAuth2 redirect error or missing code: "+s.error);const i=Object.assign({},t);delete i.provider,delete i.scopes,delete i.createData,delete i.urlCallback,a?.signal?.onabort&&(a.signal.onabort=null);const r=await this.authWithOAuth2Code(n.name,s.code,n.codeVerifier,o,t.createData,i);e(r)}catch(e){r(new ClientResponseError(e))}cleanup()}));const c={state:i.clientId};t.scopes?.length&&(c.scope=t.scopes.join(" "));const l=this._replaceQueryParams(n.authUrl+o,c);let h=t.urlCallback||function(e){s?s.location.href=e:s=openBrowserPopup(e)};await h(l)}catch(e){cleanup(),r(new ClientResponseError(e))}}))})).catch((e=>{throw cleanup(),e}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}class AsyncAuthStore extends BaseAuthStore{constructor(e){super(),this.queue=[],this.saveFunc=e.save,this.clearFunc=e.clear,this._enqueue((()=>this._loadInitial(e.initial)))}save(e,t){super.save(e,t);let s="";try{s=JSON.stringify({token:e,model:t})}catch(e){console.warn("AsyncAuthStore: failed to stringify the new state")}this._enqueue((()=>this.saveFunc(s)))}clear(){super.clear(),this.clearFunc?this._enqueue((()=>this.clearFunc())):this._enqueue((()=>this.saveFunc("")))}async _loadInitial(e){try{if(e=await e){let t;"string"==typeof e?t=JSON.parse(e)||{}:"object"==typeof e&&(t=e),this.save(t.token||"",t.model||null)}}catch(e){}}_enqueue(e){this.queue.push(e),1==this.queue.length&&this._dequeue()}_dequeue(){this.queue.length&&this.queue[0]().finally((()=>{this.queue.shift(),this.queue.length&&this._dequeue()}))}}export{AdminService,AsyncAuthStore,BaseAuthStore,ClientResponseError,CollectionService,CrudService,HealthService,LocalAuthStore,LogService,RealtimeService,RecordService,cookieParse,cookieSerialize,Client as default,getTokenPayload,isTokenExpired,normalizeUnknownQueryParams}; //# sourceMappingURL=pocketbase.es.js.map diff --git a/dist/pocketbase.es.js.map b/dist/pocketbase.es.js.map index 1178b42..bb562de 100644 --- a/dist/pocketbase.es.js.map +++ b/dist/pocketbase.es.js.map @@ -1 +1 @@ -{"version":3,"file":"pocketbase.es.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts","../src/stores/AsyncAuthStore.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * _Site-note_: when creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n async authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n const authMethods = await this.listAuthMethods();\n\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before the async call due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\nexport type AsyncSaveFunc = (serializedPayload: string) => Promise;\n\nexport type AsyncClearFunc = () => Promise;\n\ntype queueFunc = () => Promise;\n\n/**\n * AsyncAuthStore is a helper auth store implementation\n * that could be used with any external async persistent layer\n * (key-value db, local file, etc.).\n *\n * Here is an example with the React Native AsyncStorage package:\n *\n * ```\n * import AsyncStorage from \"@react-native-async-storage/async-storage\";\n * import PocketBase, { AsyncAuthStore } from \"pocketbase\";\n *\n * const store = new AsyncAuthStore({\n * save: async (serialized) => AsyncStorage.setItem(\"pb_auth\", serialized),\n * initial: AsyncStorage.getItem(\"pb_auth\"),\n * });\n *\n * const pb = new PocketBase(\"https://example.com\", store)\n * ```\n */\nexport class AsyncAuthStore extends BaseAuthStore {\n private saveFunc: AsyncSaveFunc;\n private clearFunc?: AsyncClearFunc;\n private queue: Array = [];\n\n constructor(config: {\n // The async function that is called every time\n // when the auth store state needs to be persisted.\n save: AsyncSaveFunc;\n\n /// An *optional* async function that is called every time\n /// when the auth store needs to be cleared.\n ///\n /// If not explicitly set, `saveFunc` with empty data will be used.\n clear?: AsyncClearFunc;\n\n // An *optional* initial data to load into the store.\n initial?: string | Promise;\n }) {\n super();\n\n this.saveFunc = config.save;\n this.clearFunc = config.clear;\n\n this._enqueue(() => this._loadInitial(config.initial));\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel): void {\n super.save(token, model);\n\n let value = \"\";\n try {\n value = JSON.stringify({ token, model });\n } catch (err) {\n console.warn(\"AsyncAuthStore: failed to stringify the new state\");\n }\n\n this._enqueue(() => this.saveFunc(value));\n }\n\n /**\n * @inheritdoc\n */\n clear(): void {\n super.clear();\n\n if (this.clearFunc) {\n this._enqueue(() => this.clearFunc!());\n } else {\n this._enqueue(() => this.saveFunc(\"\"));\n }\n }\n\n /**\n * Initializes the auth store state.\n */\n private async _loadInitial(payload?: string | Promise) {\n try {\n payload = await payload;\n\n if (payload) {\n let parsed;\n if (typeof payload === \"string\") {\n parsed = JSON.parse(payload) || {};\n } else if (typeof payload === \"object\") {\n parsed = payload;\n }\n\n this.save(parsed.token || \"\", parsed.model || null);\n }\n } catch (_) {}\n }\n\n /**\n * Appends an async function to the queue.\n */\n private _enqueue(asyncCallback: () => Promise) {\n this.queue.push(asyncCallback);\n\n if (this.queue.length == 1) {\n this._dequeue();\n }\n }\n\n /**\n * Starts the queue processing.\n */\n private _dequeue() {\n if (!this.queue.length) {\n return;\n }\n\n this.queue[0]().finally(() => {\n this.queue.shift();\n\n if (!this.queue.length) {\n return;\n }\n\n this._dequeue();\n });\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieParse","str","options","result","decode","assign","defaultDecode","index","length","eqIdx","indexOf","endIdx","lastIndexOf","key","slice","trim","undefined","val","charCodeAt","_","cookieSerialize","opt","encode","defaultEncode","test","TypeError","value","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","exp","now","atob","input","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","rawData","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","find","eagerDefaultPopup","cleanup","urlCallback","openBrowserPopup","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","signal","FormData","hasBlobField","form","v","append","values","File","encodedKey","AsyncAuthStore","queue","saveFunc","clearFunc","_enqueue","_loadInitial","initial","parsed","asyncCallback","_dequeue","finally","shift"],"mappings":"AAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UAAYN,EAAQM,QACzBJ,KAAKK,cAAgBP,EAAQO,cAEJ,OAArBP,EAAQK,UAAiD,iBAArBL,EAAQK,SAC5CH,KAAKG,SAAWL,EAAQK,SACA,OAAjBL,EAAQW,MAAyC,iBAAjBX,EAAQW,KAC/CT,KAAKG,SAAWL,EAAQW,KAExBT,KAAKG,SAAW,IAInBH,KAAKK,eAAmBP,aAAmBH,sBAC5CK,KAAKK,cAAgBP,GAGG,oBAAjBY,cAAgCZ,aAAmBY,eAC1DV,KAAKI,SAAU,GAGnBJ,KAAKW,KAAO,uBAAyBX,KAAKE,OAC1CF,KAAKY,QAAUZ,KAAKG,UAAUS,QACzBZ,KAAKY,UACFZ,KAAKI,QACLJ,KAAKY,QACD,mHACGZ,KAAKK,eAAeQ,OAAOD,SAASE,SAAS,oBACpDd,KAAKY,QACD,qJAEJZ,KAAKY,QAA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AOnE,GAAK,CACjB,CAKO,QAAA6Y,CAASI,GACbrb,KAAK8a,MAAM7S,KAAKoT,GAES,GAArBrb,KAAK8a,MAAMrZ,QACXzB,KAAKsb,UAEZ,CAKO,QAAAA,GACCtb,KAAK8a,MAAMrZ,QAIhBzB,KAAK8a,MAAM,KAAKS,SAAQ,KACpBvb,KAAK8a,MAAMU,QAENxb,KAAK8a,MAAMrZ,QAIhBzB,KAAKsb,UAAU,GAEtB"} \ No newline at end of file +{"version":3,"file":"pocketbase.es.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts","../src/stores/AsyncAuthStore.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * Note1: When creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * Note2: Safari may block the default `urlCallback` popup because\n * it doesn't allow `window.open` calls as part of an `async` click functions.\n * To workaround this you can either change your click handler to not be marked as `async`\n * OR manually call `window.open` before your `async` function and use the\n * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061).\n * For example:\n * ```js\n * \n * ...\n * document.getElementById(\"btn\").addEventListener(\"click\", () => {\n * pb.collection(\"users\").authWithOAuth2({\n * provider: \"gitlab\",\n * }).then((authData) => {\n * console.log(authData)\n * }).catch((err) => {\n * console.log(err, err.originalError);\n * });\n * })\n * ```\n *\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before any async calls due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n const requestKeyOptions: SendOptions = {};\n const requestKey = config.requestKey\n if (requestKey) {\n requestKeyOptions.requestKey = requestKey;\n }\n\n return this.listAuthMethods(requestKeyOptions).then((authMethods) => {\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // find the AbortController associated with the current request key (if any)\n const cancelController = requestKey ? this.client['cancelControllers']?.[requestKey] : undefined;\n if (cancelController) {\n cancelController.signal.onabort = () => {\n cleanup();\n }\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n // reset the cancelController listener as it will be triggered by the next api call\n if (cancelController?.signal?.onabort) {\n cancelController.signal.onabort = null\n }\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }).catch((err) => {\n cleanup();\n throw err // rethrow\n }) as Promise>;\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\nexport type AsyncSaveFunc = (serializedPayload: string) => Promise;\n\nexport type AsyncClearFunc = () => Promise;\n\ntype queueFunc = () => Promise;\n\n/**\n * AsyncAuthStore is a helper auth store implementation\n * that could be used with any external async persistent layer\n * (key-value db, local file, etc.).\n *\n * Here is an example with the React Native AsyncStorage package:\n *\n * ```\n * import AsyncStorage from \"@react-native-async-storage/async-storage\";\n * import PocketBase, { AsyncAuthStore } from \"pocketbase\";\n *\n * const store = new AsyncAuthStore({\n * save: async (serialized) => AsyncStorage.setItem(\"pb_auth\", serialized),\n * initial: AsyncStorage.getItem(\"pb_auth\"),\n * });\n *\n * const pb = new PocketBase(\"https://example.com\", store)\n * ```\n */\nexport class AsyncAuthStore extends BaseAuthStore {\n private saveFunc: AsyncSaveFunc;\n private clearFunc?: AsyncClearFunc;\n private queue: Array = [];\n\n constructor(config: {\n // The async function that is called every time\n // when the auth store state needs to be persisted.\n save: AsyncSaveFunc;\n\n /// An *optional* async function that is called every time\n /// when the auth store needs to be cleared.\n ///\n /// If not explicitly set, `saveFunc` with empty data will be used.\n clear?: AsyncClearFunc;\n\n // An *optional* initial data to load into the store.\n initial?: string | Promise;\n }) {\n super();\n\n this.saveFunc = config.save;\n this.clearFunc = config.clear;\n\n this._enqueue(() => this._loadInitial(config.initial));\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel): void {\n super.save(token, model);\n\n let value = \"\";\n try {\n value = JSON.stringify({ token, model });\n } catch (err) {\n console.warn(\"AsyncAuthStore: failed to stringify the new state\");\n }\n\n this._enqueue(() => this.saveFunc(value));\n }\n\n /**\n * @inheritdoc\n */\n clear(): void {\n super.clear();\n\n if (this.clearFunc) {\n this._enqueue(() => this.clearFunc!());\n } else {\n this._enqueue(() => this.saveFunc(\"\"));\n }\n }\n\n /**\n * Initializes the auth store state.\n */\n private async _loadInitial(payload?: string | Promise) {\n try {\n payload = await payload;\n\n if (payload) {\n let parsed;\n if (typeof payload === \"string\") {\n parsed = JSON.parse(payload) || {};\n } else if (typeof payload === \"object\") {\n parsed = payload;\n }\n\n this.save(parsed.token || \"\", parsed.model || null);\n }\n } catch (_) {}\n }\n\n /**\n * Appends an async function to the queue.\n */\n private _enqueue(asyncCallback: () => Promise) {\n this.queue.push(asyncCallback);\n\n if (this.queue.length == 1) {\n this._dequeue();\n }\n }\n\n /**\n * Starts the queue processing.\n */\n private _dequeue() {\n if (!this.queue.length) {\n return;\n }\n\n this.queue[0]().finally(() => {\n this.queue.shift();\n\n if (!this.queue.length) {\n return;\n }\n\n this._dequeue();\n });\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieParse","str","options","result","decode","assign","defaultDecode","index","length","eqIdx","indexOf","endIdx","lastIndexOf","key","slice","trim","undefined","val","charCodeAt","_","cookieSerialize","opt","encode","defaultEncode","test","TypeError","value","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","exp","now","atob","input","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","rawData","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","eagerDefaultPopup","urlCallback","openBrowserPopup","cleanup","requestKeyOptions","authMethods","find","cancelController","signal","onabort","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","FormData","hasBlobField","form","v","append","values","File","encodedKey","AsyncAuthStore","queue","saveFunc","clearFunc","_enqueue","_loadInitial","initial","parsed","asyncCallback","_dequeue","finally","shift"],"mappings":"AAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UAAYN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s index 4a5c756..d54572c 100644 --- a/dist/pocketbase.es.mjs +++ b/dist/pocketbase.es.mjs @@ -1,2 +1,2 @@ -class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=cookieParse(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){const s={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},n=getTokenPayload(this.token);s.expires=n?.exp?new Date(1e3*n.exp):new Date("1970-01-01"),e=Object.assign({},s,e);const r={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let o=cookieSerialize(t,JSON.stringify(r),e);const a="undefined"!=typeof Blob?new Blob([o]).size:o.length;if(r.model&&a>4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}async authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{},s=(await this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!s)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const i=this.client.buildUrl("/api/oauth2-redirect"),n=new RealtimeService(this.client);let r=null;function cleanup(){r?.close(),n.unsubscribe()}return t.urlCallback||(r=openBrowserPopup(void 0)),new Promise((async(e,o)=>{try{await n.subscribe("@oauth2",(async r=>{const a=n.clientId;try{if(!r.state||a!==r.state)throw new Error("State parameters don't match.");if(r.error||!r.code)throw new Error("OAuth2 redirect error or missing code: "+r.error);const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const o=await this.authWithOAuth2Code(s.name,r.code,s.codeVerifier,i,t.createData,n);e(o)}catch(e){o(new ClientResponseError(e))}cleanup()}));const a={state:n.clientId};t.scopes?.length&&(a.scope=t.scopes.join(" "));const c=this._replaceQueryParams(s.authUrl+i,a);let l=t.urlCallback||function(e){r?r.location.href=e:r=openBrowserPopup(e)};await l(c)}catch(e){cleanup(),o(new ClientResponseError(e))}}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}class AsyncAuthStore extends BaseAuthStore{constructor(e){super(),this.queue=[],this.saveFunc=e.save,this.clearFunc=e.clear,this._enqueue((()=>this._loadInitial(e.initial)))}save(e,t){super.save(e,t);let s="";try{s=JSON.stringify({token:e,model:t})}catch(e){console.warn("AsyncAuthStore: failed to stringify the new state")}this._enqueue((()=>this.saveFunc(s)))}clear(){super.clear(),this.clearFunc?this._enqueue((()=>this.clearFunc())):this._enqueue((()=>this.saveFunc("")))}async _loadInitial(e){try{if(e=await e){let t;"string"==typeof e?t=JSON.parse(e)||{}:"object"==typeof e&&(t=e),this.save(t.token||"",t.model||null)}}catch(e){}}_enqueue(e){this.queue.push(e),1==this.queue.length&&this._dequeue()}_dequeue(){this.queue.length&&this.queue[0]().finally((()=>{this.queue.shift(),this.queue.length&&this._dequeue()}))}}export{AdminService,AsyncAuthStore,BaseAuthStore,ClientResponseError,CollectionService,CrudService,HealthService,LocalAuthStore,LogService,RealtimeService,RecordService,cookieParse,cookieSerialize,Client as default,getTokenPayload,isTokenExpired,normalizeUnknownQueryParams}; +class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=cookieParse(e||"")[t]||"";let n={};try{n=JSON.parse(s),(null===typeof n||"object"!=typeof n||Array.isArray(n))&&(n={})}catch(e){}this.save(n.token||"",n.model||null)}exportToCookie(e,t=i){const s={secure:!0,sameSite:!0,httpOnly:!0,path:"/"},n=getTokenPayload(this.token);s.expires=n?.exp?new Date(1e3*n.exp):new Date("1970-01-01"),e=Object.assign({},s,e);const r={token:this.token,model:this.model?JSON.parse(JSON.stringify(this.model)):null};let o=cookieSerialize(t,JSON.stringify(r),e);const a="undefined"!=typeof Blob?new Blob([o]).size:o.length;if(r.model&&a>4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{};let s=null;t.urlCallback||(s=openBrowserPopup(void 0));const i=new RealtimeService(this.client);function cleanup(){s?.close(),i.unsubscribe()}const n={},r=t.requestKey;return r&&(n.requestKey=r),this.listAuthMethods(n).then((e=>{const n=e.authProviders.find((e=>e.name===t.provider));if(!n)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const o=this.client.buildUrl("/api/oauth2-redirect"),a=r?this.client.cancelControllers?.[r]:void 0;return a&&(a.signal.onabort=()=>{cleanup()}),new Promise((async(e,r)=>{try{await i.subscribe("@oauth2",(async s=>{const c=i.clientId;try{if(!s.state||c!==s.state)throw new Error("State parameters don't match.");if(s.error||!s.code)throw new Error("OAuth2 redirect error or missing code: "+s.error);const i=Object.assign({},t);delete i.provider,delete i.scopes,delete i.createData,delete i.urlCallback,a?.signal?.onabort&&(a.signal.onabort=null);const r=await this.authWithOAuth2Code(n.name,s.code,n.codeVerifier,o,t.createData,i);e(r)}catch(e){r(new ClientResponseError(e))}cleanup()}));const c={state:i.clientId};t.scopes?.length&&(c.scope=t.scopes.join(" "));const l=this._replaceQueryParams(n.authUrl+o,c);let h=t.urlCallback||function(e){s?s.location.href=e:s=openBrowserPopup(e)};await h(l)}catch(e){cleanup(),r(new ClientResponseError(e))}}))})).catch((e=>{throw cleanup(),e}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}class AsyncAuthStore extends BaseAuthStore{constructor(e){super(),this.queue=[],this.saveFunc=e.save,this.clearFunc=e.clear,this._enqueue((()=>this._loadInitial(e.initial)))}save(e,t){super.save(e,t);let s="";try{s=JSON.stringify({token:e,model:t})}catch(e){console.warn("AsyncAuthStore: failed to stringify the new state")}this._enqueue((()=>this.saveFunc(s)))}clear(){super.clear(),this.clearFunc?this._enqueue((()=>this.clearFunc())):this._enqueue((()=>this.saveFunc("")))}async _loadInitial(e){try{if(e=await e){let t;"string"==typeof e?t=JSON.parse(e)||{}:"object"==typeof e&&(t=e),this.save(t.token||"",t.model||null)}}catch(e){}}_enqueue(e){this.queue.push(e),1==this.queue.length&&this._dequeue()}_dequeue(){this.queue.length&&this.queue[0]().finally((()=>{this.queue.shift(),this.queue.length&&this._dequeue()}))}}export{AdminService,AsyncAuthStore,BaseAuthStore,ClientResponseError,CollectionService,CrudService,HealthService,LocalAuthStore,LogService,RealtimeService,RecordService,cookieParse,cookieSerialize,Client as default,getTokenPayload,isTokenExpired,normalizeUnknownQueryParams}; //# sourceMappingURL=pocketbase.es.mjs.map diff --git a/dist/pocketbase.es.mjs.map b/dist/pocketbase.es.mjs.map index d88137e..088482f 100644 --- a/dist/pocketbase.es.mjs.map +++ b/dist/pocketbase.es.mjs.map @@ -1 +1 @@ -{"version":3,"file":"pocketbase.es.mjs","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts","../src/stores/AsyncAuthStore.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * _Site-note_: when creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n async authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n const authMethods = await this.listAuthMethods();\n\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before the async call due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\nexport type AsyncSaveFunc = (serializedPayload: string) => Promise;\n\nexport type AsyncClearFunc = () => Promise;\n\ntype queueFunc = () => Promise;\n\n/**\n * AsyncAuthStore is a helper auth store implementation\n * that could be used with any external async persistent layer\n * (key-value db, local file, etc.).\n *\n * Here is an example with the React Native AsyncStorage package:\n *\n * ```\n * import AsyncStorage from \"@react-native-async-storage/async-storage\";\n * import PocketBase, { AsyncAuthStore } from \"pocketbase\";\n *\n * const store = new AsyncAuthStore({\n * save: async (serialized) => AsyncStorage.setItem(\"pb_auth\", serialized),\n * initial: AsyncStorage.getItem(\"pb_auth\"),\n * });\n *\n * const pb = new PocketBase(\"https://example.com\", store)\n * ```\n */\nexport class AsyncAuthStore extends BaseAuthStore {\n private saveFunc: AsyncSaveFunc;\n private clearFunc?: AsyncClearFunc;\n private queue: Array = [];\n\n constructor(config: {\n // The async function that is called every time\n // when the auth store state needs to be persisted.\n save: AsyncSaveFunc;\n\n /// An *optional* async function that is called every time\n /// when the auth store needs to be cleared.\n ///\n /// If not explicitly set, `saveFunc` with empty data will be used.\n clear?: AsyncClearFunc;\n\n // An *optional* initial data to load into the store.\n initial?: string | Promise;\n }) {\n super();\n\n this.saveFunc = config.save;\n this.clearFunc = config.clear;\n\n this._enqueue(() => this._loadInitial(config.initial));\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel): void {\n super.save(token, model);\n\n let value = \"\";\n try {\n value = JSON.stringify({ token, model });\n } catch (err) {\n console.warn(\"AsyncAuthStore: failed to stringify the new state\");\n }\n\n this._enqueue(() => this.saveFunc(value));\n }\n\n /**\n * @inheritdoc\n */\n clear(): void {\n super.clear();\n\n if (this.clearFunc) {\n this._enqueue(() => this.clearFunc!());\n } else {\n this._enqueue(() => this.saveFunc(\"\"));\n }\n }\n\n /**\n * Initializes the auth store state.\n */\n private async _loadInitial(payload?: string | Promise) {\n try {\n payload = await payload;\n\n if (payload) {\n let parsed;\n if (typeof payload === \"string\") {\n parsed = JSON.parse(payload) || {};\n } else if (typeof payload === \"object\") {\n parsed = payload;\n }\n\n this.save(parsed.token || \"\", parsed.model || null);\n }\n } catch (_) {}\n }\n\n /**\n * Appends an async function to the queue.\n */\n private _enqueue(asyncCallback: () => Promise) {\n this.queue.push(asyncCallback);\n\n if (this.queue.length == 1) {\n this._dequeue();\n }\n }\n\n /**\n * Starts the queue processing.\n */\n private _dequeue() {\n if (!this.queue.length) {\n return;\n }\n\n this.queue[0]().finally(() => {\n this.queue.shift();\n\n if (!this.queue.length) {\n return;\n }\n\n this._dequeue();\n });\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieParse","str","options","result","decode","assign","defaultDecode","index","length","eqIdx","indexOf","endIdx","lastIndexOf","key","slice","trim","undefined","val","charCodeAt","_","cookieSerialize","opt","encode","defaultEncode","test","TypeError","value","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","exp","now","atob","input","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","rawData","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","find","eagerDefaultPopup","cleanup","urlCallback","openBrowserPopup","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","signal","FormData","hasBlobField","form","v","append","values","File","encodedKey","AsyncAuthStore","queue","saveFunc","clearFunc","_enqueue","_loadInitial","initial","parsed","asyncCallback","_dequeue","finally","shift"],"mappings":"AAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW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gW,uBAAuB1U,cAKhC,WAAAtG,CAAYgU,GAcR9T,QAhBIC,KAAK8a,MAAqB,GAkB9B9a,KAAK+a,SAAWlH,EAAOjN,KACvB5G,KAAKgb,UAAYnH,EAAO/M,MAExB9G,KAAKib,UAAS,IAAMjb,KAAKkb,aAAarH,EAAOsH,UAChD,CAKD,IAAAvU,CAAKpC,EAAe+B,GAChBxG,MAAM6G,KAAKpC,EAAO+B,GAElB,IAAI5D,EAAQ,GACZ,IACIA,EAAQmC,KAAKwC,UAAU,CAAE9C,QAAO+B,SACnC,CAAC,MAAO0K,GACLzE,QAAQC,KAAK,oDAChB,CAEDzM,KAAKib,UAAS,IAAMjb,KAAK+a,SAASpY,IACrC,CAKD,KAAAmE,GACI/G,MAAM+G,QAEF9G,KAAKgb,UACLhb,KAAKib,UAAS,IAAMjb,KAAKgb,cAEzBhb,KAAKib,UAAS,IAAMjb,KAAK+a,SAAS,KAEzC,CAKO,kBAAMG,CAAa/V,GACvB,IAGI,GAFAA,QAAgBA,EAEH,CACT,IAAIiW,EACmB,iBAAZjW,EACPiW,EAAStW,KAAKC,MAAMI,IAAY,CAAA,EACN,iBAAZA,IACdiW,EAASjW,GAGbnF,KAAK4G,KAAKwU,EAAO5W,OAAS,GAAI4W,EAAO7U,OAAS,KACjD,CACJ,CAAC,MAAOnE,GAAK,CACjB,CAKO,QAAA6Y,CAASI,GACbrb,KAAK8a,MAAM7S,KAAKoT,GAES,GAArBrb,KAAK8a,MAAMrZ,QACXzB,KAAKsb,UAEZ,CAKO,QAAAA,GACCtb,KAAK8a,MAAMrZ,QAIhBzB,KAAK8a,MAAM,KAAKS,SAAQ,KACpBvb,KAAK8a,MAAMU,QAENxb,KAAK8a,MAAMrZ,QAIhBzB,KAAKsb,UAAU,GAEtB"} \ No newline at end of file +{"version":3,"file":"pocketbase.es.mjs","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts","../src/stores/AsyncAuthStore.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * Note1: When creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * Note2: Safari may block the default `urlCallback` popup because\n * it doesn't allow `window.open` calls as part of an `async` click functions.\n * To workaround this you can either change your click handler to not be marked as `async`\n * OR manually call `window.open` before your `async` function and use the\n * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061).\n * For example:\n * ```js\n * \n * ...\n * document.getElementById(\"btn\").addEventListener(\"click\", () => {\n * pb.collection(\"users\").authWithOAuth2({\n * provider: \"gitlab\",\n * }).then((authData) => {\n * console.log(authData)\n * }).catch((err) => {\n * console.log(err, err.originalError);\n * });\n * })\n * ```\n *\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before any async calls due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n const requestKeyOptions: SendOptions = {};\n const requestKey = config.requestKey\n if (requestKey) {\n requestKeyOptions.requestKey = requestKey;\n }\n\n return this.listAuthMethods(requestKeyOptions).then((authMethods) => {\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // find the AbortController associated with the current request key (if any)\n const cancelController = requestKey ? this.client['cancelControllers']?.[requestKey] : undefined;\n if (cancelController) {\n cancelController.signal.onabort = () => {\n cleanup();\n }\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n // reset the cancelController listener as it will be triggered by the next api call\n if (cancelController?.signal?.onabort) {\n cancelController.signal.onabort = null\n }\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }).catch((err) => {\n cleanup();\n throw err // rethrow\n }) as Promise>;\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\nexport type AsyncSaveFunc = (serializedPayload: string) => Promise;\n\nexport type AsyncClearFunc = () => Promise;\n\ntype queueFunc = () => Promise;\n\n/**\n * AsyncAuthStore is a helper auth store implementation\n * that could be used with any external async persistent layer\n * (key-value db, local file, etc.).\n *\n * Here is an example with the React Native AsyncStorage package:\n *\n * ```\n * import AsyncStorage from \"@react-native-async-storage/async-storage\";\n * import PocketBase, { AsyncAuthStore } from \"pocketbase\";\n *\n * const store = new AsyncAuthStore({\n * save: async (serialized) => AsyncStorage.setItem(\"pb_auth\", serialized),\n * initial: AsyncStorage.getItem(\"pb_auth\"),\n * });\n *\n * const pb = new PocketBase(\"https://example.com\", store)\n * ```\n */\nexport class AsyncAuthStore extends BaseAuthStore {\n private saveFunc: AsyncSaveFunc;\n private clearFunc?: AsyncClearFunc;\n private queue: Array = [];\n\n constructor(config: {\n // The async function that is called every time\n // when the auth store state needs to be persisted.\n save: AsyncSaveFunc;\n\n /// An *optional* async function that is called every time\n /// when the auth store needs to be cleared.\n ///\n /// If not explicitly set, `saveFunc` with empty data will be used.\n clear?: AsyncClearFunc;\n\n // An *optional* initial data to load into the store.\n initial?: string | Promise;\n }) {\n super();\n\n this.saveFunc = config.save;\n this.clearFunc = config.clear;\n\n this._enqueue(() => this._loadInitial(config.initial));\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel): void {\n super.save(token, model);\n\n let value = \"\";\n try {\n value = JSON.stringify({ token, model });\n } catch (err) {\n console.warn(\"AsyncAuthStore: failed to stringify the new state\");\n }\n\n this._enqueue(() => this.saveFunc(value));\n }\n\n /**\n * @inheritdoc\n */\n clear(): void {\n super.clear();\n\n if (this.clearFunc) {\n this._enqueue(() => this.clearFunc!());\n } else {\n this._enqueue(() => this.saveFunc(\"\"));\n }\n }\n\n /**\n * Initializes the auth store state.\n */\n private async _loadInitial(payload?: string | Promise) {\n try {\n payload = await payload;\n\n if (payload) {\n let parsed;\n if (typeof payload === \"string\") {\n parsed = JSON.parse(payload) || {};\n } else if (typeof payload === \"object\") {\n parsed = payload;\n }\n\n this.save(parsed.token || \"\", parsed.model || null);\n }\n } catch (_) {}\n }\n\n /**\n * Appends an async function to the queue.\n */\n private _enqueue(asyncCallback: () => Promise) {\n this.queue.push(asyncCallback);\n\n if (this.queue.length == 1) {\n this._dequeue();\n }\n }\n\n /**\n * Starts the queue processing.\n */\n private _dequeue() {\n if (!this.queue.length) {\n return;\n }\n\n this.queue[0]().finally(() => {\n this.queue.shift();\n\n if (!this.queue.length) {\n return;\n }\n\n this._dequeue();\n });\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieParse","str","options","result","decode","assign","defaultDecode","index","length","eqIdx","indexOf","endIdx","lastIndexOf","key","slice","trim","undefined","val","charCodeAt","_","cookieSerialize","opt","encode","defaultEncode","test","TypeError","value","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","exp","now","atob","input","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","rawData","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","eagerDefaultPopup","urlCallback","openBrowserPopup","cleanup","requestKeyOptions","authMethods","find","cancelController","signal","onabort","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","FormData","hasBlobField","form","v","append","values","File","encodedKey","AsyncAuthStore","queue","saveFunc","clearFunc","_enqueue","_loadInitial","initial","parsed","asyncCallback","_dequeue","finally","shift"],"mappings":"AAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UAAYN,EAAQM,QACzBJ,KAAKK,cAAgBP,EAAQO,cAEJ,OAArBP,EAAQK,UAAiD,iBAArBL,EAAQK,SAC5CH,KAAKG,SAAWL,EAAQK,SACA,OAAjBL,EAAQW,MAAyC,iBAAjBX,EAAQW,KAC/CT,KAAKG,SAAWL,EAAQW,KAExBT,KAAKG,SAAW,IAInBH,KAAKK,eAAmBP,aAAmBH,sBAC5CK,KAAKK,cAAgBP,GAGG,oBAAjBY,cAAgCZ,aAAmBY,eAC1DV,KAAKI,SAAU,GAGnBJ,KAAKW,KAAO,uBAAyBX,KAAKE,OAC1CF,KAAKY,QAAUZ,KAAKG,UAAUS,QACzBZ,KAAKY,U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,SACnC,CAAC,MAAO0K,GACLzE,QAAQC,KAAK,oDAChB,CAEDzM,KAAKqb,UAAS,IAAMrb,KAAKmb,SAASxY,IACrC,CAKD,KAAAmE,GACI/G,MAAM+G,QAEF9G,KAAKob,UACLpb,KAAKqb,UAAS,IAAMrb,KAAKob,cAEzBpb,KAAKqb,UAAS,IAAMrb,KAAKmb,SAAS,KAEzC,CAKO,kBAAMG,CAAanW,GACvB,IAGI,GAFAA,QAAgBA,EAEH,CACT,IAAIqW,EACmB,iBAAZrW,EACPqW,EAAS1W,KAAKC,MAAMI,IAAY,CAAA,EACN,iBAAZA,IACdqW,EAASrW,GAGbnF,KAAK4G,KAAK4U,EAAOhX,OAAS,GAAIgX,EAAOjV,OAAS,KACjD,CACJ,CAAC,MAAOnE,GAAK,CACjB,CAKO,QAAAiZ,CAASI,GACbzb,KAAKkb,MAAMjT,KAAKwT,GAES,GAArBzb,KAAKkb,MAAMzZ,QACXzB,KAAK0b,UAEZ,CAKO,QAAAA,GACC1b,KAAKkb,MAAMzZ,QAIhBzB,KAAKkb,MAAM,KAAKS,SAAQ,KACpB3b,KAAKkb,MAAMU,QAEN5b,KAAKkb,MAAMzZ,QAIhBzB,KAAK0b,UAAU,GAEtB"} \ No newline at end of file diff --git a/dist/pocketbase.iife.d.ts b/dist/pocketbase.iife.d.ts index 2353cb1..5f07fd6 100644 --- a/dist/pocketbase.iife.d.ts +++ b/dist/pocketbase.iife.d.ts @@ -776,10 +776,31 @@ declare class RecordService extends CrudService { * }) * ``` * - * _Site-note_: when creating the OAuth2 app in the provider dashboard + * Note1: When creating the OAuth2 app in the provider dashboard * you have to configure `https://yourdomain.com/api/oauth2-redirect` * as redirect URL. * + * Note2: Safari may block the default `urlCallback` popup because + * it doesn't allow `window.open` calls as part of an `async` click functions. + * To workaround this you can either change your click handler to not be marked as `async` + * OR manually call `window.open` before your `async` function and use the + * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061). + * For example: + * ```js + * + * ... + * document.getElementById("btn").addEventListener("click", () => { + * pb.collection("users").authWithOAuth2({ + * provider: "gitlab", + * }).then((authData) => { + * console.log(authData) + * }).catch((err) => { + * console.log(err, err.originalError); + * }); + * }) + * ``` + * + * * @throws {ClientResponseError} */ authWithOAuth2(options: OAuth2AuthConfig): Promise>; diff --git a/dist/pocketbase.iife.js b/dist/pocketbase.iife.js index e125977..ebdfa7d 100644 --- a/dist/pocketbase.iife.js +++ b/dist/pocketbase.iife.js @@ -1,2 +1,2 @@ -var PocketBase=function(){"use strict";class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,s,i){const n=Object.assign({},i||{}),r=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const o=r(s);if(o&&!e.test(o))throw new TypeError("argument val is invalid");let a=t+"="+o;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}const t="undefined"!=typeof navigator&&"ReactNative"===navigator.product||"undefined"!=typeof global&&global.HermesInternal;let s;function getTokenPayload(e){if(e)try{const t=decodeURIComponent(s(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let s=getTokenPayload(e);return!(Object.keys(s).length>0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}async authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{},s=(await this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!s)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const i=this.client.buildUrl("/api/oauth2-redirect"),n=new RealtimeService(this.client);let r=null;function cleanup(){r?.close(),n.unsubscribe()}return t.urlCallback||(r=openBrowserPopup(void 0)),new Promise((async(e,o)=>{try{await n.subscribe("@oauth2",(async r=>{const a=n.clientId;try{if(!r.state||a!==r.state)throw new Error("State parameters don't match.");if(r.error||!r.code)throw new Error("OAuth2 redirect error or missing code: "+r.error);const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const o=await this.authWithOAuth2Code(s.name,r.code,s.codeVerifier,i,t.createData,n);e(o)}catch(e){o(new ClientResponseError(e))}cleanup()}));const a={state:n.clientId};t.scopes?.length&&(a.scope=t.scopes.join(" "));const c=this._replaceQueryParams(s.authUrl+i,a);let l=t.urlCallback||function(e){r?r.location.href=e:r=openBrowserPopup(e)};await l(c)}catch(e){cleanup(),o(new ClientResponseError(e))}}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}return class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}}(); +var PocketBase=function(){"use strict";class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,s,i){const n=Object.assign({},i||{}),r=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const o=r(s);if(o&&!e.test(o))throw new TypeError("argument val is invalid");let a=t+"="+o;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}const t="undefined"!=typeof navigator&&"ReactNative"===navigator.product||"undefined"!=typeof global&&global.HermesInternal;let s;function getTokenPayload(e){if(e)try{const t=decodeURIComponent(s(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let s=getTokenPayload(e);return!(Object.keys(s).length>0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,r=0,o="";i=t.charAt(r++);~i&&(s=n%4?64*s+i:i,n++%4)?o+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n4096){r.model={id:r?.model?.id,email:r?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(r.model[e]=this.model[e]);o=cookieSerialize(t,JSON.stringify(r),e)}return o}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,r){return r=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},r),this.client.send("/api/settings/apple/generate-client-secret",r)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const r=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let o=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return o=this.authResponse(o),r&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,r=e.authStore.model,o=e.authStore.onChange(((t,s)=>{(!t||s?.id!=r?.id||(s?.collectionId||r?.collectionId)&&s?.collectionId!=r?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){o(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(r,o)=>{const a=e.authStore.token;if(o.query?.autoRefresh)return n?n(r,o):{url:r,sendOptions:o};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=o.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return o.headers=l,n?n(r,o):{url:r,sendOptions:o}}}(this.client,r,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),o}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",r).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,r,o){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,r,o),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{};let s=null;t.urlCallback||(s=openBrowserPopup(void 0));const i=new RealtimeService(this.client);function cleanup(){s?.close(),i.unsubscribe()}const n={},r=t.requestKey;return r&&(n.requestKey=r),this.listAuthMethods(n).then((e=>{const n=e.authProviders.find((e=>e.name===t.provider));if(!n)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const o=this.client.buildUrl("/api/oauth2-redirect"),a=r?this.client.cancelControllers?.[r]:void 0;return a&&(a.signal.onabort=()=>{cleanup()}),new Promise((async(e,r)=>{try{await i.subscribe("@oauth2",(async s=>{const c=i.clientId;try{if(!s.state||c!==s.state)throw new Error("State parameters don't match.");if(s.error||!s.code)throw new Error("OAuth2 redirect error or missing code: "+s.error);const i=Object.assign({},t);delete i.provider,delete i.scopes,delete i.createData,delete i.urlCallback,a?.signal?.onabort&&(a.signal.onabort=null);const r=await this.authWithOAuth2Code(n.name,s.code,n.codeVerifier,o,t.createData,i);e(r)}catch(e){r(new ClientResponseError(e))}cleanup()}));const c={state:i.clientId};t.scopes?.length&&(c.scope=t.scopes.join(" "));const l=this._replaceQueryParams(n.authUrl+o,c);let h=t.urlCallback||function(e){s?s.location.href=e:s=openBrowserPopup(e)};await h(l)}catch(e){cleanup(),r(new ClientResponseError(e))}}))})).catch((e=>{throw cleanup(),e}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let r={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return r=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",r,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",r).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},r=i.split("&");for(const e of r){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let r=i/2-t/2,o=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+o+",left="+r+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}return class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}}(); //# sourceMappingURL=pocketbase.iife.js.map diff --git a/dist/pocketbase.iife.js.map b/dist/pocketbase.iife.js.map index f250112..c7d5ae7 100644 --- a/dist/pocketbase.iife.js.map +++ b/dist/pocketbase.iife.js.map @@ -1 +1 @@ -{"version":3,"file":"pocketbase.iife.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * _Site-note_: when creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n async authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n const authMethods = await this.listAuthMethods();\n\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before the async call due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieSerialize","val","options","opt","assign","encode","defaultEncode","test","TypeError","value","result","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","defaultDecode","indexOf","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","charCodeAt","slice","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","length","exp","now","atob","input","str","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","key","rawData","cookieParse","decode","index","eqIdx","endIdx","lastIndexOf","trim","undefined","_","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","find","eagerDefaultPopup","cleanup","urlCallback","openBrowserPopup","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","signal","FormData","hasBlobField","form","v","append","values","File","encodedKey"],"mappings":"uCAIM,MAAO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D,UAAU5F,KAEjEC,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBxB,GAEzD,CAED,OAAOC,EAAOsC,KAAK,IACtB"} \ No newline at end of file +{"version":3,"file":"pocketbase.iife.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * Note1: When creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * Note2: Safari may block the default `urlCallback` popup because\n * it doesn't allow `window.open` calls as part of an `async` click functions.\n * To workaround this you can either change your click handler to not be marked as `async`\n * OR manually call `window.open` before your `async` function and use the\n * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061).\n * For example:\n * ```js\n * \n * ...\n * document.getElementById(\"btn\").addEventListener(\"click\", () => {\n * pb.collection(\"users\").authWithOAuth2({\n * provider: \"gitlab\",\n * }).then((authData) => {\n * console.log(authData)\n * }).catch((err) => {\n * console.log(err, err.originalError);\n * });\n * })\n * ```\n *\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before any async calls due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n const requestKeyOptions: SendOptions = {};\n const requestKey = config.requestKey\n if (requestKey) {\n requestKeyOptions.requestKey = requestKey;\n }\n\n return this.listAuthMethods(requestKeyOptions).then((authMethods) => {\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // find the AbortController associated with the current request key (if any)\n const cancelController = requestKey ? this.client['cancelControllers']?.[requestKey] : undefined;\n if (cancelController) {\n cancelController.signal.onabort = () => {\n cleanup();\n }\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n // reset the cancelController listener as it will be triggered by the next api call\n if (cancelController?.signal?.onabort) {\n cancelController.signal.onabort = null\n }\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }).catch((err) => {\n cleanup();\n throw err // rethrow\n }) as Promise>;\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieSerialize","val","options","opt","assign","encode","defaultEncode","test","TypeError","value","result","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","defaultDecode","indexOf","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","charCodeAt","slice","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","length","exp","now","atob","input","str","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","key","rawData","cookieParse","decode","index","eqIdx","endIdx","lastIndexOf","trim","undefined","_","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","eagerDefaultPopup","urlCallback","openBrowserPopup","cleanup","requestKeyOptions","authMethods","find","cancelController","signal","onabort","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","FormData","hasBlobField","form","v","append","values","File","encodedKey"],"mappings":"uCAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UAAYN,EAAQM,QACzBJ,KAAKK,cAAgBP,EAAQO,cAEJ,OAArBP,EAAQK,UAAiD,iBAArBL,EAAQK,SAC5CH,KAAKG,SAAWL,EAAQK,SACA,OAAjBL,EAAQW,MAAyC,iBAAjBX,EAAQW,KAC/CT,KAAKG,SAAWL,EAAQW,KAExBT,KAAKG,SAAW,IAInBH,KAAKK,eAAmBP,aAAmBH,sBAC5CK,KAAKK,cAAgBP,GAGG,oBAAjBY,cAAgCZ,aAAmBY,eAC1DV,KAAKI,SAAU,GAGnBJ,KAAKW,KAAO,uBAAyBX,KAAKE,OAC1CF,KAAKY,QAAUZ,KAAKG,UAAUS,QACzBZ,KAAKY,UACFZ,KAAKI,QACLJ,KAAKY,QACD,mHACGZ,KAAKK,eAAeQ,OAAOD,SAASE,SAAS,oBACpDd,KAAKY,QACD,qJAEJZ,KAAKY,QAAU,sDAG1B,CAKD,QAAIH,GACA,OAAOT,KAAKG,QACf,CAMD,MAAAY,GACI,MAAO,IAAKf,KACf,ECvDL,MAAMgB,EAAqB,iDAqFXC,gBACZN,EACAO,EACAC,GAEA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AAA8T,CAAW1Q,GACf,OACIA,IAI2B,aAA1BA,EAAK9J,YAAYc,MAIO,oBAAb8Z,UAA4B9Q,aAAgB8Q,SAE/D,CAKO,oBAAAZ,CAAqB/G,GACzB,MAAMnR,EAAwB,GAC9B,IAAK,MAAM4E,KAAOuM,EAAQ,CACtB,GAAoB,OAAhBA,EAAOvM,GAEP,SAGJ,MAAM7E,EAAQoR,EAAOvM,GACfyU,EAAa9X,mBAAmBqD,GAEtC,GAAIW,MAAMC,QAAQzF,GAEd,IAAK,MAAMkZ,KAAKlZ,EACZC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmB0X,SAE/ClZ,aAAiBa,KACxBZ,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBxB,EAAM4X,gBAChC,cAAV5X,GAAmC,iBAAVA,EACvCC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBgB,KAAKoD,UAAU5F,KAEjEC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBxB,GAEzD,CAED,OAAOC,EAAOsC,KAAK,IACtB"} \ No newline at end of file diff --git a/dist/pocketbase.umd.d.ts b/dist/pocketbase.umd.d.ts index 2353cb1..5f07fd6 100644 --- a/dist/pocketbase.umd.d.ts +++ b/dist/pocketbase.umd.d.ts @@ -776,10 +776,31 @@ declare class RecordService extends CrudService { * }) * ``` * - * _Site-note_: when creating the OAuth2 app in the provider dashboard + * Note1: When creating the OAuth2 app in the provider dashboard * you have to configure `https://yourdomain.com/api/oauth2-redirect` * as redirect URL. * + * Note2: Safari may block the default `urlCallback` popup because + * it doesn't allow `window.open` calls as part of an `async` click functions. + * To workaround this you can either change your click handler to not be marked as `async` + * OR manually call `window.open` before your `async` function and use the + * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061). + * For example: + * ```js + * + * ... + * document.getElementById("btn").addEventListener("click", () => { + * pb.collection("users").authWithOAuth2({ + * provider: "gitlab", + * }).then((authData) => { + * console.log(authData) + * }).catch((err) => { + * console.log(err, err.originalError); + * }); + * }) + * ``` + * + * * @throws {ClientResponseError} */ authWithOAuth2(options: OAuth2AuthConfig): Promise>; diff --git a/dist/pocketbase.umd.js b/dist/pocketbase.umd.js index ed43317..297f253 100644 --- a/dist/pocketbase.umd.js +++ b/dist/pocketbase.umd.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PocketBase=t()}(this,(function(){"use strict";class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,s,i){const n=Object.assign({},i||{}),o=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const r=o(s);if(r&&!e.test(r))throw new TypeError("argument val is invalid");let a=t+"="+r;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}const t="undefined"!=typeof navigator&&"ReactNative"===navigator.product||"undefined"!=typeof global&&global.HermesInternal;let s;function getTokenPayload(e){if(e)try{const t=decodeURIComponent(s(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let s=getTokenPayload(e);return!(Object.keys(s).length>0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,o=0,r="";i=t.charAt(o++);~i&&(s=n%4?64*s+i:i,n++%4)?r+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return r}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n4096){o.model={id:o?.model?.id,email:o?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(o.model[e]=this.model[e]);r=cookieSerialize(t,JSON.stringify(o),e)}return r}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,o){return o=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},o),this.client.send("/api/settings/apple/generate-client-secret",o)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const o=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let r=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return r=this.authResponse(r),o&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,o=e.authStore.model,r=e.authStore.onChange(((t,s)=>{(!t||s?.id!=o?.id||(s?.collectionId||o?.collectionId)&&s?.collectionId!=o?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){r(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(o,r)=>{const a=e.authStore.token;if(r.query?.autoRefresh)return n?n(o,r):{url:o,sendOptions:r};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=r.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return r.headers=l,n?n(o,r):{url:o,sendOptions:r}}}(this.client,o,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),r}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",o,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",o).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,o,r){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,o,r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}async authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{},s=(await this.listAuthMethods()).authProviders.find((e=>e.name===t.provider));if(!s)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const i=this.client.buildUrl("/api/oauth2-redirect"),n=new RealtimeService(this.client);let o=null;function cleanup(){o?.close(),n.unsubscribe()}return t.urlCallback||(o=openBrowserPopup(void 0)),new Promise((async(e,r)=>{try{await n.subscribe("@oauth2",(async o=>{const a=n.clientId;try{if(!o.state||a!==o.state)throw new Error("State parameters don't match.");if(o.error||!o.code)throw new Error("OAuth2 redirect error or missing code: "+o.error);const n=Object.assign({},t);delete n.provider,delete n.scopes,delete n.createData,delete n.urlCallback;const r=await this.authWithOAuth2Code(s.name,o.code,s.codeVerifier,i,t.createData,n);e(r)}catch(e){r(new ClientResponseError(e))}cleanup()}));const a={state:n.clientId};t.scopes?.length&&(a.scope=t.scopes.join(" "));const c=this._replaceQueryParams(s.authUrl+i,a);let l=t.urlCallback||function(e){o?o.location.href=e:o=openBrowserPopup(e)};await l(c)}catch(e){cleanup(),r(new ClientResponseError(e))}}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",o,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",o).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},o=i.split("&");for(const e of o){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let o=i/2-t/2,r=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+r+",left="+o+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}return class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PocketBase=t()}(this,(function(){"use strict";class ClientResponseError extends Error{constructor(e){super("ClientResponseError"),this.url="",this.status=0,this.response={},this.isAbort=!1,this.originalError=null,Object.setPrototypeOf(this,ClientResponseError.prototype),null!==e&&"object"==typeof e&&(this.url="string"==typeof e.url?e.url:"",this.status="number"==typeof e.status?e.status:0,this.isAbort=!!e.isAbort,this.originalError=e.originalError,null!==e.response&&"object"==typeof e.response?this.response=e.response:null!==e.data&&"object"==typeof e.data?this.response=e.data:this.response={}),this.originalError||e instanceof ClientResponseError||(this.originalError=e),"undefined"!=typeof DOMException&&e instanceof DOMException&&(this.isAbort=!0),this.name="ClientResponseError "+this.status,this.message=this.response?.message,this.message||(this.isAbort?this.message="The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.":this.originalError?.cause?.message?.includes("ECONNREFUSED ::1")?this.message="Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).":this.message="Something went wrong while processing your request.")}get data(){return this.response}toJSON(){return{...this}}}const e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function cookieSerialize(t,s,i){const n=Object.assign({},i||{}),o=n.encode||defaultEncode;if(!e.test(t))throw new TypeError("argument name is invalid");const r=o(s);if(r&&!e.test(r))throw new TypeError("argument val is invalid");let a=t+"="+r;if(null!=n.maxAge){const e=n.maxAge-0;if(isNaN(e)||!isFinite(e))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(e)}if(n.domain){if(!e.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!e.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){if(!function isDate(e){return"[object Date]"===Object.prototype.toString.call(e)||e instanceof Date}(n.expires)||isNaN(n.expires.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority){switch("string"==typeof n.priority?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(n.sameSite){switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return a}function defaultDecode(e){return-1!==e.indexOf("%")?decodeURIComponent(e):e}function defaultEncode(e){return encodeURIComponent(e)}const t="undefined"!=typeof navigator&&"ReactNative"===navigator.product||"undefined"!=typeof global&&global.HermesInternal;let s;function getTokenPayload(e){if(e)try{const t=decodeURIComponent(s(e.split(".")[1]).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(t)||{}}catch(e){}return{}}function isTokenExpired(e,t=0){let s=getTokenPayload(e);return!(Object.keys(s).length>0&&(!s.exp||s.exp-t>Date.now()/1e3))}s="function"!=typeof atob||t?e=>{let t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,n=0,o=0,r="";i=t.charAt(o++);~i&&(s=n%4?64*s+i:i,n++%4)?r+=String.fromCharCode(255&s>>(-2*n&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return r}:atob;const i="pb_auth";class BaseAuthStore{constructor(){this.baseToken="",this.baseModel=null,this._onChangeCallbacks=[]}get token(){return this.baseToken}get model(){return this.baseModel}get isValid(){return!isTokenExpired(this.token)}get isAdmin(){return"admin"===getTokenPayload(this.token).type}get isAuthRecord(){return"authRecord"===getTokenPayload(this.token).type}save(e,t){this.baseToken=e||"",this.baseModel=t||null,this.triggerChange()}clear(){this.baseToken="",this.baseModel=null,this.triggerChange()}loadFromCookie(e,t=i){const s=function cookieParse(e,t){const s={};if("string"!=typeof e)return s;const i=Object.assign({},t||{}).decode||defaultDecode;let n=0;for(;n4096){o.model={id:o?.model?.id,email:o?.model?.email};const s=["collectionId","username","verified"];for(const e in this.model)s.includes(e)&&(o.model[e]=this.model[e]);r=cookieSerialize(t,JSON.stringify(o),e)}return r}onChange(e,t=!1){return this._onChangeCallbacks.push(e),t&&e(this.token,this.model),()=>{for(let t=this._onChangeCallbacks.length-1;t>=0;t--)if(this._onChangeCallbacks[t]==e)return delete this._onChangeCallbacks[t],void this._onChangeCallbacks.splice(t,1)}}triggerChange(){for(const e of this._onChangeCallbacks)e&&e(this.token,this.model)}}class LocalAuthStore extends BaseAuthStore{constructor(e="pocketbase_auth"){super(),this.storageFallback={},this.storageKey=e,this._bindStorageEvent()}get token(){return(this._storageGet(this.storageKey)||{}).token||""}get model(){return(this._storageGet(this.storageKey)||{}).model||null}save(e,t){this._storageSet(this.storageKey,{token:e,model:t}),super.save(e,t)}clear(){this._storageRemove(this.storageKey),super.clear()}_storageGet(e){if("undefined"!=typeof window&&window?.localStorage){const t=window.localStorage.getItem(e)||"";try{return JSON.parse(t)}catch(e){return t}}return this.storageFallback[e]}_storageSet(e,t){if("undefined"!=typeof window&&window?.localStorage){let s=t;"string"!=typeof t&&(s=JSON.stringify(t)),window.localStorage.setItem(e,s)}else this.storageFallback[e]=t}_storageRemove(e){"undefined"!=typeof window&&window?.localStorage&&window.localStorage?.removeItem(e),delete this.storageFallback[e]}_bindStorageEvent(){"undefined"!=typeof window&&window?.localStorage&&window.addEventListener&&window.addEventListener("storage",(e=>{if(e.key!=this.storageKey)return;const t=this._storageGet(this.storageKey)||{};super.save(t.token||"",t.model||null)}))}}class BaseService{constructor(e){this.client=e}}class SettingsService extends BaseService{async getAll(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/settings",e)}async update(e,t){return t=Object.assign({method:"PATCH",body:e},t),this.client.send("/api/settings",t)}async testS3(e="storage",t){return t=Object.assign({method:"POST",body:{filesystem:e}},t),this.client.send("/api/settings/test/s3",t).then((()=>!0))}async testEmail(e,t,s){return s=Object.assign({method:"POST",body:{email:e,template:t}},s),this.client.send("/api/settings/test/email",s).then((()=>!0))}async generateAppleClientSecret(e,t,s,i,n,o){return o=Object.assign({method:"POST",body:{clientId:e,teamId:t,keyId:s,privateKey:i,duration:n}},o),this.client.send("/api/settings/apple/generate-client-secret",o)}}class CrudService extends BaseService{decode(e){return e}async getFullList(e,t){if("number"==typeof e)return this._getFullList(e,t);let s=500;return(t=Object.assign({},e,t)).batch&&(s=t.batch,delete t.batch),this._getFullList(s,t)}async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send(this.baseCrudPath,s).then((e=>(e.items=e.items?.map((e=>this.decode(e)))||[],e)))}async getFirstListItem(e,t){return(t=Object.assign({requestKey:"one_by_filter_"+this.baseCrudPath+"_"+e},t)).query=Object.assign({filter:e,skipTotal:1},t.query),this.getList(1,1,t).then((e=>{if(!e?.items?.length)throw new ClientResponseError({status:404,response:{code:404,message:"The requested resource wasn't found.",data:{}}});return e.items[0]}))}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl(this.baseCrudPath+"/"),status:404,response:{code:404,message:"Missing required record id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((e=>this.decode(e)))}async create(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send(this.baseCrudPath,t).then((e=>this.decode(e)))}async update(e,t,s){return s=Object.assign({method:"PATCH",body:t},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),s).then((e=>this.decode(e)))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e),t).then((()=>!0))}_getFullList(e=500,t){(t=t||{}).query=Object.assign({skipTotal:1},t.query);let s=[],request=async i=>this.getList(i,e||500,t).then((e=>{const t=e.items;return s=s.concat(t),t.length==e.perPage?request(i+1):s}));return request(1)}}function normalizeLegacyOptionsArgs(e,t,s,i){const n=void 0!==i;return n||void 0!==s?n?(console.warn(e),t.body=Object.assign({},t.body,s),t.query=Object.assign({},t.query,i),t):Object.assign(t,s):t}function resetAutoRefresh(e){e._resetAutoRefresh?.()}class AdminService extends CrudService{get baseCrudPath(){return"/api/admins"}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id===e.id&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(t&&this.client.authStore.model?.id===e&&void 0===this.client.authStore.model?.collectionId&&this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.admin||{});return e?.token&&e?.admin&&this.client.authStore.save(e.token,t),Object.assign({},e,{token:e?.token||"",admin:t})}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};n=normalizeLegacyOptionsArgs("This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).",n,s,i);const o=n.autoRefreshThreshold;delete n.autoRefreshThreshold,n.autoRefresh||resetAutoRefresh(this.client);let r=await this.client.send(this.baseCrudPath+"/auth-with-password",n);return r=this.authResponse(r),o&&function registerAutoRefresh(e,t,s,i){resetAutoRefresh(e);const n=e.beforeSend,o=e.authStore.model,r=e.authStore.onChange(((t,s)=>{(!t||s?.id!=o?.id||(s?.collectionId||o?.collectionId)&&s?.collectionId!=o?.collectionId)&&resetAutoRefresh(e)}));e._resetAutoRefresh=function(){r(),e.beforeSend=n,delete e._resetAutoRefresh},e.beforeSend=async(o,r)=>{const a=e.authStore.token;if(r.query?.autoRefresh)return n?n(o,r):{url:o,sendOptions:r};let c=e.authStore.isValid;if(c&&isTokenExpired(e.authStore.token,t))try{await s()}catch(e){c=!1}c||await i();const l=r.headers||{};for(let t in l)if("authorization"==t.toLowerCase()&&a==l[t]&&e.authStore.token){l[t]=e.authStore.token;break}return r.headers=l,n?n(o,r):{url:o,sendOptions:r}}}(this.client,o,(()=>this.authRefresh({autoRefresh:!0})),(()=>this.authWithPassword(e,t,Object.assign({autoRefresh:!0},n)))),r}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCrudPath+"/auth-refresh",s).then(this.authResponse.bind(this))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCrudPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).",o,i,n),this.client.send(this.baseCrudPath+"/confirm-password-reset",o).then((()=>!0))}}const n=["requestKey","$cancelKey","$autoCancel","fetch","headers","body","query","params","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window"];function normalizeUnknownQueryParams(e){if(e){e.query=e.query||{};for(let t in e)n.includes(t)||(e.query[t]=e[t],delete e[t])}}class RealtimeService extends BaseService{constructor(){super(...arguments),this.clientId="",this.eventSource=null,this.subscriptions={},this.lastSentSubscriptions=[],this.maxConnectTimeout=15e3,this.reconnectAttempts=0,this.maxReconnectAttempts=1/0,this.predefinedReconnectIntervals=[200,300,500,1e3,1200,1500,2e3],this.pendingConnects=[]}get isConnected(){return!!this.eventSource&&!!this.clientId&&!this.pendingConnects.length}async subscribe(e,t,s){if(!e)throw new Error("topic must be set.");let i=e;if(s){normalizeUnknownQueryParams(s);const e="options="+encodeURIComponent(JSON.stringify({query:s.query,headers:s.headers}));i+=(i.includes("?")?"&":"?")+e}const listener=function(e){const s=e;let i;try{i=JSON.parse(s?.data)}catch{}t(i||{})};return this.subscriptions[i]||(this.subscriptions[i]=[]),this.subscriptions[i].push(listener),this.isConnected?1===this.subscriptions[i].length?await this.submitSubscriptions():this.eventSource?.addEventListener(i,listener):await this.connect(),async()=>this.unsubscribeByTopicAndListener(e,listener)}async unsubscribe(e){let t=!1;if(e){const s=this.getSubscriptionsByTopic(e);for(let e in s)if(this.hasSubscriptionListeners(e)){for(let t of this.subscriptions[e])this.eventSource?.removeEventListener(e,t);delete this.subscriptions[e],t||(t=!0)}}else this.subscriptions={};this.hasSubscriptionListeners()?t&&await this.submitSubscriptions():this.disconnect()}async unsubscribeByPrefix(e){let t=!1;for(let s in this.subscriptions)if((s+"?").startsWith(e)){t=!0;for(let e of this.subscriptions[s])this.eventSource?.removeEventListener(s,e);delete this.subscriptions[s]}t&&(this.hasSubscriptionListeners()?await this.submitSubscriptions():this.disconnect())}async unsubscribeByTopicAndListener(e,t){let s=!1;const i=this.getSubscriptionsByTopic(e);for(let e in i){if(!Array.isArray(this.subscriptions[e])||!this.subscriptions[e].length)continue;let i=!1;for(let s=this.subscriptions[e].length-1;s>=0;s--)this.subscriptions[e][s]===t&&(i=!0,delete this.subscriptions[e][s],this.subscriptions[e].splice(s,1),this.eventSource?.removeEventListener(e,t));i&&(this.subscriptions[e].length||delete this.subscriptions[e],s||this.hasSubscriptionListeners(e)||(s=!0))}this.hasSubscriptionListeners()?s&&await this.submitSubscriptions():this.disconnect()}hasSubscriptionListeners(e){if(this.subscriptions=this.subscriptions||{},e)return!!this.subscriptions[e]?.length;for(let e in this.subscriptions)if(this.subscriptions[e]?.length)return!0;return!1}async submitSubscriptions(){if(this.clientId)return this.addAllSubscriptionListeners(),this.lastSentSubscriptions=this.getNonEmptySubscriptionKeys(),this.client.send("/api/realtime",{method:"POST",body:{clientId:this.clientId,subscriptions:this.lastSentSubscriptions},requestKey:this.getSubscriptionsCancelKey()}).catch((e=>{if(!e?.isAbort)throw e}))}getSubscriptionsCancelKey(){return"realtime_"+this.clientId}getSubscriptionsByTopic(e){const t={};e=e.includes("?")?e:e+"?";for(let s in this.subscriptions)(s+"?").startsWith(e)&&(t[s]=this.subscriptions[s]);return t}getNonEmptySubscriptionKeys(){const e=[];for(let t in this.subscriptions)this.subscriptions[t].length&&e.push(t);return e}addAllSubscriptionListeners(){if(this.eventSource){this.removeAllSubscriptionListeners();for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.addEventListener(e,t)}}removeAllSubscriptionListeners(){if(this.eventSource)for(let e in this.subscriptions)for(let t of this.subscriptions[e])this.eventSource.removeEventListener(e,t)}async connect(){if(!(this.reconnectAttempts>0))return new Promise(((e,t)=>{this.pendingConnects.push({resolve:e,reject:t}),this.pendingConnects.length>1||this.initConnect()}))}initConnect(){this.disconnect(!0),clearTimeout(this.connectTimeoutId),this.connectTimeoutId=setTimeout((()=>{this.connectErrorHandler(new Error("EventSource connect took too long."))}),this.maxConnectTimeout),this.eventSource=new EventSource(this.client.buildUrl("/api/realtime")),this.eventSource.onerror=e=>{this.connectErrorHandler(new Error("Failed to establish realtime connection."))},this.eventSource.addEventListener("PB_CONNECT",(e=>{const t=e;this.clientId=t?.lastEventId,this.submitSubscriptions().then((async()=>{let e=3;for(;this.hasUnsentSubscriptions()&&e>0;)e--,await this.submitSubscriptions()})).then((()=>{for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[],this.reconnectAttempts=0,clearTimeout(this.reconnectTimeoutId),clearTimeout(this.connectTimeoutId);const t=this.getSubscriptionsByTopic("PB_CONNECT");for(let s in t)for(let i of t[s])i(e)})).catch((e=>{this.clientId="",this.connectErrorHandler(e)}))}))}hasUnsentSubscriptions(){const e=this.getNonEmptySubscriptionKeys();if(e.length!=this.lastSentSubscriptions.length)return!0;for(const t of e)if(!this.lastSentSubscriptions.includes(t))return!0;return!1}connectErrorHandler(e){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),!this.clientId&&!this.reconnectAttempts||this.reconnectAttempts>this.maxReconnectAttempts){for(let t of this.pendingConnects)t.reject(new ClientResponseError(e));return this.pendingConnects=[],void this.disconnect()}this.disconnect(!0);const t=this.predefinedReconnectIntervals[this.reconnectAttempts]||this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length-1];this.reconnectAttempts++,this.reconnectTimeoutId=setTimeout((()=>{this.initConnect()}),t)}disconnect(e=!1){if(clearTimeout(this.connectTimeoutId),clearTimeout(this.reconnectTimeoutId),this.removeAllSubscriptionListeners(),this.client.cancelRequest(this.getSubscriptionsCancelKey()),this.eventSource?.close(),this.eventSource=null,this.clientId="",!e){this.reconnectAttempts=0;for(let e of this.pendingConnects)e.resolve();this.pendingConnects=[]}}}class RecordService extends CrudService{constructor(e,t){super(e),this.collectionIdOrName=t}get baseCrudPath(){return this.baseCollectionPath+"/records"}get baseCollectionPath(){return"/api/collections/"+encodeURIComponent(this.collectionIdOrName)}async subscribe(e,t,s){if(!e)throw new Error("Missing topic.");if(!t)throw new Error("Missing subscription callback.");return this.client.realtime.subscribe(this.collectionIdOrName+"/"+e,t,s)}async unsubscribe(e){return e?this.client.realtime.unsubscribe(this.collectionIdOrName+"/"+e):this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName)}async getFullList(e,t){if("number"==typeof e)return super.getFullList(e,t);const s=Object.assign({},e,t);return super.getFullList(s)}async getList(e=1,t=30,s){return super.getList(e,t,s)}async getFirstListItem(e,t){return super.getFirstListItem(e,t)}async getOne(e,t){return super.getOne(e,t)}async create(e,t){return super.create(e,t)}async update(e,t,s){return super.update(e,t,s).then((e=>(this.client.authStore.model?.id!==e?.id||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.save(this.client.authStore.token,e),e)))}async delete(e,t){return super.delete(e,t).then((t=>(!t||this.client.authStore.model?.id!==e||this.client.authStore.model?.collectionId!==this.collectionIdOrName&&this.client.authStore.model?.collectionName!==this.collectionIdOrName||this.client.authStore.clear(),t)))}authResponse(e){const t=this.decode(e?.record||{});return this.client.authStore.save(e?.token,t),Object.assign({},e,{token:e?.token||"",record:t})}async listAuthMethods(e){return e=Object.assign({method:"GET"},e),this.client.send(this.baseCollectionPath+"/auth-methods",e).then((e=>Object.assign({},e,{usernamePassword:!!e?.usernamePassword,emailPassword:!!e?.emailPassword,authProviders:Array.isArray(e?.authProviders)?e?.authProviders:[]})))}async authWithPassword(e,t,s,i){let n={method:"POST",body:{identity:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/auth-with-password",n).then((e=>this.authResponse(e)))}async authWithOAuth2Code(e,t,s,i,n,o,r){let a={method:"POST",body:{provider:e,code:t,codeVerifier:s,redirectUrl:i,createData:n}};return a=normalizeLegacyOptionsArgs("This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).",a,o,r),this.client.send(this.baseCollectionPath+"/auth-with-oauth2",a).then((e=>this.authResponse(e)))}authWithOAuth2(...e){if(e.length>1||"string"==typeof e?.[0])return console.warn("PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration."),this.authWithOAuth2Code(e?.[0]||"",e?.[1]||"",e?.[2]||"",e?.[3]||"",e?.[4]||{},e?.[5]||{},e?.[6]||{});const t=e?.[0]||{};let s=null;t.urlCallback||(s=openBrowserPopup(void 0));const i=new RealtimeService(this.client);function cleanup(){s?.close(),i.unsubscribe()}const n={},o=t.requestKey;return o&&(n.requestKey=o),this.listAuthMethods(n).then((e=>{const n=e.authProviders.find((e=>e.name===t.provider));if(!n)throw new ClientResponseError(new Error(`Missing or invalid provider "${t.provider}".`));const r=this.client.buildUrl("/api/oauth2-redirect"),a=o?this.client.cancelControllers?.[o]:void 0;return a&&(a.signal.onabort=()=>{cleanup()}),new Promise((async(e,o)=>{try{await i.subscribe("@oauth2",(async s=>{const c=i.clientId;try{if(!s.state||c!==s.state)throw new Error("State parameters don't match.");if(s.error||!s.code)throw new Error("OAuth2 redirect error or missing code: "+s.error);const i=Object.assign({},t);delete i.provider,delete i.scopes,delete i.createData,delete i.urlCallback,a?.signal?.onabort&&(a.signal.onabort=null);const o=await this.authWithOAuth2Code(n.name,s.code,n.codeVerifier,r,t.createData,i);e(o)}catch(e){o(new ClientResponseError(e))}cleanup()}));const c={state:i.clientId};t.scopes?.length&&(c.scope=t.scopes.join(" "));const l=this._replaceQueryParams(n.authUrl+r,c);let h=t.urlCallback||function(e){s?s.location.href=e:s=openBrowserPopup(e)};await h(l)}catch(e){cleanup(),o(new ClientResponseError(e))}}))})).catch((e=>{throw cleanup(),e}))}async authRefresh(e,t){let s={method:"POST"};return s=normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).",s,e,t),this.client.send(this.baseCollectionPath+"/auth-refresh",s).then((e=>this.authResponse(e)))}async requestPasswordReset(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-password-reset",i).then((()=>!0))}async confirmPasswordReset(e,t,s,i,n){let o={method:"POST",body:{token:e,password:t,passwordConfirm:s}};return o=normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).",o,i,n),this.client.send(this.baseCollectionPath+"/confirm-password-reset",o).then((()=>!0))}async requestVerification(e,t,s){let i={method:"POST",body:{email:e}};return i=normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-verification",i).then((()=>!0))}async confirmVerification(e,t,s){let i={method:"POST",body:{token:e}};return i=normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/confirm-verification",i).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&!s.verified&&s.id===t.id&&s.collectionId===t.collectionId&&(s.verified=!0,this.client.authStore.save(this.client.authStore.token,s)),!0}))}async requestEmailChange(e,t,s){let i={method:"POST",body:{newEmail:e}};return i=normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).",i,t,s),this.client.send(this.baseCollectionPath+"/request-email-change",i).then((()=>!0))}async confirmEmailChange(e,t,s,i){let n={method:"POST",body:{token:e,password:t}};return n=normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).",n,s,i),this.client.send(this.baseCollectionPath+"/confirm-email-change",n).then((()=>{const t=getTokenPayload(e),s=this.client.authStore.model;return s&&s.id===t.id&&s.collectionId===t.collectionId&&this.client.authStore.clear(),!0}))}async listExternalAuths(e,t){return t=Object.assign({method:"GET"},t),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths",t)}async unlinkExternalAuth(e,t,s){return s=Object.assign({method:"DELETE"},s),this.client.send(this.baseCrudPath+"/"+encodeURIComponent(e)+"/external-auths/"+encodeURIComponent(t),s).then((()=>!0))}_replaceQueryParams(e,t={}){let s=e,i="";e.indexOf("?")>=0&&(s=e.substring(0,e.indexOf("?")),i=e.substring(e.indexOf("?")+1));const n={},o=i.split("&");for(const e of o){if(""==e)continue;const t=e.split("=");n[decodeURIComponent(t[0].replace(/\+/g," "))]=decodeURIComponent((t[1]||"").replace(/\+/g," "))}for(let e in t)t.hasOwnProperty(e)&&(null==t[e]?delete n[e]:n[e]=t[e]);i="";for(let e in n)n.hasOwnProperty(e)&&(""!=i&&(i+="&"),i+=encodeURIComponent(e.replace(/%20/g,"+"))+"="+encodeURIComponent(n[e].replace(/%20/g,"+")));return""!=i?s+"?"+i:s}}function openBrowserPopup(e){if("undefined"==typeof window||!window?.open)throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));let t=1024,s=768,i=window.innerWidth,n=window.innerHeight;t=t>i?i:t,s=s>n?n:s;let o=i/2-t/2,r=n/2-s/2;return window.open(e,"popup_window","width="+t+",height="+s+",top="+r+",left="+o+",resizable,menubar=no")}class CollectionService extends CrudService{get baseCrudPath(){return"/api/collections"}async import(e,t=!1,s){return s=Object.assign({method:"PUT",body:{collections:e,deleteMissing:t}},s),this.client.send(this.baseCrudPath+"/import",s).then((()=>!0))}}class LogService extends BaseService{async getList(e=1,t=30,s){return(s=Object.assign({method:"GET"},s)).query=Object.assign({page:e,perPage:t},s.query),this.client.send("/api/logs",s)}async getOne(e,t){if(!e)throw new ClientResponseError({url:this.client.buildUrl("/api/logs/"),status:404,response:{code:404,message:"Missing required log id.",data:{}}});return t=Object.assign({method:"GET"},t),this.client.send("/api/logs/"+encodeURIComponent(e),t)}async getStats(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/logs/stats",e)}}class HealthService extends BaseService{async check(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/health",e)}}class FileService extends BaseService{getUrl(e,t,s={}){if(!t||!e?.id||!e?.collectionId&&!e?.collectionName)return"";const i=[];i.push("api"),i.push("files"),i.push(encodeURIComponent(e.collectionId||e.collectionName)),i.push(encodeURIComponent(e.id)),i.push(encodeURIComponent(t));let n=this.client.buildUrl(i.join("/"));if(Object.keys(s).length){!1===s.download&&delete s.download;const e=new URLSearchParams(s);n+=(n.includes("?")?"&":"?")+e}return n}async getToken(e){return e=Object.assign({method:"POST"},e),this.client.send("/api/files/token",e).then((e=>e?.token||""))}}class BackupService extends BaseService{async getFullList(e){return e=Object.assign({method:"GET"},e),this.client.send("/api/backups",e)}async create(e,t){return t=Object.assign({method:"POST",body:{name:e}},t),this.client.send("/api/backups",t).then((()=>!0))}async upload(e,t){return t=Object.assign({method:"POST",body:e},t),this.client.send("/api/backups/upload",t).then((()=>!0))}async delete(e,t){return t=Object.assign({method:"DELETE"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}`,t).then((()=>!0))}async restore(e,t){return t=Object.assign({method:"POST"},t),this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`,t).then((()=>!0))}getDownloadUrl(e,t){return this.client.buildUrl(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`)}}return class Client{constructor(e="/",t,s="en-US"){this.cancelControllers={},this.recordServices={},this.enableAutoCancellation=!0,this.baseUrl=e,this.lang=s,this.authStore=t||new LocalAuthStore,this.admins=new AdminService(this),this.collections=new CollectionService(this),this.files=new FileService(this),this.logs=new LogService(this),this.settings=new SettingsService(this),this.realtime=new RealtimeService(this),this.health=new HealthService(this),this.backups=new BackupService(this)}collection(e){return this.recordServices[e]||(this.recordServices[e]=new RecordService(this,e)),this.recordServices[e]}autoCancellation(e){return this.enableAutoCancellation=!!e,this}cancelRequest(e){return this.cancelControllers[e]&&(this.cancelControllers[e].abort(),delete this.cancelControllers[e]),this}cancelAllRequests(){for(let e in this.cancelControllers)this.cancelControllers[e].abort();return this.cancelControllers={},this}filter(e,t){if(!t)return e;for(let s in t){let i=t[s];switch(typeof i){case"boolean":case"number":i=""+i;break;case"string":i="'"+i.replace(/'/g,"\\'")+"'";break;default:i=null===i?"null":i instanceof Date?"'"+i.toISOString().replace("T"," ")+"'":"'"+JSON.stringify(i).replace(/'/g,"\\'")+"'"}e=e.replaceAll("{:"+s+"}",i)}return e}getFileUrl(e,t,s={}){return this.files.getUrl(e,t,s)}buildUrl(e){let t=this.baseUrl;return"undefined"==typeof window||!window.location||t.startsWith("https://")||t.startsWith("http://")||(t=window.location.origin?.endsWith("/")?window.location.origin.substring(0,window.location.origin.length-1):window.location.origin||"",this.baseUrl.startsWith("/")||(t+=window.location.pathname||"/",t+=t.endsWith("/")?"":"/"),t+=this.baseUrl),e&&(t+=t.endsWith("/")?"":"/",t+=e.startsWith("/")?e.substring(1):e),t}async send(e,t){t=this.initSendOptions(e,t);let s=this.buildUrl(e);if(this.beforeSend){const e=Object.assign({},await this.beforeSend(s,t));void 0!==e.url||void 0!==e.options?(s=e.url||s,t=e.options||t):Object.keys(e).length&&(t=e,console?.warn&&console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."))}if(void 0!==t.query){const e=this.serializeQueryParams(t.query);e&&(s+=(s.includes("?")?"&":"?")+e),delete t.query}"application/json"==this.getHeader(t.headers,"Content-Type")&&t.body&&"string"!=typeof t.body&&(t.body=JSON.stringify(t.body));return(t.fetch||fetch)(s,t).then((async e=>{let t={};try{t=await e.json()}catch(e){}if(this.afterSend&&(t=await this.afterSend(e,t)),e.status>=400)throw new ClientResponseError({url:e.url,status:e.status,data:t});return t})).catch((e=>{throw new ClientResponseError(e)}))}initSendOptions(e,t){if((t=Object.assign({method:"GET"},t)).body=this.convertToFormDataIfNeeded(t.body),normalizeUnknownQueryParams(t),t.query=Object.assign({},t.params,t.query),void 0===t.requestKey&&(!1===t.$autoCancel||!1===t.query.$autoCancel?t.requestKey=null:(t.$cancelKey||t.query.$cancelKey)&&(t.requestKey=t.$cancelKey||t.query.$cancelKey)),delete t.$autoCancel,delete t.query.$autoCancel,delete t.$cancelKey,delete t.query.$cancelKey,null!==this.getHeader(t.headers,"Content-Type")||this.isFormData(t.body)||(t.headers=Object.assign({},t.headers,{"Content-Type":"application/json"})),null===this.getHeader(t.headers,"Accept-Language")&&(t.headers=Object.assign({},t.headers,{"Accept-Language":this.lang})),this.authStore.token&&null===this.getHeader(t.headers,"Authorization")&&(t.headers=Object.assign({},t.headers,{Authorization:this.authStore.token})),this.enableAutoCancellation&&null!==t.requestKey){const s=t.requestKey||(t.method||"GET")+e;delete t.requestKey,this.cancelRequest(s);const i=new AbortController;this.cancelControllers[s]=i,t.signal=i.signal}return t}convertToFormDataIfNeeded(e){if("undefined"==typeof FormData||void 0===e||"object"!=typeof e||null===e||this.isFormData(e)||!this.hasBlobField(e))return e;const t=new FormData;for(const s in e){const i=e[s];if("object"!=typeof i||this.hasBlobField({data:i})){const e=Array.isArray(i)?i:[i];for(let i of e)t.append(s,i)}else{let e={};e[s]=i,t.append("@jsonPayload",JSON.stringify(e))}}return t}hasBlobField(e){for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];for(const e of s)if("undefined"!=typeof Blob&&e instanceof Blob||"undefined"!=typeof File&&e instanceof File)return!0}return!1}getHeader(e,t){e=e||{},t=t.toLowerCase();for(let s in e)if(s.toLowerCase()==t)return e[s];return null}isFormData(e){return e&&("FormData"===e.constructor.name||"undefined"!=typeof FormData&&e instanceof FormData)}serializeQueryParams(e){const t=[];for(const s in e){if(null===e[s])continue;const i=e[s],n=encodeURIComponent(s);if(Array.isArray(i))for(const e of i)t.push(n+"="+encodeURIComponent(e));else i instanceof Date?t.push(n+"="+encodeURIComponent(i.toISOString())):null!==typeof i&&"object"==typeof i?t.push(n+"="+encodeURIComponent(JSON.stringify(i))):t.push(n+"="+encodeURIComponent(i))}return t.join("&")}}})); //# sourceMappingURL=pocketbase.umd.js.map diff --git a/dist/pocketbase.umd.js.map b/dist/pocketbase.umd.js.map index 9e15a78..71c219b 100644 --- a/dist/pocketbase.umd.js.map +++ b/dist/pocketbase.umd.js.map @@ -1 +1 @@ -{"version":3,"file":"pocketbase.umd.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * _Site-note_: when creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n async authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n const authMethods = await this.listAuthMethods();\n\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before the async call due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieSerialize","val","options","opt","assign","encode","defaultEncode","test","TypeError","value","result","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","defaultDecode","indexOf","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","charCodeAt","slice","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","length","exp","now","atob","input","str","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","key","rawData","cookieParse","decode","index","eqIdx","endIdx","lastIndexOf","trim","undefined","_","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","find","eagerDefaultPopup","cleanup","urlCallback","openBrowserPopup","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","signal","FormData","hasBlobField","form","v","append","values","File","encodedKey"],"mappings":"2OAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UAAYN,EAAQM,QACzBJ,KAAKK,cAAgBP,EAAQO,cAEJ,OAArBP,EAAQK,UAAiD,iBAArBL,EAAQK,SAC5CH,KAAKG,SAAWL,EAAQK,SACA,OAAjBL,EAAQW,MAAyC,iBAAjBX,EAAQW,KAC/CT,KAAKG,SAAWL,EAAQW,KAExBT,KAAKG,SAAW,IAInBH,KAAKK,eAAmBP,aAAmBH,sBAC5CK,KAAKK,cAAgBP,GAGG,oBAAjBY,cAAgCZ,aAAmBY,eAC1DV,KAAKI,SAAU,GAGnBJ,KAAKW,KAAO,uBAAyBX,KAAKE,OAC1CF,KAAKY,QAAUZ,KAAKG,UAAUS,QACzBZ,KAAKY,UACFZ,KAAKI,QACLJ,KAAKY,QACD,mHACGZ,KAAKK,eAAeQ,OAAOD,SAASE,SAAS,oBACpDd,KAAKY,QACD,qJAEJZ,KAAKY,QAAU,sDAG1B,CAKD,QAAIH,GACA,OAAOT,KAAKG,QACf,CAMD,MAAAY,GACI,MAAO,IAAKf,KACf,ECvDL,MAAMgB,EAAqB,iDAqFXC,gBACZN,EACAO,EACAC,GAEA,MAAMC,EAAMd,OAAOe,OAAO,CAAA,EAAIF,GAAW,CAAA,GACnCG,EAASF,EAAIE,QAAUC,cAE7B,I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AAmBxB,EAAMuX,gBAChC,cAAVvX,GAAmC,iBAAVA,EACvCC,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBgB,KAAKoD,UAAU5F,KAEjEC,EAAOsG,KAAK2S,EAAa,IAAM1X,mBAAmBxB,GAEzD,CAED,OAAOC,EAAOsC,KAAK,IACtB"} \ No newline at end of file +{"version":3,"file":"pocketbase.umd.js","sources":["../src/ClientResponseError.ts","../src/stores/utils/cookie.ts","../src/stores/utils/jwt.ts","../src/stores/BaseAuthStore.ts","../src/stores/LocalAuthStore.ts","../src/services/utils/BaseService.ts","../src/services/SettingsService.ts","../src/services/utils/CrudService.ts","../src/services/utils/legacy.ts","../src/services/utils/refresh.ts","../src/services/AdminService.ts","../src/services/utils/options.ts","../src/services/RealtimeService.ts","../src/services/RecordService.ts","../src/services/CollectionService.ts","../src/services/LogService.ts","../src/services/HealthService.ts","../src/services/FileService.ts","../src/services/BackupService.ts","../src/Client.ts"],"sourcesContent":["/**\n * ClientResponseError is a custom Error class that is intended to wrap\n * and normalize any error thrown by `Client.send()`.\n */\nexport class ClientResponseError extends Error {\n url: string = \"\";\n status: number = 0;\n response: { [key: string]: any } = {};\n isAbort: boolean = false;\n originalError: any = null;\n\n constructor(errData?: any) {\n super(\"ClientResponseError\");\n\n // Set the prototype explicitly.\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ClientResponseError.prototype);\n\n if (errData !== null && typeof errData === \"object\") {\n this.url = typeof errData.url === \"string\" ? errData.url : \"\";\n this.status = typeof errData.status === \"number\" ? errData.status : 0;\n this.isAbort = !!errData.isAbort;\n this.originalError = errData.originalError;\n\n if (errData.response !== null && typeof errData.response === \"object\") {\n this.response = errData.response;\n } else if (errData.data !== null && typeof errData.data === \"object\") {\n this.response = errData.data;\n } else {\n this.response = {};\n }\n }\n\n if (!this.originalError && !(errData instanceof ClientResponseError)) {\n this.originalError = errData;\n }\n\n if (typeof DOMException !== \"undefined\" && errData instanceof DOMException) {\n this.isAbort = true;\n }\n\n this.name = \"ClientResponseError \" + this.status;\n this.message = this.response?.message;\n if (!this.message) {\n if (this.isAbort) {\n this.message =\n \"The request was autocancelled. You can find more info in https://github.com/pocketbase/js-sdk#auto-cancellation.\";\n } else if (this.originalError?.cause?.message?.includes(\"ECONNREFUSED ::1\")) {\n this.message =\n \"Failed to connect to the PocketBase server. Try changing the SDK URL from localhost to 127.0.0.1 (https://github.com/pocketbase/js-sdk/issues/21).\";\n } else {\n this.message = \"Something went wrong while processing your request.\";\n }\n }\n }\n\n /**\n * Alias for `this.response` to preserve the backward compatibility.\n */\n get data() {\n return this.response;\n }\n\n /**\n * Make a POJO's copy of the current error class instance.\n * @see https://github.com/vuex-orm/vuex-orm/issues/255\n */\n toJSON() {\n return { ...this };\n }\n}\n","/**\n * -------------------------------------------------------------------\n * Simple cookie parse and serialize utilities mostly based on the\n * node module https://github.com/jshttp/cookie.\n * -------------------------------------------------------------------\n */\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\nexport interface ParseOptions {\n decode?: (val: string) => string;\n}\n\n/**\n * Parses the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function cookieParse(str: string, options?: ParseOptions): { [key: string]: any } {\n const result: { [key: string]: any } = {};\n\n if (typeof str !== \"string\") {\n return result;\n }\n\n const opt = Object.assign({}, options || {});\n const decode = opt.decode || defaultDecode;\n\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(\";\", index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === result[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n result[key] = decode(val);\n } catch (_) {\n result[key] = val; // no decoding\n }\n }\n\n index = endIdx + 1;\n }\n\n return result;\n}\n\nexport interface SerializeOptions {\n encode?: (val: string | number | boolean) => string;\n maxAge?: number;\n domain?: string;\n path?: string;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n priority?: string;\n sameSite?: boolean | string;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * ```js\n * cookieSerialize('foo', 'bar', { httpOnly: true }) // \"foo=bar; httpOnly\"\n * ```\n */\nexport function cookieSerialize(\n name: string,\n val: string,\n options?: SerializeOptions,\n): string {\n const opt = Object.assign({}, options || {});\n const encode = opt.encode || defaultEncode;\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError(\"argument name is invalid\");\n }\n\n const value = encode(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError(\"argument val is invalid\");\n }\n\n let result = name + \"=\" + value;\n\n if (opt.maxAge != null) {\n const maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError(\"option maxAge is invalid\");\n }\n\n result += \"; Max-Age=\" + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError(\"option domain is invalid\");\n }\n\n result += \"; Domain=\" + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError(\"option path is invalid\");\n }\n\n result += \"; Path=\" + opt.path;\n }\n\n if (opt.expires) {\n if (!isDate(opt.expires) || isNaN(opt.expires.valueOf())) {\n throw new TypeError(\"option expires is invalid\");\n }\n\n result += \"; Expires=\" + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n result += \"; HttpOnly\";\n }\n\n if (opt.secure) {\n result += \"; Secure\";\n }\n\n if (opt.priority) {\n const priority =\n typeof opt.priority === \"string\" ? opt.priority.toLowerCase() : opt.priority;\n\n switch (priority) {\n case \"low\":\n result += \"; Priority=Low\";\n break;\n case \"medium\":\n result += \"; Priority=Medium\";\n break;\n case \"high\":\n result += \"; Priority=High\";\n break;\n default:\n throw new TypeError(\"option priority is invalid\");\n }\n }\n\n if (opt.sameSite) {\n const sameSite =\n typeof opt.sameSite === \"string\" ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n result += \"; SameSite=Strict\";\n break;\n case \"lax\":\n result += \"; SameSite=Lax\";\n break;\n case \"strict\":\n result += \"; SameSite=Strict\";\n break;\n case \"none\":\n result += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(\"option sameSite is invalid\");\n }\n }\n\n return result;\n}\n\n/**\n * Default URL-decode string value function.\n * Optimized to skip native call when no `%`.\n */\nfunction defaultDecode(val: string): string {\n return val.indexOf(\"%\") !== -1 ? decodeURIComponent(val) : val;\n}\n\n/**\n * Default URL-encode value function.\n */\nfunction defaultEncode(val: string | number | boolean): string {\n return encodeURIComponent(val);\n}\n\n/**\n * Determines if value is a Date.\n */\nfunction isDate(val: any): boolean {\n return Object.prototype.toString.call(val) === \"[object Date]\" || val instanceof Date;\n}\n","// @todo remove after https://github.com/reactwg/react-native-releases/issues/287\nconst isReactNative = (\n (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ||\n (typeof global !== 'undefined' && (global as any).HermesInternal)\n);\n\nlet atobPolyfill: Function;\nif (typeof atob === \"function\" && !isReactNative) {\n atobPolyfill = atob;\n} else {\n /**\n * The code was extracted from:\n * https://github.com/davidchambers/Base64.js\n */\n atobPolyfill = (input: any) => {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\n let str = String(input).replace(/=+$/, \"\");\n if (str.length % 4 == 1) {\n throw new Error(\n \"'atob' failed: The string to be decoded is not correctly encoded.\",\n );\n }\n\n for (\n // initialize result and counters\n var bc = 0, bs, buffer, idx = 0, output = \"\";\n // get next character\n (buffer = str.charAt(idx++));\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer &&\n ((bs = bc % 4 ? (bs as any) * 64 + buffer : buffer),\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4)\n ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n}\n\n/**\n * Returns JWT token's payload data.\n */\nexport function getTokenPayload(token: string): { [key: string]: any } {\n if (token) {\n try {\n const encodedPayload = decodeURIComponent(\n atobPolyfill(token.split(\".\")[1])\n .split(\"\")\n .map(function (c: string) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(\"\"),\n );\n\n return JSON.parse(encodedPayload) || {};\n } catch (e) {}\n }\n\n return {};\n}\n\n/**\n * Checks whether a JWT token is expired or not.\n * Tokens without `exp` payload key are considered valid.\n * Tokens with empty payload (eg. invalid token strings) are considered expired.\n *\n * @param token The token to check.\n * @param [expirationThreshold] Time in seconds that will be subtracted from the token `exp` property.\n */\nexport function isTokenExpired(token: string, expirationThreshold = 0): boolean {\n let payload = getTokenPayload(token);\n\n if (\n Object.keys(payload).length > 0 &&\n (!payload.exp || payload.exp - expirationThreshold > Date.now() / 1000)\n ) {\n return false;\n }\n\n return true;\n}\n","import { cookieParse, cookieSerialize, SerializeOptions } from \"@/stores/utils/cookie\";\nimport { isTokenExpired, getTokenPayload } from \"@/stores/utils/jwt\";\n\nexport type AuthModel = { [key: string]: any } | null;\n\nexport type OnStoreChangeFunc = (token: string, model: AuthModel) => void;\n\nconst defaultCookieKey = \"pb_auth\";\n\n/**\n * Base AuthStore class that is intended to be extended by all other\n * PocketBase AuthStore implementations.\n */\nexport abstract class BaseAuthStore {\n protected baseToken: string = \"\";\n protected baseModel: AuthModel = null;\n\n private _onChangeCallbacks: Array = [];\n\n /**\n * Retrieves the stored token (if any).\n */\n get token(): string {\n return this.baseToken;\n }\n\n /**\n * Retrieves the stored model data (if any).\n */\n get model(): AuthModel {\n return this.baseModel;\n }\n\n /**\n * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).\n */\n get isValid(): boolean {\n return !isTokenExpired(this.token);\n }\n\n /**\n * Checks whether the current store state is for admin authentication.\n */\n get isAdmin(): boolean {\n return getTokenPayload(this.token).type === \"admin\";\n }\n\n /**\n * Checks whether the current store state is for auth record authentication.\n */\n get isAuthRecord(): boolean {\n return getTokenPayload(this.token).type === \"authRecord\";\n }\n\n /**\n * Saves the provided new token and model data in the auth store.\n */\n save(token: string, model?: AuthModel): void {\n this.baseToken = token || \"\";\n this.baseModel = model || null;\n\n this.triggerChange();\n }\n\n /**\n * Removes the stored token and model data form the auth store.\n */\n clear(): void {\n this.baseToken = \"\";\n this.baseModel = null;\n this.triggerChange();\n }\n\n /**\n * Parses the provided cookie string and updates the store state\n * with the cookie's token and model data.\n *\n * NB! This function doesn't validate the token or its data.\n * Usually this isn't a concern if you are interacting only with the\n * PocketBase API because it has the proper server-side security checks in place,\n * but if you are using the store `isValid` state for permission controls\n * in a node server (eg. SSR), then it is recommended to call `authRefresh()`\n * after loading the cookie to ensure an up-to-date token and model state.\n * For example:\n *\n * ```js\n * pb.authStore.loadFromCookie(\"cookie string...\");\n *\n * try {\n * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)\n * pb.authStore.isValid && await pb.collection('users').authRefresh();\n * } catch (_) {\n * // clear the auth store on failed refresh\n * pb.authStore.clear();\n * }\n * ```\n */\n loadFromCookie(cookie: string, key = defaultCookieKey): void {\n const rawData = cookieParse(cookie || \"\")[key] || \"\";\n\n let data: { [key: string]: any } = {};\n try {\n data = JSON.parse(rawData);\n // normalize\n if (typeof data === null || typeof data !== \"object\" || Array.isArray(data)) {\n data = {};\n }\n } catch (_) {}\n\n this.save(data.token || \"\", data.model || null);\n }\n\n /**\n * Exports the current store state as cookie string.\n *\n * By default the following optional attributes are added:\n * - Secure\n * - HttpOnly\n * - SameSite=Strict\n * - Path=/\n * - Expires={the token expiration date}\n *\n * NB! If the generated cookie exceeds 4096 bytes, this method will\n * strip the model data to the bare minimum to try to fit within the\n * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.\n */\n exportToCookie(options?: SerializeOptions, key = defaultCookieKey): string {\n const defaultOptions: SerializeOptions = {\n secure: true,\n sameSite: true,\n httpOnly: true,\n path: \"/\",\n };\n\n // extract the token expiration date\n const payload = getTokenPayload(this.token);\n if (payload?.exp) {\n defaultOptions.expires = new Date(payload.exp * 1000);\n } else {\n defaultOptions.expires = new Date(\"1970-01-01\");\n }\n\n // merge with the user defined options\n options = Object.assign({}, defaultOptions, options);\n\n const rawData = {\n token: this.token,\n model: this.model ? JSON.parse(JSON.stringify(this.model)) : null,\n };\n\n let result = cookieSerialize(key, JSON.stringify(rawData), options);\n\n const resultLength =\n typeof Blob !== \"undefined\" ? new Blob([result]).size : result.length;\n\n // strip down the model data to the bare minimum\n if (rawData.model && resultLength > 4096) {\n rawData.model = { id: rawData?.model?.id, email: rawData?.model?.email };\n const extraProps = [\"collectionId\", \"username\", \"verified\"];\n for (const prop in this.model) {\n if (extraProps.includes(prop)) {\n rawData.model[prop] = this.model[prop];\n }\n }\n result = cookieSerialize(key, JSON.stringify(rawData), options);\n }\n\n return result;\n }\n\n /**\n * Register a callback function that will be called on store change.\n *\n * You can set the `fireImmediately` argument to true in order to invoke\n * the provided callback right after registration.\n *\n * Returns a removal function that you could call to \"unsubscribe\" from the changes.\n */\n onChange(callback: OnStoreChangeFunc, fireImmediately = false): () => void {\n this._onChangeCallbacks.push(callback);\n\n if (fireImmediately) {\n callback(this.token, this.model);\n }\n\n return () => {\n for (let i = this._onChangeCallbacks.length - 1; i >= 0; i--) {\n if (this._onChangeCallbacks[i] == callback) {\n delete this._onChangeCallbacks[i]; // removes the function reference\n this._onChangeCallbacks.splice(i, 1); // reindex the array\n return;\n }\n }\n };\n }\n\n protected triggerChange(): void {\n for (const callback of this._onChangeCallbacks) {\n callback && callback(this.token, this.model);\n }\n }\n}\n","import { BaseAuthStore, AuthModel } from \"@/stores/BaseAuthStore\";\n\n/**\n * The default token store for browsers with auto fallback\n * to runtime/memory if local storage is undefined (eg. in node env).\n */\nexport class LocalAuthStore extends BaseAuthStore {\n private storageFallback: { [key: string]: any } = {};\n private storageKey: string;\n\n constructor(storageKey = \"pocketbase_auth\") {\n super();\n\n this.storageKey = storageKey;\n\n this._bindStorageEvent();\n }\n\n /**\n * @inheritdoc\n */\n get token(): string {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.token || \"\";\n }\n\n /**\n * @inheritdoc\n */\n get model(): AuthModel {\n const data = this._storageGet(this.storageKey) || {};\n\n return data.model || null;\n }\n\n /**\n * @inheritdoc\n */\n save(token: string, model?: AuthModel) {\n this._storageSet(this.storageKey, {\n token: token,\n model: model,\n });\n\n super.save(token, model);\n }\n\n /**\n * @inheritdoc\n */\n clear() {\n this._storageRemove(this.storageKey);\n\n super.clear();\n }\n\n // ---------------------------------------------------------------\n // Internal helpers:\n // ---------------------------------------------------------------\n\n /**\n * Retrieves `key` from the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageGet(key: string): any {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n const rawValue = window.localStorage.getItem(key) || \"\";\n try {\n return JSON.parse(rawValue);\n } catch (e) {\n // not a json\n return rawValue;\n }\n }\n\n // fallback\n return this.storageFallback[key];\n }\n\n /**\n * Stores a new data in the browser's local storage\n * (or runtime/memory if local storage is undefined).\n */\n private _storageSet(key: string, value: any) {\n if (typeof window !== \"undefined\" && window?.localStorage) {\n // store in local storage\n let normalizedVal = value;\n if (typeof value !== \"string\") {\n normalizedVal = JSON.stringify(value);\n }\n window.localStorage.setItem(key, normalizedVal);\n } else {\n // store in fallback\n this.storageFallback[key] = value;\n }\n }\n\n /**\n * Removes `key` from the browser's local storage and the runtime/memory.\n */\n private _storageRemove(key: string) {\n // delete from local storage\n if (typeof window !== \"undefined\" && window?.localStorage) {\n window.localStorage?.removeItem(key);\n }\n\n // delete from fallback\n delete this.storageFallback[key];\n }\n\n /**\n * Updates the current store state on localStorage change.\n */\n private _bindStorageEvent() {\n if (\n typeof window === \"undefined\" ||\n !window?.localStorage ||\n !window.addEventListener\n ) {\n return;\n }\n\n window.addEventListener(\"storage\", (e) => {\n if (e.key != this.storageKey) {\n return;\n }\n\n const data = this._storageGet(this.storageKey) || {};\n\n super.save(data.token || \"\", data.model || null);\n });\n }\n}\n","import Client from \"@/Client\";\n\n/**\n * BaseService class that should be inherited from all API services.\n */\nexport abstract class BaseService {\n readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\ninterface appleClientSecret {\n secret: string;\n}\n\nexport class SettingsService extends BaseService {\n /**\n * Fetch all available app settings.\n *\n * @throws {ClientResponseError}\n */\n async getAll(options?: CommonOptions): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Bulk updates app settings.\n *\n * @throws {ClientResponseError}\n */\n async update(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise<{ [key: string]: any }> {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/settings\", options);\n }\n\n /**\n * Performs a S3 filesystem connection test.\n *\n * The currently supported `filesystem` are \"storage\" and \"backups\".\n *\n * @throws {ClientResponseError}\n */\n async testS3(\n filesystem: string = \"storage\",\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n filesystem: filesystem,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/s3\", options).then(() => true);\n }\n\n /**\n * Sends a test email.\n *\n * The possible `emailTemplate` values are:\n * - verification\n * - password-reset\n * - email-change\n *\n * @throws {ClientResponseError}\n */\n async testEmail(\n toEmail: string,\n emailTemplate: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n email: toEmail,\n template: emailTemplate,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/test/email\", options).then(() => true);\n }\n\n /**\n * Generates a new Apple OAuth2 client secret.\n *\n * @throws {ClientResponseError}\n */\n async generateAppleClientSecret(\n clientId: string,\n teamId: string,\n keyId: string,\n privateKey: string,\n duration: number,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n clientId,\n teamId,\n keyId,\n privateKey,\n duration,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/settings/apple/generate-client-secret\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, FullListOptions } from \"@/services/utils/options\";\n\nexport abstract class CrudService extends BaseService {\n /**\n * Base path for the crud actions (without trailing slash, eg. '/admins').\n */\n abstract get baseCrudPath(): string;\n\n /**\n * Response data decoder.\n */\n decode(data: { [key: string]: any }): T {\n return data as T;\n }\n\n /**\n * Returns a promise with all list items batch fetched at once\n * (by default 500 items per request; to change it set the `batch` query param).\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: FullListOptions): Promise>;\n\n /**\n * Legacy version of getFullList with explicitly specified batch size.\n */\n async getFullList(batch?: number, options?: ListOptions): Promise>;\n\n async getFullList(\n batchOrqueryParams?: number | FullListOptions,\n options?: ListOptions,\n ): Promise> {\n if (typeof batchOrqueryParams == \"number\") {\n return this._getFullList(batchOrqueryParams, options);\n }\n\n options = Object.assign({}, batchOrqueryParams, options);\n\n let batch = 500;\n if (options.batch) {\n batch = options.batch;\n delete options.batch;\n }\n\n return this._getFullList(batch, options);\n }\n\n /**\n * Returns paginated items list.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(this.baseCrudPath, options).then((responseData: any) => {\n responseData.items =\n responseData.items?.map((item: any) => {\n return this.decode(item);\n }) || [];\n\n return responseData;\n });\n }\n\n /**\n * Returns the first found item by the specified filter.\n *\n * Internally it calls `getList(1, 1, { filter, skipTotal })` and\n * returns the first found item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * For consistency with `getOne`, this method will throw a 404\n * ClientResponseError if no item was found.\n *\n * @throws {ClientResponseError}\n */\n async getFirstListItem(filter: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n requestKey: \"one_by_filter_\" + this.baseCrudPath + \"_\" + filter,\n },\n options,\n );\n\n options.query = Object.assign(\n {\n filter: filter,\n skipTotal: 1,\n },\n options.query,\n );\n\n return this.getList(1, 1, options).then((result) => {\n if (!result?.items?.length) {\n throw new ClientResponseError({\n status: 404,\n response: {\n code: 404,\n message: \"The requested resource wasn't found.\",\n data: {},\n },\n });\n }\n\n return result.items[0];\n });\n }\n\n /**\n * Returns single item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(this.baseCrudPath + \"/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required record id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Creates a new item.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath, options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Updates an existing item by its id.\n *\n * You can use the generic T to supply a wrapper type of the crud model.\n *\n * @throws {ClientResponseError}\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PATCH\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then((responseData: any) => this.decode(responseData));\n }\n\n /**\n * Deletes an existing item by its id.\n *\n * @throws {ClientResponseError}\n */\n async delete(id: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/\" + encodeURIComponent(id), options)\n .then(() => true);\n }\n\n /**\n * Returns a promise with all list items batch fetched at once.\n */\n protected _getFullList(\n batchSize = 500,\n options?: ListOptions,\n ): Promise> {\n options = options || {};\n options.query = Object.assign(\n {\n skipTotal: 1,\n },\n options.query,\n );\n\n let result: Array = [];\n\n let request = async (page: number): Promise> => {\n return this.getList(page, batchSize || 500, options).then((list) => {\n const castedList = list as any as ListResult;\n const items = castedList.items;\n\n result = result.concat(items);\n\n if (items.length == list.perPage) {\n return request(page + 1);\n }\n\n return result;\n });\n };\n\n return request(1);\n }\n}\n","import { SendOptions } from \"@/services/utils/options\";\n\nexport function normalizeLegacyOptionsArgs(\n legacyWarn: string,\n baseOptions: SendOptions,\n bodyOrOptions?: any,\n query?: any,\n): SendOptions {\n const hasBodyOrOptions = typeof bodyOrOptions !== \"undefined\";\n const hasQuery = typeof query !== \"undefined\";\n\n if (!hasQuery && !hasBodyOrOptions) {\n return baseOptions;\n }\n\n if (hasQuery) {\n console.warn(legacyWarn);\n baseOptions.body = Object.assign({}, baseOptions.body, bodyOrOptions);\n baseOptions.query = Object.assign({}, baseOptions.query, query);\n\n return baseOptions;\n }\n\n return Object.assign(baseOptions, bodyOrOptions);\n}\n","import Client from \"@/Client\";\nimport { isTokenExpired } from \"@/stores/utils/jwt\";\n\n// reset previous auto refresh registrations\nexport function resetAutoRefresh(client: Client) {\n (client as any)._resetAutoRefresh?.();\n}\n\nexport function registerAutoRefresh(\n client: Client,\n threshold: number,\n refreshFunc: () => Promise,\n reauthenticateFunc: () => Promise,\n) {\n resetAutoRefresh(client);\n\n const oldBeforeSend = client.beforeSend;\n const oldModel = client.authStore.model;\n\n // unset the auto refresh in case the auth store was cleared\n // OR a new model was authenticated\n const unsubStoreChange = client.authStore.onChange((newToken, model) => {\n if (\n !newToken ||\n model?.id != oldModel?.id ||\n // check the collection id in case an admin and auth record share the same id\n ((model?.collectionId || oldModel?.collectionId) &&\n model?.collectionId != oldModel?.collectionId)\n ) {\n resetAutoRefresh(client);\n }\n });\n\n // initialize a reset function and attach it dynamically to the client\n (client as any)._resetAutoRefresh = function () {\n unsubStoreChange();\n client.beforeSend = oldBeforeSend;\n delete (client as any)._resetAutoRefresh;\n };\n\n client.beforeSend = async (url, sendOptions) => {\n const oldToken = client.authStore.token;\n\n if (sendOptions.query?.autoRefresh) {\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n }\n\n let isValid = client.authStore.isValid;\n if (\n // is loosely valid\n isValid &&\n // but it is going to expire in the next \"threshold\" seconds\n isTokenExpired(client.authStore.token, threshold)\n ) {\n try {\n await refreshFunc();\n } catch (_) {\n isValid = false;\n }\n }\n\n // still invalid -> reauthenticate\n if (!isValid) {\n await reauthenticateFunc();\n }\n\n // the request wasn't sent with a custom token\n const headers = sendOptions.headers || {};\n for (let key in headers) {\n if (\n key.toLowerCase() == \"authorization\" &&\n // the request wasn't sent with a custom token\n oldToken == headers[key] &&\n client.authStore.token\n ) {\n // set the latest store token\n headers[key] = client.authStore.token;\n break;\n }\n }\n sendOptions.headers = headers;\n\n return oldBeforeSend ? oldBeforeSend(url, sendOptions) : { url, sendOptions };\n };\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { AdminModel } from \"@/services/utils/dtos\";\nimport { AuthOptions, CommonOptions } from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\nimport { registerAutoRefresh, resetAutoRefresh } from \"@/services/utils/refresh\";\n\nexport interface AdminAuthResponse {\n [key: string]: any;\n\n token: string;\n admin: AdminModel;\n}\n\nexport class AdminService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/admins\";\n }\n\n // ---------------------------------------------------------------\n // Post update/delete AuthStore sync\n // ---------------------------------------------------------------\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n // update the store state if the updated item id matches with the stored model\n if (\n this.client.authStore.model?.id === item.id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n // clear the store state if the deleted item id matches with the stored model\n if (\n success &&\n this.client.authStore.model?.id === id &&\n typeof this.client.authStore.model?.collectionId === \"undefined\" // is not record auth\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful authorize response.\n */\n protected authResponse(responseData: any): AdminAuthResponse {\n const admin = this.decode(responseData?.admin || {});\n\n if (responseData?.token && responseData?.admin) {\n this.client.authStore.save(responseData.token, admin);\n }\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n admin: admin,\n });\n }\n\n /**\n * Authenticate an admin account with its email and password\n * and returns a new admin token and data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n email: string,\n password: string,\n options?: AuthOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using authWithPassword(email, password, options?).\n */\n async authWithPassword(\n email: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async authWithPassword(\n email: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n identity: email,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(email, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(email, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n const autoRefreshThreshold = options.autoRefreshThreshold;\n delete options.autoRefreshThreshold;\n\n // not from auto refresh reauthentication\n if (!options.autoRefresh) {\n resetAutoRefresh(this.client);\n }\n\n let authData = await this.client.send(\n this.baseCrudPath + \"/auth-with-password\",\n options,\n );\n\n authData = this.authResponse(authData);\n\n if (autoRefreshThreshold) {\n registerAutoRefresh(\n this.client,\n autoRefreshThreshold,\n () => this.authRefresh({ autoRefresh: true }),\n () =>\n this.authWithPassword(\n email,\n password,\n Object.assign({ autoRefresh: true }, options),\n ),\n );\n }\n\n return authData;\n }\n\n /**\n * Refreshes the current admin authenticated instance and\n * returns a new token and admin data.\n *\n * On success this method automatically updates the client's AuthStore data.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise;\n\n async authRefresh(bodyOrOptions?: any, query?: any): Promise {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/auth-refresh\", options)\n .then(this.authResponse.bind(this));\n }\n\n /**\n * Sends admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms admin password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(resetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n resetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: resetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(resetToken, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(resetToken, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCrudPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n}\n","export interface SendOptions extends RequestInit {\n // for backward compatibility and to minimize the verbosity,\n // any top-level field that doesn't exist in RequestInit or the\n // fields below will be treated as query parameter.\n [key: string]: any;\n\n /**\n * Optional custom fetch function to use for sending the request.\n */\n fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise;\n\n /**\n * Custom headers to send with the requests.\n */\n headers?: { [key: string]: string };\n\n /**\n * The body of the request (serialized automatically for json requests).\n */\n body?: any;\n\n /**\n * Query parameters that will be appended to the request url.\n */\n query?: { [key: string]: any };\n\n /**\n * @deprecated use `query` instead\n *\n * for backward-compatibility `params` values are merged with `query`,\n * but this option may get removed in the final v1 release\n */\n params?: { [key: string]: any };\n\n /**\n * The request identifier that can be used to cancel pending requests.\n */\n requestKey?: string | null;\n\n /**\n * @deprecated use `requestKey:string` instead\n */\n $cancelKey?: string;\n\n /**\n * @deprecated use `requestKey:null` instead\n */\n $autoCancel?: boolean;\n}\n\nexport interface CommonOptions extends SendOptions {\n fields?: string;\n}\n\nexport interface ListOptions extends CommonOptions {\n page?: number;\n perPage?: number;\n sort?: string;\n filter?: string;\n skipTotal?: boolean;\n}\n\nexport interface FullListOptions extends ListOptions {\n batch?: number;\n}\n\nexport interface RecordOptions extends CommonOptions {\n expand?: string;\n}\n\nexport interface RecordListOptions extends ListOptions, RecordOptions {}\n\nexport interface RecordFullListOptions extends FullListOptions, RecordOptions {}\n\nexport interface LogStatsOptions extends CommonOptions {\n filter?: string;\n}\n\nexport interface FileOptions extends CommonOptions {\n thumb?: string;\n download?: boolean;\n}\n\nexport interface AuthOptions extends CommonOptions {\n /**\n * If autoRefreshThreshold is set it will take care to auto refresh\n * when necessary the auth data before each request to ensure that\n * the auth state is always valid.\n *\n * The value must be in seconds, aka. the amount of seconds\n * that will be subtracted from the current token `exp` claim in order\n * to determine whether it is going to expire within the specified time threshold.\n *\n * For example, if you want to auto refresh the token if it is\n * going to expire in the next 30mins (or already has expired),\n * it can be set to `1800`\n */\n autoRefreshThreshold?: number;\n}\n\n// -------------------------------------------------------------------\n\n// list of known SendOptions keys (everything else is treated as query param)\nconst knownSendOptionsKeys = [\n \"requestKey\",\n \"$cancelKey\",\n \"$autoCancel\",\n \"fetch\",\n \"headers\",\n \"body\",\n \"query\",\n \"params\",\n // ---,\n \"cache\",\n \"credentials\",\n \"headers\",\n \"integrity\",\n \"keepalive\",\n \"method\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"window\",\n];\n\n// modifies in place the provided options by moving unknown send options as query parameters.\nexport function normalizeUnknownQueryParams(options?: SendOptions): void {\n if (!options) {\n return;\n }\n\n options.query = options.query || {};\n for (let key in options) {\n if (knownSendOptionsKeys.includes(key)) {\n continue;\n }\n\n options.query[key] = options[key];\n delete options[key];\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { SendOptions, normalizeUnknownQueryParams } from \"@/services/utils/options\";\n\ninterface promiseCallbacks {\n resolve: Function;\n reject: Function;\n}\n\ntype Subscriptions = { [key: string]: Array };\n\nexport type UnsubscribeFunc = () => Promise;\n\nexport class RealtimeService extends BaseService {\n clientId: string = \"\";\n\n private eventSource: EventSource | null = null;\n private subscriptions: Subscriptions = {};\n private lastSentSubscriptions: Array = [];\n private connectTimeoutId: any;\n private maxConnectTimeout: number = 15000;\n private reconnectTimeoutId: any;\n private reconnectAttempts: number = 0;\n private maxReconnectAttempts: number = Infinity;\n private predefinedReconnectIntervals: Array = [\n 200, 300, 500, 1000, 1200, 1500, 2000,\n ];\n private pendingConnects: Array = [];\n\n /**\n * Returns whether the realtime connection has been established.\n */\n get isConnected(): boolean {\n return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;\n }\n\n /**\n * Register the subscription listener.\n *\n * You can subscribe multiple times to the same topic.\n *\n * If the SSE connection is not started yet,\n * this method will also initialize it.\n */\n async subscribe(\n topic: string,\n callback: (data: any) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"topic must be set.\");\n }\n\n let key = topic;\n\n // serialize and append the topic options (if any)\n if (options) {\n normalizeUnknownQueryParams(options);\n const serialized =\n \"options=\" +\n encodeURIComponent(\n JSON.stringify({ query: options.query, headers: options.headers }),\n );\n key += (key.includes(\"?\") ? \"&\" : \"?\") + serialized;\n }\n\n const listener = function (e: Event) {\n const msgEvent = e as MessageEvent;\n\n let data;\n try {\n data = JSON.parse(msgEvent?.data);\n } catch {}\n\n callback(data || {});\n };\n\n // store the listener\n if (!this.subscriptions[key]) {\n this.subscriptions[key] = [];\n }\n this.subscriptions[key].push(listener);\n\n if (!this.isConnected) {\n // initialize sse connection\n await this.connect();\n } else if (this.subscriptions[key].length === 1) {\n // send the updated subscriptions (if it is the first for the key)\n await this.submitSubscriptions();\n } else {\n // only register the listener\n this.eventSource?.addEventListener(key, listener);\n }\n\n return async (): Promise => {\n return this.unsubscribeByTopicAndListener(topic, listener);\n };\n }\n\n /**\n * Unsubscribe from all subscription listeners with the specified topic.\n *\n * If `topic` is not provided, then this method will unsubscribe\n * from all active subscriptions.\n *\n * This method is no-op if there are no active subscriptions.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribe(topic?: string): Promise {\n let needToSubmit = false;\n\n if (!topic) {\n // remove all subscriptions\n this.subscriptions = {};\n } else {\n // remove all listeners related to the topic\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (!this.hasSubscriptionListeners(key)) {\n continue; // already unsubscribed\n }\n\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit) {\n needToSubmit = true;\n }\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n /**\n * Unsubscribe from all subscription listeners starting with the specified topic prefix.\n *\n * This method is no-op if there are no active subscriptions with the specified topic prefix.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByPrefix(keyPrefix: string): Promise {\n let hasAtleastOneTopic = false;\n for (let key in this.subscriptions) {\n // \"?\" so that it can be used as end delimiter for the prefix\n if (!(key + \"?\").startsWith(keyPrefix)) {\n continue;\n }\n\n hasAtleastOneTopic = true;\n for (let listener of this.subscriptions[key]) {\n this.eventSource?.removeEventListener(key, listener);\n }\n delete this.subscriptions[key];\n }\n\n if (!hasAtleastOneTopic) {\n return; // nothing to unsubscribe from\n }\n\n if (this.hasSubscriptionListeners()) {\n // submit the deleted subscriptions\n await this.submitSubscriptions();\n } else {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n }\n }\n\n /**\n * Unsubscribe from all subscriptions matching the specified topic and listener function.\n *\n * This method is no-op if there are no active subscription with\n * the specified topic and listener.\n *\n * The related sse connection will be autoclosed if after the\n * unsubscribe operation there are no active subscriptions left.\n */\n async unsubscribeByTopicAndListener(\n topic: string,\n listener: EventListener,\n ): Promise {\n let needToSubmit = false;\n\n const subs = this.getSubscriptionsByTopic(topic);\n for (let key in subs) {\n if (\n !Array.isArray(this.subscriptions[key]) ||\n !this.subscriptions[key].length\n ) {\n continue; // already unsubscribed\n }\n\n let exist = false;\n for (let i = this.subscriptions[key].length - 1; i >= 0; i--) {\n if (this.subscriptions[key][i] !== listener) {\n continue;\n }\n\n exist = true; // has at least one matching listener\n delete this.subscriptions[key][i]; // removes the function reference\n this.subscriptions[key].splice(i, 1); // reindex the array\n this.eventSource?.removeEventListener(key, listener);\n }\n if (!exist) {\n continue;\n }\n\n // remove the key from the subscriptions list if there are no other listeners\n if (!this.subscriptions[key].length) {\n delete this.subscriptions[key];\n }\n\n // mark for subscriptions change submit if there are no other listeners\n if (!needToSubmit && !this.hasSubscriptionListeners(key)) {\n needToSubmit = true;\n }\n }\n\n if (!this.hasSubscriptionListeners()) {\n // no other active subscriptions -> close the sse connection\n this.disconnect();\n } else if (needToSubmit) {\n await this.submitSubscriptions();\n }\n }\n\n private hasSubscriptionListeners(keyToCheck?: string): boolean {\n this.subscriptions = this.subscriptions || {};\n\n // check the specified key\n if (keyToCheck) {\n return !!this.subscriptions[keyToCheck]?.length;\n }\n\n // check for at least one non-empty subscription\n for (let key in this.subscriptions) {\n if (!!this.subscriptions[key]?.length) {\n return true;\n }\n }\n\n return false;\n }\n\n private async submitSubscriptions(): Promise {\n if (!this.clientId) {\n return; // no client/subscriber\n }\n\n // optimistic update\n this.addAllSubscriptionListeners();\n\n this.lastSentSubscriptions = this.getNonEmptySubscriptionKeys();\n\n return this.client\n .send(\"/api/realtime\", {\n method: \"POST\",\n body: {\n clientId: this.clientId,\n subscriptions: this.lastSentSubscriptions,\n },\n requestKey: this.getSubscriptionsCancelKey(),\n })\n .catch((err) => {\n if (err?.isAbort) {\n return; // silently ignore aborted pending requests\n }\n throw err;\n });\n }\n\n private getSubscriptionsCancelKey(): string {\n return \"realtime_\" + this.clientId;\n }\n\n private getSubscriptionsByTopic(topic: string): Subscriptions {\n const result: Subscriptions = {};\n\n // \"?\" so that it can be used as end delimiter for the topic\n topic = topic.includes(\"?\") ? topic : topic + \"?\";\n\n for (let key in this.subscriptions) {\n if ((key + \"?\").startsWith(topic)) {\n result[key] = this.subscriptions[key];\n }\n }\n\n return result;\n }\n\n private getNonEmptySubscriptionKeys(): Array {\n const result: Array = [];\n\n for (let key in this.subscriptions) {\n if (this.subscriptions[key].length) {\n result.push(key);\n }\n }\n\n return result;\n }\n\n private addAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n this.removeAllSubscriptionListeners();\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.addEventListener(key, listener);\n }\n }\n }\n\n private removeAllSubscriptionListeners(): void {\n if (!this.eventSource) {\n return;\n }\n\n for (let key in this.subscriptions) {\n for (let listener of this.subscriptions[key]) {\n this.eventSource.removeEventListener(key, listener);\n }\n }\n }\n\n private async connect(): Promise {\n if (this.reconnectAttempts > 0) {\n // immediately resolve the promise to avoid indefinitely\n // blocking the client during reconnection\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.pendingConnects.push({ resolve, reject });\n\n if (this.pendingConnects.length > 1) {\n // all promises will be resolved once the connection is established\n return;\n }\n\n this.initConnect();\n });\n }\n\n private initConnect() {\n this.disconnect(true);\n\n // wait up to 15s for connect\n clearTimeout(this.connectTimeoutId);\n this.connectTimeoutId = setTimeout(() => {\n this.connectErrorHandler(new Error(\"EventSource connect took too long.\"));\n }, this.maxConnectTimeout);\n\n this.eventSource = new EventSource(this.client.buildUrl(\"/api/realtime\"));\n\n this.eventSource.onerror = (_) => {\n this.connectErrorHandler(\n new Error(\"Failed to establish realtime connection.\"),\n );\n };\n\n this.eventSource.addEventListener(\"PB_CONNECT\", (e) => {\n const msgEvent = e as MessageEvent;\n this.clientId = msgEvent?.lastEventId;\n\n this.submitSubscriptions()\n .then(async () => {\n let retries = 3;\n while (this.hasUnsentSubscriptions() && retries > 0) {\n retries--;\n // resubscribe to ensure that the latest topics are submitted\n //\n // This is needed because missed topics could happen on reconnect\n // if after the pending sent `submitSubscriptions()` call another `subscribe()`\n // was made before the submit was able to complete.\n await this.submitSubscriptions();\n }\n })\n .then(() => {\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n\n // reset connect meta\n this.pendingConnects = [];\n this.reconnectAttempts = 0;\n clearTimeout(this.reconnectTimeoutId);\n clearTimeout(this.connectTimeoutId);\n\n // propagate the PB_CONNECT event\n const connectSubs = this.getSubscriptionsByTopic(\"PB_CONNECT\");\n for (let key in connectSubs) {\n for (let listener of connectSubs[key]) {\n listener(e);\n }\n }\n })\n .catch((err) => {\n this.clientId = \"\";\n this.connectErrorHandler(err);\n });\n });\n }\n\n private hasUnsentSubscriptions(): boolean {\n const latestTopics = this.getNonEmptySubscriptionKeys();\n if (latestTopics.length != this.lastSentSubscriptions.length) {\n return true;\n }\n\n for (const t of latestTopics) {\n if (!this.lastSentSubscriptions.includes(t)) {\n return true;\n }\n }\n\n return false;\n }\n\n private connectErrorHandler(err: any) {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n\n if (\n // wasn't previously connected -> direct reject\n (!this.clientId && !this.reconnectAttempts) ||\n // was previously connected but the max reconnection limit has been reached\n this.reconnectAttempts > this.maxReconnectAttempts\n ) {\n for (let p of this.pendingConnects) {\n p.reject(new ClientResponseError(err));\n }\n this.pendingConnects = [];\n this.disconnect();\n return;\n }\n\n // otherwise -> reconnect in the background\n this.disconnect(true);\n const timeout =\n this.predefinedReconnectIntervals[this.reconnectAttempts] ||\n this.predefinedReconnectIntervals[\n this.predefinedReconnectIntervals.length - 1\n ];\n this.reconnectAttempts++;\n this.reconnectTimeoutId = setTimeout(() => {\n this.initConnect();\n }, timeout);\n }\n\n private disconnect(fromReconnect = false): void {\n clearTimeout(this.connectTimeoutId);\n clearTimeout(this.reconnectTimeoutId);\n this.removeAllSubscriptionListeners();\n this.client.cancelRequest(this.getSubscriptionsCancelKey());\n this.eventSource?.close();\n this.eventSource = null;\n this.clientId = \"\";\n\n if (!fromReconnect) {\n this.reconnectAttempts = 0;\n\n // resolve any remaining connect promises\n //\n // this is done to avoid unnecessary throwing errors in case\n // unsubscribe is called before the pending connect promises complete\n // (see https://github.com/pocketbase/pocketbase/discussions/2897#discussioncomment-6423818)\n for (let p of this.pendingConnects) {\n p.resolve();\n }\n this.pendingConnects = [];\n }\n }\n}\n","import Client from \"@/Client\";\nimport { getTokenPayload } from \"@/stores/utils/jwt\";\nimport { CrudService } from \"@/services/utils/CrudService\";\nimport { RealtimeService, UnsubscribeFunc } from \"@/services/RealtimeService\";\nimport { ClientResponseError } from \"@/ClientResponseError\";\nimport { ListResult, RecordModel, ExternalAuthModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n CommonOptions,\n RecordOptions,\n RecordListOptions,\n RecordFullListOptions,\n} from \"@/services/utils/options\";\nimport { normalizeLegacyOptionsArgs } from \"@/services/utils/legacy\";\n\nexport interface RecordAuthResponse {\n /**\n * The signed PocketBase auth record.\n */\n record: T;\n\n /**\n * The PocketBase record auth token.\n *\n * If you are looking for the OAuth2 access and refresh tokens\n * they are available under the `meta.accessToken` and `meta.refreshToken` props.\n */\n token: string;\n\n /**\n * Auth meta data usually filled when OAuth2 is used.\n */\n meta?: { [key: string]: any };\n}\n\nexport interface AuthProviderInfo {\n name: string;\n displayName: string;\n state: string;\n authUrl: string;\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n}\n\nexport interface AuthMethodsList {\n usernamePassword: boolean;\n emailPassword: boolean;\n onlyVerified: boolean;\n authProviders: Array;\n}\n\nexport interface RecordSubscription {\n action: string; // eg. create, update, delete\n record: T;\n}\n\nexport type OAuth2UrlCallback = (url: string) => void | Promise;\n\nexport interface OAuth2AuthConfig extends SendOptions {\n // the name of the OAuth2 provider (eg. \"google\")\n provider: string;\n\n // custom scopes to overwrite the default ones\n scopes?: Array;\n\n // optional record create data\n createData?: { [key: string]: any };\n\n // optional callback that is triggered after the OAuth2 sign-in/sign-up url generation\n urlCallback?: OAuth2UrlCallback;\n\n // optional query params to send with the PocketBase auth request (eg. fields, expand, etc.)\n query?: RecordOptions;\n}\n\nexport class RecordService extends CrudService {\n readonly collectionIdOrName: string;\n\n constructor(client: Client, collectionIdOrName: string) {\n super(client);\n\n this.collectionIdOrName = collectionIdOrName;\n }\n\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return this.baseCollectionPath + \"/records\";\n }\n\n /**\n * Returns the current collection service base path.\n */\n get baseCollectionPath(): string {\n return \"/api/collections/\" + encodeURIComponent(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Realtime handlers\n // ---------------------------------------------------------------\n\n /**\n * Subscribe to realtime changes to the specified topic (\"*\" or record id).\n *\n * If `topic` is the wildcard \"*\", then this method will subscribe to\n * any record changes in the collection.\n *\n * If `topic` is a record id, then this method will subscribe only\n * to changes of the specified record id.\n *\n * It's OK to subscribe multiple times to the same topic.\n * You can use the returned `UnsubscribeFunc` to remove only a single subscription.\n * Or use `unsubscribe(topic)` if you want to remove all subscriptions attached to the topic.\n */\n async subscribe(\n topic: string,\n callback: (data: RecordSubscription) => void,\n options?: SendOptions,\n ): Promise {\n if (!topic) {\n throw new Error(\"Missing topic.\");\n }\n\n if (!callback) {\n throw new Error(\"Missing subscription callback.\");\n }\n\n return this.client.realtime.subscribe(\n this.collectionIdOrName + \"/\" + topic,\n callback,\n options,\n );\n }\n\n /**\n * Unsubscribe from all subscriptions of the specified topic\n * (\"*\" or record id).\n *\n * If `topic` is not set, then this method will unsubscribe from\n * all subscriptions associated to the current collection.\n */\n async unsubscribe(topic?: string): Promise {\n // unsubscribe from the specified topic\n if (topic) {\n return this.client.realtime.unsubscribe(\n this.collectionIdOrName + \"/\" + topic,\n );\n }\n\n // unsubscribe from everything related to the collection\n return this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);\n }\n\n // ---------------------------------------------------------------\n // Crud handers\n // ---------------------------------------------------------------\n /**\n * @inheritdoc\n */\n async getFullList(options?: RecordFullListOptions): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batch?: number,\n options?: RecordListOptions,\n ): Promise>;\n\n /**\n * @inheritdoc\n */\n async getFullList(\n batchOrOptions?: number | RecordFullListOptions,\n options?: RecordListOptions,\n ): Promise> {\n if (typeof batchOrOptions == \"number\") {\n return super.getFullList(batchOrOptions, options);\n }\n\n const params = Object.assign({}, batchOrOptions, options);\n\n return super.getFullList(params);\n }\n\n /**\n * @inheritdoc\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: RecordListOptions,\n ): Promise> {\n return super.getList(page, perPage, options);\n }\n\n /**\n * @inheritdoc\n */\n async getFirstListItem(\n filter: string,\n options?: RecordListOptions,\n ): Promise {\n return super.getFirstListItem(filter, options);\n }\n\n /**\n * @inheritdoc\n */\n async getOne(id: string, options?: RecordOptions): Promise {\n return super.getOne(id, options);\n }\n\n /**\n * @inheritdoc\n */\n async create(\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.create(bodyParams, options);\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the updated id, then\n * on success the `client.authStore.model` will be updated with the result.\n */\n async update(\n id: string,\n bodyParams?: { [key: string]: any } | FormData,\n options?: RecordOptions,\n ): Promise {\n return super.update(id, bodyParams, options).then((item) => {\n if (\n // is record auth\n this.client.authStore.model?.id === item?.id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.save(this.client.authStore.token, item);\n }\n\n return item as any as T;\n });\n }\n\n /**\n * @inheritdoc\n *\n * If the current `client.authStore.model` matches with the deleted id,\n * then on success the `client.authStore` will be cleared.\n */\n async delete(id: string, options?: CommonOptions): Promise {\n return super.delete(id, options).then((success) => {\n if (\n success &&\n // is record auth\n this.client.authStore.model?.id === id &&\n (this.client.authStore.model?.collectionId === this.collectionIdOrName ||\n this.client.authStore.model?.collectionName ===\n this.collectionIdOrName)\n ) {\n this.client.authStore.clear();\n }\n\n return success;\n });\n }\n\n // ---------------------------------------------------------------\n // Auth handlers\n // ---------------------------------------------------------------\n\n /**\n * Prepare successful collection authorization response.\n */\n protected authResponse(responseData: any): RecordAuthResponse {\n const record = this.decode(responseData?.record || {});\n\n this.client.authStore.save(responseData?.token, record as any);\n\n return Object.assign({}, responseData, {\n // normalize common fields\n token: responseData?.token || \"\",\n record: record as any as T,\n });\n }\n\n /**\n * Returns all available collection auth methods.\n *\n * @throws {ClientResponseError}\n */\n async listAuthMethods(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-methods\", options)\n .then((responseData: any) => {\n return Object.assign({}, responseData, {\n // normalize common fields\n usernamePassword: !!responseData?.usernamePassword,\n emailPassword: !!responseData?.emailPassword,\n authProviders: Array.isArray(responseData?.authProviders)\n ? responseData?.authProviders\n : [],\n });\n });\n }\n\n /**\n * Authenticate a single auth collection record via its username/email and password.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n *\n * @throws {ClientResponseError}\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithPassword(usernameOrEmail, password, options?).\n */\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithPassword(\n usernameOrEmail: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n identity: usernameOrEmail,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithPassword(usernameOrEmail, pass, body?, query?) is deprecated. Consider replacing it with authWithPassword(usernameOrEmail, pass, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-password\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Authenticate a single auth collection record with OAuth2 code.\n *\n * If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n options?: RecordOptions,\n ): Promise>;\n\n /**\n * @deprecated\n * Consider using authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createdData, options?).\n */\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n body?: any,\n query?: any,\n ): Promise>;\n\n async authWithOAuth2Code(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n body: {\n provider: provider,\n code: code,\n codeVerifier: codeVerifier,\n redirectUrl: redirectUrl,\n createData: createData,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, body?, query?) is deprecated. Consider replacing it with authWithOAuth2Code(provider, code, codeVerifier, redirectUrl, createData?, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-with-oauth2\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * @deprecated This form of authWithOAuth2 is deprecated.\n *\n * Please use `authWithOAuth2Code()` OR its simplified realtime version\n * as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\n */\n async authWithOAuth2(\n provider: string,\n code: string,\n codeVerifier: string,\n redirectUrl: string,\n createData?: { [key: string]: any },\n bodyParams?: { [key: string]: any },\n queryParams?: RecordOptions,\n ): Promise>;\n\n /**\n * Authenticate a single auth collection record with OAuth2\n * **without custom redirects, deeplinks or even page reload**.\n *\n * This method initializes a one-off realtime subscription and will\n * open a popup window with the OAuth2 vendor page to authenticate.\n * Once the external OAuth2 sign-in/sign-up flow is completed, the popup\n * window will be automatically closed and the OAuth2 data sent back\n * to the user through the previously established realtime connection.\n *\n * You can specify an optional `urlCallback` prop to customize\n * the default url `window.open` behavior.\n *\n * On success, this method also automatically updates\n * the client's AuthStore data and returns:\n * - the authentication token\n * - the authenticated record model\n * - the OAuth2 account data (eg. name, email, avatar, etc.)\n *\n * Example:\n *\n * ```js\n * const authData = await pb.collection(\"users\").authWithOAuth2({\n * provider: \"google\",\n * })\n * ```\n *\n * Note1: When creating the OAuth2 app in the provider dashboard\n * you have to configure `https://yourdomain.com/api/oauth2-redirect`\n * as redirect URL.\n *\n * Note2: Safari may block the default `urlCallback` popup because\n * it doesn't allow `window.open` calls as part of an `async` click functions.\n * To workaround this you can either change your click handler to not be marked as `async`\n * OR manually call `window.open` before your `async` function and use the\n * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061).\n * For example:\n * ```js\n * \n * ...\n * document.getElementById(\"btn\").addEventListener(\"click\", () => {\n * pb.collection(\"users\").authWithOAuth2({\n * provider: \"gitlab\",\n * }).then((authData) => {\n * console.log(authData)\n * }).catch((err) => {\n * console.log(err, err.originalError);\n * });\n * })\n * ```\n *\n *\n * @throws {ClientResponseError}\n */\n async authWithOAuth2(\n options: OAuth2AuthConfig,\n ): Promise>;\n\n authWithOAuth2(...args: any): Promise> {\n // fallback to legacy format\n if (args.length > 1 || typeof args?.[0] === \"string\") {\n console.warn(\n \"PocketBase: This form of authWithOAuth2() is deprecated and may get removed in the future. Please replace with authWithOAuth2Code() OR use the authWithOAuth2() realtime form as shown in https://pocketbase.io/docs/authentication/#oauth2-integration.\",\n );\n return this.authWithOAuth2Code(\n args?.[0] || \"\",\n args?.[1] || \"\",\n args?.[2] || \"\",\n args?.[3] || \"\",\n args?.[4] || {},\n args?.[5] || {},\n args?.[6] || {},\n );\n }\n\n const config = args?.[0] || {};\n\n // open a new popup window in case config.urlCallback is not set\n //\n // note: it is opened before any async calls due to Safari restrictions\n // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061)\n let eagerDefaultPopup: Window | null = null;\n if (!config.urlCallback) {\n eagerDefaultPopup = openBrowserPopup(undefined);\n }\n\n // initialize a one-off realtime service\n const realtime = new RealtimeService(this.client);\n\n function cleanup() {\n eagerDefaultPopup?.close();\n realtime.unsubscribe();\n }\n\n const requestKeyOptions: SendOptions = {};\n const requestKey = config.requestKey\n if (requestKey) {\n requestKeyOptions.requestKey = requestKey;\n }\n\n return this.listAuthMethods(requestKeyOptions).then((authMethods) => {\n const provider = authMethods.authProviders.find(\n (p) => p.name === config.provider,\n );\n if (!provider) {\n throw new ClientResponseError(\n new Error(`Missing or invalid provider \"${config.provider}\".`),\n );\n }\n\n const redirectUrl = this.client.buildUrl(\"/api/oauth2-redirect\");\n\n // find the AbortController associated with the current request key (if any)\n const cancelController = requestKey ? this.client['cancelControllers']?.[requestKey] : undefined;\n if (cancelController) {\n cancelController.signal.onabort = () => {\n cleanup();\n }\n }\n\n return new Promise(async (resolve, reject) => {\n try {\n await realtime.subscribe(\"@oauth2\", async (e) => {\n const oldState = realtime.clientId;\n\n try {\n if (!e.state || oldState !== e.state) {\n throw new Error(\"State parameters don't match.\");\n }\n\n if (e.error || !e.code) {\n throw new Error(\n \"OAuth2 redirect error or missing code: \" + e.error,\n );\n }\n\n // clear the non SendOptions props\n const options = Object.assign({}, config);\n delete options.provider;\n delete options.scopes;\n delete options.createData;\n delete options.urlCallback;\n\n // reset the cancelController listener as it will be triggered by the next api call\n if (cancelController?.signal?.onabort) {\n cancelController.signal.onabort = null\n }\n\n const authData = await this.authWithOAuth2Code(\n provider.name,\n e.code,\n provider.codeVerifier,\n redirectUrl,\n config.createData,\n options,\n );\n\n resolve(authData);\n } catch (err) {\n reject(new ClientResponseError(err));\n }\n\n cleanup();\n });\n\n const replacements: { [key: string]: any } = {\n state: realtime.clientId,\n };\n if (config.scopes?.length) {\n replacements[\"scope\"] = config.scopes.join(\" \");\n }\n\n const url = this._replaceQueryParams(\n provider.authUrl + redirectUrl,\n replacements,\n );\n\n let urlCallback =\n config.urlCallback ||\n function (url: string) {\n if (eagerDefaultPopup) {\n eagerDefaultPopup.location.href = url;\n } else {\n // it could have been blocked due to its empty initial url,\n // try again...\n eagerDefaultPopup = openBrowserPopup(url);\n }\n };\n\n await urlCallback(url);\n } catch (err) {\n cleanup();\n reject(new ClientResponseError(err));\n }\n });\n }).catch((err) => {\n cleanup();\n throw err // rethrow\n }) as Promise>;\n }\n\n /**\n * Refreshes the current authenticated record instance and\n * returns a new token and record data.\n *\n * On success this method also automatically updates the client's AuthStore.\n *\n * @throws {ClientResponseError}\n */\n async authRefresh(options?: RecordOptions): Promise>;\n\n /**\n * @deprecated\n * Consider using authRefresh(options?).\n */\n async authRefresh(body?: any, query?: any): Promise>;\n\n async authRefresh(\n bodyOrOptions?: any,\n query?: any,\n ): Promise> {\n let options: any = {\n method: \"POST\",\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/auth-refresh\", options)\n .then((data) => this.authResponse(data));\n }\n\n /**\n * Sends auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async requestPasswordReset(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestPasswordReset(email, options?).\n */\n async requestPasswordReset(email: string, body?: any, query?: any): Promise;\n\n async requestPasswordReset(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record password reset request.\n *\n * @throws {ClientResponseError}\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmPasswordReset(passwordResetToken, password, passwordConfirm, options?).\n */\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmPasswordReset(\n passwordResetToken: string,\n password: string,\n passwordConfirm: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: passwordResetToken,\n password: password,\n passwordConfirm: passwordConfirm,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-password-reset\", options)\n .then(() => true);\n }\n\n /**\n * Sends auth record verification email request.\n *\n * @throws {ClientResponseError}\n */\n async requestVerification(email: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestVerification(email, options?).\n */\n async requestVerification(email: string, body?: any, query?: any): Promise;\n\n async requestVerification(\n email: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n email: email,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-verification\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record email verification request.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore.model.verified` will be updated to `true`.\n *\n * @throws {ClientResponseError}\n */\n async confirmVerification(\n verificationToken: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmVerification(verificationToken, options?).\n */\n async confirmVerification(\n verificationToken: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmVerification(\n verificationToken: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: verificationToken,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-verification\", options)\n .then(() => {\n // on success manually update the current auth record verified state\n const payload = getTokenPayload(verificationToken);\n const model = this.client.authStore.model;\n if (\n model &&\n !model.verified &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n model.verified = true;\n this.client.authStore.save(this.client.authStore.token, model);\n }\n\n return true;\n });\n }\n\n /**\n * Sends an email change request to the authenticated record model.\n *\n * @throws {ClientResponseError}\n */\n async requestEmailChange(newEmail: string, options?: CommonOptions): Promise;\n\n /**\n * @deprecated\n * Consider using requestEmailChange(newEmail, options?).\n */\n async requestEmailChange(newEmail: string, body?: any, query?: any): Promise;\n\n async requestEmailChange(\n newEmail: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n newEmail: newEmail,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/request-email-change\", options)\n .then(() => true);\n }\n\n /**\n * Confirms auth record's new email address.\n *\n * If the current `client.authStore.model` matches with the auth record from the token,\n * then on success the `client.authStore` will be cleared.\n *\n * @throws {ClientResponseError}\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n options?: CommonOptions,\n ): Promise;\n\n /**\n * @deprecated\n * Consider using confirmEmailChange(emailChangeToken, password, options?).\n */\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n body?: any,\n query?: any,\n ): Promise;\n\n async confirmEmailChange(\n emailChangeToken: string,\n password: string,\n bodyOrOptions?: any,\n query?: any,\n ): Promise {\n let options: any = {\n method: \"POST\",\n body: {\n token: emailChangeToken,\n password: password,\n },\n };\n\n options = normalizeLegacyOptionsArgs(\n \"This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).\",\n options,\n bodyOrOptions,\n query,\n );\n\n return this.client\n .send(this.baseCollectionPath + \"/confirm-email-change\", options)\n .then(() => {\n const payload = getTokenPayload(emailChangeToken);\n const model = this.client.authStore.model;\n if (\n model &&\n model.id === payload.id &&\n model.collectionId === payload.collectionId\n ) {\n this.client.authStore.clear();\n }\n\n return true;\n });\n }\n\n /**\n * Lists all linked external auth providers for the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async listExternalAuths(\n recordId: string,\n options?: CommonOptions,\n ): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\n this.baseCrudPath + \"/\" + encodeURIComponent(recordId) + \"/external-auths\",\n options,\n );\n }\n\n /**\n * Unlink a single external auth provider from the specified auth record.\n *\n * @throws {ClientResponseError}\n */\n async unlinkExternalAuth(\n recordId: string,\n provider: string,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(\n this.baseCrudPath +\n \"/\" +\n encodeURIComponent(recordId) +\n \"/external-auths/\" +\n encodeURIComponent(provider),\n options,\n )\n .then(() => true);\n }\n\n // ---------------------------------------------------------------\n\n // very rudimentary url query params replacement because at the moment\n // URL (and URLSearchParams) doesn't seem to be fully supported in React Native\n //\n // note: for details behind some of the decode/encode parsing check https://unixpapa.com/js/querystring.html\n private _replaceQueryParams(\n url: string,\n replacements: { [key: string]: any } = {},\n ): string {\n let urlPath = url;\n let query = \"\";\n\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex >= 0) {\n urlPath = url.substring(0, url.indexOf(\"?\"));\n query = url.substring(url.indexOf(\"?\") + 1);\n }\n\n const parsedParams: { [key: string]: string } = {};\n\n // parse the query parameters\n const rawParams = query.split(\"&\");\n for (const param of rawParams) {\n if (param == \"\") {\n continue;\n }\n\n const pair = param.split(\"=\");\n parsedParams[decodeURIComponent(pair[0].replace(/\\+/g, \" \"))] =\n decodeURIComponent((pair[1] || \"\").replace(/\\+/g, \" \"));\n }\n\n // apply the replacements\n for (let key in replacements) {\n if (!replacements.hasOwnProperty(key)) {\n continue;\n }\n\n if (replacements[key] == null) {\n delete parsedParams[key];\n } else {\n parsedParams[key] = replacements[key];\n }\n }\n\n // construct back the full query string\n query = \"\";\n for (let key in parsedParams) {\n if (!parsedParams.hasOwnProperty(key)) {\n continue;\n }\n\n if (query != \"\") {\n query += \"&\";\n }\n\n query +=\n encodeURIComponent(key.replace(/%20/g, \"+\")) +\n \"=\" +\n encodeURIComponent(parsedParams[key].replace(/%20/g, \"+\"));\n }\n\n return query != \"\" ? urlPath + \"?\" + query : urlPath;\n }\n}\n\nfunction openBrowserPopup(url?: string): Window | null {\n if (typeof window === \"undefined\" || !window?.open) {\n throw new ClientResponseError(\n new Error(\n `Not in a browser context - please pass a custom urlCallback function.`,\n ),\n );\n }\n\n let width = 1024;\n let height = 768;\n\n let windowWidth = window.innerWidth;\n let windowHeight = window.innerHeight;\n\n // normalize window size\n width = width > windowWidth ? windowWidth : width;\n height = height > windowHeight ? windowHeight : height;\n\n let left = windowWidth / 2 - width / 2;\n let top = windowHeight / 2 - height / 2;\n\n // note: we don't use the noopener and noreferrer attributes since\n // for some reason browser blocks such windows then url is undefined/blank\n return window.open(\n url,\n \"popup_window\",\n \"width=\" +\n width +\n \",height=\" +\n height +\n \",top=\" +\n top +\n \",left=\" +\n left +\n \",resizable,menubar=no\",\n );\n}\n","import { CrudService } from \"@/services/utils/CrudService\";\nimport { CollectionModel } from \"@/services/utils/dtos\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport class CollectionService extends CrudService {\n /**\n * @inheritdoc\n */\n get baseCrudPath(): string {\n return \"/api/collections\";\n }\n\n /**\n * Imports the provided collections.\n *\n * If `deleteMissing` is `true`, all local collections and schema fields,\n * that are not present in the imported configuration, WILL BE DELETED\n * (including their related records data)!\n *\n * @throws {ClientResponseError}\n */\n async import(\n collections: Array,\n deleteMissing: boolean = false,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"PUT\",\n body: {\n collections: collections,\n deleteMissing: deleteMissing,\n },\n },\n options,\n );\n\n return this.client.send(this.baseCrudPath + \"/import\", options).then(() => true);\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseService } from \"@/services/utils/BaseService\";\nimport { ListResult, LogModel } from \"@/services/utils/dtos\";\nimport { CommonOptions, ListOptions, LogStatsOptions } from \"@/services/utils/options\";\n\nexport interface HourlyStats {\n total: number;\n date: string;\n}\n\nexport class LogService extends BaseService {\n /**\n * Returns paginated logs list.\n *\n * @throws {ClientResponseError}\n */\n async getList(\n page = 1,\n perPage = 30,\n options?: ListOptions,\n ): Promise> {\n options = Object.assign({ method: \"GET\" }, options);\n\n options.query = Object.assign(\n {\n page: page,\n perPage: perPage,\n },\n options.query,\n );\n\n return this.client.send(\"/api/logs\", options);\n }\n\n /**\n * Returns a single log by its id.\n *\n * If `id` is empty it will throw a 404 error.\n *\n * @throws {ClientResponseError}\n */\n async getOne(id: string, options?: CommonOptions): Promise {\n if (!id) {\n throw new ClientResponseError({\n url: this.client.buildUrl(\"/api/logs/\"),\n status: 404,\n response: {\n code: 404,\n message: \"Missing required log id.\",\n data: {},\n },\n });\n }\n\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/\" + encodeURIComponent(id), options);\n }\n\n /**\n * Returns logs statistics.\n *\n * @throws {ClientResponseError}\n */\n async getStats(options?: LogStatsOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/logs/stats\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface HealthCheckResponse {\n code: number;\n message: string;\n data: { [key: string]: any };\n}\n\nexport class HealthService extends BaseService {\n /**\n * Checks the health status of the api.\n *\n * @throws {ClientResponseError}\n */\n async check(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/health\", options);\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions, FileOptions } from \"@/services/utils/options\";\n\nexport class FileService extends BaseService {\n /**\n * Builds and returns an absolute record file url for the provided filename.\n */\n getUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n if (\n !filename ||\n !record?.id ||\n !(record?.collectionId || record?.collectionName)\n ) {\n return \"\";\n }\n\n const parts = [];\n parts.push(\"api\");\n parts.push(\"files\");\n parts.push(encodeURIComponent(record.collectionId || record.collectionName));\n parts.push(encodeURIComponent(record.id));\n parts.push(encodeURIComponent(filename));\n\n let result = this.client.buildUrl(parts.join(\"/\"));\n\n if (Object.keys(queryParams).length) {\n // normalize the download query param for consistency with the Dart sdk\n if (queryParams.download === false) {\n delete queryParams.download;\n }\n\n const params = new URLSearchParams(queryParams);\n\n result += (result.includes(\"?\") ? \"&\" : \"?\") + params;\n }\n\n return result;\n }\n\n /**\n * Requests a new private file access token for the current auth model (admin or record).\n *\n * @throws {ClientResponseError}\n */\n async getToken(options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(\"/api/files/token\", options)\n .then((data) => data?.token || \"\");\n }\n}\n","import { BaseService } from \"@/services/utils/BaseService\";\nimport { CommonOptions } from \"@/services/utils/options\";\n\nexport interface BackupFileInfo {\n key: string;\n size: number;\n modified: string;\n}\n\nexport class BackupService extends BaseService {\n /**\n * Returns list with all available backup files.\n *\n * @throws {ClientResponseError}\n */\n async getFullList(options?: CommonOptions): Promise> {\n options = Object.assign(\n {\n method: \"GET\",\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options);\n }\n\n /**\n * Initializes a new backup.\n *\n * @throws {ClientResponseError}\n */\n async create(basename: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: {\n name: basename,\n },\n },\n options,\n );\n\n return this.client.send(\"/api/backups\", options).then(() => true);\n }\n\n /**\n * Uploads an existing backup file.\n *\n * Example:\n *\n * ```js\n * await pb.backups.upload({\n * file: new Blob([...]),\n * });\n * ```\n *\n * @throws {ClientResponseError}\n */\n async upload(\n bodyParams: { [key: string]: any } | FormData,\n options?: CommonOptions,\n ): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n body: bodyParams,\n },\n options,\n );\n\n return this.client.send(\"/api/backups/upload\", options).then(() => true);\n }\n\n /**\n * Deletes a single backup file.\n *\n * @throws {ClientResponseError}\n */\n async delete(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"DELETE\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}`, options)\n .then(() => true);\n }\n\n /**\n * Initializes an app data restore from an existing backup.\n *\n * @throws {ClientResponseError}\n */\n async restore(key: string, options?: CommonOptions): Promise {\n options = Object.assign(\n {\n method: \"POST\",\n },\n options,\n );\n\n return this.client\n .send(`/api/backups/${encodeURIComponent(key)}/restore`, options)\n .then(() => true);\n }\n\n /**\n * Builds a download url for a single existing backup using an\n * admin file token and the backup file key.\n *\n * The file token can be generated via `pb.files.getToken()`.\n */\n getDownloadUrl(token: string, key: string): string {\n return this.client.buildUrl(\n `/api/backups/${encodeURIComponent(key)}?token=${encodeURIComponent(token)}`,\n );\n }\n}\n","import { ClientResponseError } from \"@/ClientResponseError\";\nimport { BaseAuthStore } from \"@/stores/BaseAuthStore\";\nimport { LocalAuthStore } from \"@/stores/LocalAuthStore\";\nimport { SettingsService } from \"@/services/SettingsService\";\nimport { AdminService } from \"@/services/AdminService\";\nimport { RecordService } from \"@/services/RecordService\";\nimport { CollectionService } from \"@/services/CollectionService\";\nimport { LogService } from \"@/services/LogService\";\nimport { RealtimeService } from \"@/services/RealtimeService\";\nimport { HealthService } from \"@/services/HealthService\";\nimport { FileService } from \"@/services/FileService\";\nimport { BackupService } from \"@/services/BackupService\";\nimport { RecordModel } from \"@/services/utils/dtos\";\nimport {\n SendOptions,\n FileOptions,\n normalizeUnknownQueryParams,\n} from \"@/services/utils/options\";\n\nexport interface BeforeSendResult {\n [key: string]: any; // for backward compatibility\n url?: string;\n options?: { [key: string]: any };\n}\n\n/**\n * PocketBase JS Client.\n */\nexport default class Client {\n /**\n * The base PocketBase backend url address (eg. 'http://127.0.0.1.8090').\n */\n baseUrl: string;\n\n /**\n * Hook that get triggered right before sending the fetch request,\n * allowing you to inspect and modify the url and request options.\n *\n * For list of the possible options check https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n *\n * You can return a non-empty result object `{ url, options }` to replace the url and request options entirely.\n *\n * Example:\n * ```js\n * client.beforeSend = function (url, options) {\n * options.headers = Object.assign({}, options.headers, {\n * 'X-Custom-Header': 'example',\n * });\n *\n * return { url, options }\n * };\n * ```\n */\n beforeSend?: (\n url: string,\n options: SendOptions,\n ) => BeforeSendResult | Promise;\n\n /**\n * Hook that get triggered after successfully sending the fetch request,\n * allowing you to inspect/modify the response object and its parsed data.\n *\n * Returns the new Promise resolved `data` that will be returned to the client.\n *\n * Example:\n * ```js\n * client.afterSend = function (response, data) {\n * if (response.status != 200) {\n * throw new ClientResponseError({\n * url: response.url,\n * status: response.status,\n * response: { ... },\n * });\n * }\n *\n * return data;\n * };\n * ```\n */\n afterSend?: (response: Response, data: any) => any;\n\n /**\n * Optional language code (default to `en-US`) that will be sent\n * with the requests to the server as `Accept-Language` header.\n */\n lang: string;\n\n /**\n * A replaceable instance of the local auth store service.\n */\n authStore: BaseAuthStore;\n\n /**\n * An instance of the service that handles the **Settings APIs**.\n */\n readonly settings: SettingsService;\n\n /**\n * An instance of the service that handles the **Admin APIs**.\n */\n readonly admins: AdminService;\n\n /**\n * An instance of the service that handles the **Collection APIs**.\n */\n readonly collections: CollectionService;\n\n /**\n * An instance of the service that handles the **File APIs**.\n */\n readonly files: FileService;\n\n /**\n * An instance of the service that handles the **Log APIs**.\n */\n readonly logs: LogService;\n\n /**\n * An instance of the service that handles the **Realtime APIs**.\n */\n readonly realtime: RealtimeService;\n\n /**\n * An instance of the service that handles the **Health APIs**.\n */\n readonly health: HealthService;\n\n /**\n * An instance of the service that handles the **Backup APIs**.\n */\n readonly backups: BackupService;\n\n private cancelControllers: { [key: string]: AbortController } = {};\n private recordServices: { [key: string]: RecordService } = {};\n private enableAutoCancellation: boolean = true;\n\n constructor(baseUrl = \"/\", authStore?: BaseAuthStore | null, lang = \"en-US\") {\n this.baseUrl = baseUrl;\n this.lang = lang;\n this.authStore = authStore || new LocalAuthStore();\n\n // services\n this.admins = new AdminService(this);\n this.collections = new CollectionService(this);\n this.files = new FileService(this);\n this.logs = new LogService(this);\n this.settings = new SettingsService(this);\n this.realtime = new RealtimeService(this);\n this.health = new HealthService(this);\n this.backups = new BackupService(this);\n }\n\n /**\n * Returns the RecordService associated to the specified collection.\n *\n * @param {string} idOrName\n * @return {RecordService}\n */\n collection(idOrName: string): RecordService {\n if (!this.recordServices[idOrName]) {\n this.recordServices[idOrName] = new RecordService(this, idOrName);\n }\n\n return this.recordServices[idOrName];\n }\n\n /**\n * Globally enable or disable auto cancellation for pending duplicated requests.\n */\n autoCancellation(enable: boolean): Client {\n this.enableAutoCancellation = !!enable;\n\n return this;\n }\n\n /**\n * Cancels single request by its cancellation key.\n */\n cancelRequest(requestKey: string): Client {\n if (this.cancelControllers[requestKey]) {\n this.cancelControllers[requestKey].abort();\n delete this.cancelControllers[requestKey];\n }\n\n return this;\n }\n\n /**\n * Cancels all pending requests.\n */\n cancelAllRequests(): Client {\n for (let k in this.cancelControllers) {\n this.cancelControllers[k].abort();\n }\n\n this.cancelControllers = {};\n\n return this;\n }\n\n /**\n * Constructs a filter expression with placeholders populated from a parameters object.\n *\n * Placeholder parameters are defined with the `{:paramName}` notation.\n *\n * The following parameter values are supported:\n *\n * - `string` (_single quotes are autoescaped_)\n * - `number`\n * - `boolean`\n * - `Date` object (_stringified into the PocketBase datetime format_)\n * - `null`\n * - everything else is converted to a string using `JSON.stringify()`\n *\n * Example:\n *\n * ```js\n * pb.collection(\"example\").getFirstListItem(pb.filter(\n * 'title ~ {:title} && created >= {:created}',\n * { title: \"example\", created: new Date()}\n * ))\n * ```\n */\n filter(raw: string, params?: { [key: string]: any }): string {\n if (!params) {\n return raw;\n }\n\n for (let key in params) {\n let val = params[key];\n switch (typeof val) {\n case \"boolean\":\n case \"number\":\n val = \"\" + val;\n break;\n case \"string\":\n val = \"'\" + val.replace(/'/g, \"\\\\'\") + \"'\";\n break;\n default:\n if (val === null) {\n val = \"null\";\n } else if (val instanceof Date) {\n val = \"'\" + val.toISOString().replace(\"T\", \" \") + \"'\";\n } else {\n val = \"'\" + JSON.stringify(val).replace(/'/g, \"\\\\'\") + \"'\";\n }\n }\n raw = raw.replaceAll(\"{:\" + key + \"}\", val);\n }\n\n return raw;\n }\n\n /**\n * Legacy alias of `pb.files.getUrl()`.\n */\n getFileUrl(\n record: { [key: string]: any },\n filename: string,\n queryParams: FileOptions = {},\n ): string {\n return this.files.getUrl(record, filename, queryParams);\n }\n\n /**\n * Builds a full client url by safely concatenating the provided path.\n */\n buildUrl(path: string): string {\n let url = this.baseUrl;\n\n // construct an absolute base url if in a browser environment\n if (\n typeof window !== \"undefined\" &&\n !!window.location &&\n !url.startsWith(\"https://\") &&\n !url.startsWith(\"http://\")\n ) {\n url = window.location.origin?.endsWith(\"/\")\n ? window.location.origin.substring(0, window.location.origin.length - 1)\n : window.location.origin || \"\";\n\n if (!this.baseUrl.startsWith(\"/\")) {\n url += window.location.pathname || \"/\";\n url += url.endsWith(\"/\") ? \"\" : \"/\";\n }\n\n url += this.baseUrl;\n }\n\n // concatenate the path\n if (path) {\n url += url.endsWith(\"/\") ? \"\" : \"/\"; // append trailing slash if missing\n url += path.startsWith(\"/\") ? path.substring(1) : path;\n }\n\n return url;\n }\n\n /**\n * Sends an api http request.\n *\n * @throws {ClientResponseError}\n */\n async send(path: string, options: SendOptions): Promise {\n options = this.initSendOptions(path, options);\n\n // build url + path\n let url = this.buildUrl(path);\n\n if (this.beforeSend) {\n const result = Object.assign({}, await this.beforeSend(url, options));\n if (\n typeof result.url !== \"undefined\" ||\n typeof result.options !== \"undefined\"\n ) {\n url = result.url || url;\n options = result.options || options;\n } else if (Object.keys(result).length) {\n // legacy behavior\n options = result as SendOptions;\n console?.warn &&\n console.warn(\n \"Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`.\",\n );\n }\n }\n\n // serialize the query parameters\n if (typeof options.query !== \"undefined\") {\n const query = this.serializeQueryParams(options.query);\n if (query) {\n url += (url.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n delete options.query;\n }\n\n // ensures that the json body is serialized\n if (\n this.getHeader(options.headers, \"Content-Type\") == \"application/json\" &&\n options.body &&\n typeof options.body !== \"string\"\n ) {\n options.body = JSON.stringify(options.body);\n }\n\n const fetchFunc = options.fetch || fetch;\n\n // send the request\n return fetchFunc(url, options)\n .then(async (response) => {\n let data: any = {};\n\n try {\n data = await response.json();\n } catch (_) {\n // all api responses are expected to return json\n // with the exception of the realtime event and 204\n }\n\n if (this.afterSend) {\n data = await this.afterSend(response, data);\n }\n\n if (response.status >= 400) {\n throw new ClientResponseError({\n url: response.url,\n status: response.status,\n data: data,\n });\n }\n\n return data as T;\n })\n .catch((err) => {\n // wrap to normalize all errors\n throw new ClientResponseError(err);\n });\n }\n\n /**\n * Shallow copy the provided object and takes care to initialize\n * any options required to preserve the backward compatability.\n *\n * @param {SendOptions} options\n * @return {SendOptions}\n */\n private initSendOptions(path: string, options: SendOptions): SendOptions {\n options = Object.assign({ method: \"GET\" } as SendOptions, options);\n\n // auto convert the body to FormData, if needed\n options.body = this.convertToFormDataIfNeeded(options.body);\n\n // move unknown send options as query parameters\n normalizeUnknownQueryParams(options);\n\n // requestKey normalizations for backward-compatibility\n // ---\n options.query = Object.assign({}, options.params, options.query);\n if (typeof options.requestKey === \"undefined\") {\n if (options.$autoCancel === false || options.query.$autoCancel === false) {\n options.requestKey = null;\n } else if (options.$cancelKey || options.query.$cancelKey) {\n options.requestKey = options.$cancelKey || options.query.$cancelKey;\n }\n }\n // remove the deprecated special cancellation params from the other query params\n delete options.$autoCancel;\n delete options.query.$autoCancel;\n delete options.$cancelKey;\n delete options.query.$cancelKey;\n // ---\n\n // add the json header, if not explicitly set\n // (for FormData body the Content-Type header should be skipped since the boundary is autogenerated)\n if (\n this.getHeader(options.headers, \"Content-Type\") === null &&\n !this.isFormData(options.body)\n ) {\n options.headers = Object.assign({}, options.headers, {\n \"Content-Type\": \"application/json\",\n });\n }\n\n // add Accept-Language header, if not explicitly set\n if (this.getHeader(options.headers, \"Accept-Language\") === null) {\n options.headers = Object.assign({}, options.headers, {\n \"Accept-Language\": this.lang,\n });\n }\n\n // check if Authorization header can be added\n if (\n // has valid token\n this.authStore.token &&\n // auth header is not explicitly set\n this.getHeader(options.headers, \"Authorization\") === null\n ) {\n options.headers = Object.assign({}, options.headers, {\n Authorization: this.authStore.token,\n });\n }\n\n // handle auto cancelation for duplicated pending request\n if (this.enableAutoCancellation && options.requestKey !== null) {\n const requestKey = options.requestKey || (options.method || \"GET\") + path;\n\n delete options.requestKey;\n\n // cancel previous pending requests\n this.cancelRequest(requestKey);\n\n const controller = new AbortController();\n this.cancelControllers[requestKey] = controller;\n options.signal = controller.signal;\n }\n\n return options;\n }\n\n /**\n * Converts analyzes the provided body and converts it to FormData\n * in case a plain object with File/Blob values is used.\n */\n private convertToFormDataIfNeeded(body: any): any {\n if (\n typeof FormData === \"undefined\" ||\n typeof body === \"undefined\" ||\n typeof body !== \"object\" ||\n body === null ||\n this.isFormData(body) ||\n !this.hasBlobField(body)\n ) {\n return body;\n }\n\n const form = new FormData();\n\n for (const key in body) {\n const val = body[key];\n\n if (typeof val === \"object\" && !this.hasBlobField({ data: val })) {\n // send json-like values as jsonPayload to avoid the implicit string value normalization\n let payload: { [key: string]: any } = {};\n payload[key] = val;\n form.append(\"@jsonPayload\", JSON.stringify(payload));\n } else {\n // in case of mixed string and file/blob\n const normalizedVal = Array.isArray(val) ? val : [val];\n for (let v of normalizedVal) {\n form.append(key, v);\n }\n }\n }\n\n return form;\n }\n\n /**\n * Checks if the submitted body object has at least one Blob/File field.\n */\n private hasBlobField(body: { [key: string]: any }): boolean {\n for (const key in body) {\n const values = Array.isArray(body[key]) ? body[key] : [body[key]];\n for (const v of values) {\n if (\n (typeof Blob !== \"undefined\" && v instanceof Blob) ||\n (typeof File !== \"undefined\" && v instanceof File)\n ) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Extracts the header with the provided name in case-insensitive manner.\n * Returns `null` if no header matching the name is found.\n */\n private getHeader(\n headers: { [key: string]: string } | undefined,\n name: string,\n ): string | null {\n headers = headers || {};\n name = name.toLowerCase();\n\n for (let key in headers) {\n if (key.toLowerCase() == name) {\n return headers[key];\n }\n }\n\n return null;\n }\n\n /**\n * Loosely checks if the specified body is a FormData instance.\n */\n private isFormData(body: any): boolean {\n return (\n body &&\n // we are checking the constructor name because FormData\n // is not available natively in some environments and the\n // polyfill(s) may not be globally accessible\n (body.constructor.name === \"FormData\" ||\n // fallback to global FormData instance check\n // note: this is needed because the constructor.name could be different in case of\n // custom global FormData implementation, eg. React Native on Android/iOS\n (typeof FormData !== \"undefined\" && body instanceof FormData))\n );\n }\n\n /**\n * Serializes the provided query parameters into a query string.\n */\n private serializeQueryParams(params: { [key: string]: any }): string {\n const result: Array = [];\n for (const key in params) {\n if (params[key] === null) {\n // skip null query params\n continue;\n }\n\n const value = params[key];\n const encodedKey = encodeURIComponent(key);\n\n if (Array.isArray(value)) {\n // repeat array params\n for (const v of value) {\n result.push(encodedKey + \"=\" + encodeURIComponent(v));\n }\n } else if (value instanceof Date) {\n result.push(encodedKey + \"=\" + encodeURIComponent(value.toISOString()));\n } else if (typeof value !== null && typeof value === \"object\") {\n result.push(encodedKey + \"=\" + encodeURIComponent(JSON.stringify(value)));\n } else {\n result.push(encodedKey + \"=\" + encodeURIComponent(value));\n }\n }\n\n return result.join(\"&\");\n }\n}\n"],"names":["ClientResponseError","Error","constructor","errData","super","this","url","status","response","isAbort","originalError","Object","setPrototypeOf","prototype","data","DOMException","name","message","cause","includes","toJSON","fieldContentRegExp","cookieSerialize","val","options","opt","assign","encode","defaultEncode","test","TypeError","value","result","maxAge","isNaN","isFinite","Math","floor","domain","path","expires","isDate","toString","call","Date","valueOf","toUTCString","httpOnly","secure","priority","toLowerCase","sameSite","defaultDecode","indexOf","decodeURIComponent","encodeURIComponent","isReactNative","navigator","product","global","HermesInternal","atobPolyfill","getTokenPayload","token","encodedPayload","split","map","c","charCodeAt","slice","join","JSON","parse","e","isTokenExpired","expirationThreshold","payload","keys","length","exp","now","atob","input","str","String","replace","bs","buffer","bc","idx","output","charAt","fromCharCode","defaultCookieKey","BaseAuthStore","baseToken","baseModel","_onChangeCallbacks","model","isValid","isAdmin","type","isAuthRecord","save","triggerChange","clear","loadFromCookie","cookie","key","rawData","cookieParse","decode","index","eqIdx","endIdx","lastIndexOf","trim","undefined","_","Array","isArray","exportToCookie","defaultOptions","stringify","resultLength","Blob","size","id","email","extraProps","prop","onChange","callback","fireImmediately","push","i","splice","LocalAuthStore","storageKey","storageFallback","_bindStorageEvent","_storageGet","_storageSet","_storageRemove","window","localStorage","rawValue","getItem","normalizedVal","setItem","removeItem","addEventListener","BaseService","client","SettingsService","getAll","method","send","update","bodyParams","body","testS3","filesystem","then","testEmail","toEmail","emailTemplate","template","generateAppleClientSecret","clientId","teamId","keyId","privateKey","duration","CrudService","getFullList","batchOrqueryParams","_getFullList","batch","getList","page","perPage","query","baseCrudPath","responseData","items","item","getFirstListItem","filter","requestKey","skipTotal","code","getOne","buildUrl","create","batchSize","request","async","list","concat","normalizeLegacyOptionsArgs","legacyWarn","baseOptions","bodyOrOptions","hasQuery","console","warn","resetAutoRefresh","_resetAutoRefresh","AdminService","authStore","collectionId","delete","success","authResponse","admin","authWithPassword","password","identity","autoRefreshThreshold","autoRefresh","authData","registerAutoRefresh","threshold","refreshFunc","reauthenticateFunc","oldBeforeSend","beforeSend","oldModel","unsubStoreChange","newToken","sendOptions","oldToken","headers","authRefresh","bind","requestPasswordReset","confirmPasswordReset","resetToken","passwordConfirm","knownSendOptionsKeys","normalizeUnknownQueryParams","RealtimeService","eventSource","subscriptions","lastSentSubscriptions","maxConnectTimeout","reconnectAttempts","maxReconnectAttempts","Infinity","predefinedReconnectIntervals","pendingConnects","isConnected","subscribe","topic","serialized","listener","msgEvent","submitSubscriptions","connect","unsubscribeByTopicAndListener","unsubscribe","needToSubmit","subs","getSubscriptionsByTopic","hasSubscriptionListeners","removeEventListener","disconnect","unsubscribeByPrefix","keyPrefix","hasAtleastOneTopic","startsWith","exist","keyToCheck","addAllSubscriptionListeners","getNonEmptySubscriptionKeys","getSubscriptionsCancelKey","catch","err","removeAllSubscriptionListeners","Promise","resolve","reject","initConnect","clearTimeout","connectTimeoutId","setTimeout","connectErrorHandler","EventSource","onerror","lastEventId","retries","hasUnsentSubscriptions","p","reconnectTimeoutId","connectSubs","latestTopics","t","timeout","fromReconnect","cancelRequest","close","RecordService","collectionIdOrName","baseCollectionPath","realtime","batchOrOptions","params","collectionName","record","listAuthMethods","usernamePassword","emailPassword","authProviders","usernameOrEmail","authWithOAuth2Code","provider","codeVerifier","redirectUrl","createData","authWithOAuth2","args","config","eagerDefaultPopup","urlCallback","openBrowserPopup","cleanup","requestKeyOptions","authMethods","find","cancelController","signal","onabort","oldState","state","error","scopes","replacements","_replaceQueryParams","authUrl","location","href","passwordResetToken","requestVerification","confirmVerification","verificationToken","verified","requestEmailChange","newEmail","confirmEmailChange","emailChangeToken","listExternalAuths","recordId","unlinkExternalAuth","urlPath","substring","parsedParams","rawParams","param","pair","hasOwnProperty","open","width","height","windowWidth","innerWidth","windowHeight","innerHeight","left","top","CollectionService","import","collections","deleteMissing","LogService","getStats","HealthService","check","FileService","getUrl","filename","queryParams","parts","download","URLSearchParams","getToken","BackupService","basename","upload","restore","getDownloadUrl","Client","baseUrl","lang","cancelControllers","recordServices","enableAutoCancellation","admins","files","logs","settings","health","backups","collection","idOrName","autoCancellation","enable","abort","cancelAllRequests","k","raw","toISOString","replaceAll","getFileUrl","origin","endsWith","pathname","initSendOptions","serializeQueryParams","getHeader","fetch","json","afterSend","convertToFormDataIfNeeded","$autoCancel","$cancelKey","isFormData","Authorization","controller","AbortController","FormData","hasBlobField","form","v","append","values","File","encodedKey"],"mappings":"2OAIM,MAAOA,4BAA4BC,MAOrC,WAAAC,CAAYC,GACRC,MAAM,uBAPVC,KAAGC,IAAW,GACdD,KAAME,OAAW,EACjBF,KAAQG,SAA2B,GACnCH,KAAOI,SAAY,EACnBJ,KAAaK,cAAQ,KAOjBC,OAAOC,eAAeP,KAAML,oBAAoBa,WAEhC,OAAZV,GAAuC,iBAAZA,IAC3BE,KAAKC,IAA6B,iBAAhBH,EAAQG,IAAmBH,EAAQG,IAAM,GAC3DD,KAAKE,OAAmC,iBAAnBJ,EAAQI,OAAsBJ,EAAQI,OAAS,EACpEF,KAAKI,UAAYN,EAAQM,QACzBJ,KAAKK,cAAgBP,EAAQO,cAEJ,OAArBP,EAAQK,UAAiD,iBAArBL,EAAQK,SAC5CH,KAAKG,SAAWL,EAAQK,SACA,OAAjBL,EAAQW,MAAyC,iBAAjBX,EAAQW,KAC/CT,KAAKG,SAAWL,EAAQW,KAExBT,KAAKG,SAAW,IAInBH,KAAKK,eAAmBP,aAAmBH,sBAC5CK,KAAKK,cAAgBP,GAGG,oBAAjBY,cAAgCZ,aAAmBY,eAC1DV,KAAKI,SAAU,GAGnBJ,KAAKW,KAAO,uBAAyBX,KAAKE,OAC1CF,KAAKY,QAAUZ,KAAKG,UAAUS,QACzBZ,KAAKY,UACFZ,KAAKI,QACLJ,KAAKY,QACD,mHACGZ,KAAKK,eAAeQ,OAAOD,SAASE,SAAS,oBACpDd,KAAKY,QACD,qJAEJZ,KAAKY,QAAU,sDAG1B,CAKD,QAAIH,GACA,OAAOT,K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AAK,IAAI0D,KAAO6H,EACZ,GAAI7H,EAAI1D,eAAiBlC,EACrB,OAAOyN,EAAQ7H,GAIvB,OAAO,IACV,CAKO,UAAA8T,CAAW1Q,GACf,OACIA,IAI2B,aAA1BA,EAAK9J,YAAYc,MAIO,oBAAb8Z,UAA4B9Q,aAAgB8Q,SAE/D,CAKO,oBAAAZ,CAAqB/G,GACzB,MAAMnR,EAAwB,GAC9B,IAAK,MAAM4E,KAAOuM,EAAQ,CACtB,GAAoB,OAAhBA,EAAOvM,GAEP,SAGJ,MAAM7E,EAAQoR,EAAOvM,GACfyU,EAAa9X,mBAAmBqD,GAEtC,GAAIW,MAAMC,QAAQzF,GAEd,IAAK,MAAMkZ,KAAKlZ,EACZC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmB0X,SAE/ClZ,aAAiBa,KACxBZ,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBxB,EAAM4X,gBAChC,cAAV5X,GAAmC,iBAAVA,EACvCC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBgB,KAAKoD,UAAU5F,KAEjEC,EAAOsG,KAAK+S,EAAa,IAAM9X,mBAAmBxB,GAEzD,CAED,OAAOC,EAAOsC,KAAK,IACtB"} \ No newline at end of file diff --git a/package.json b/package.json index 070ce8d..b414358 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "0.21.3", + "version": "0.21.4", "name": "pocketbase", "description": "PocketBase JavaScript SDK", "author": "Gani Georgiev", diff --git a/src/services/RecordService.ts b/src/services/RecordService.ts index 6fad3f8..a401d10 100644 --- a/src/services/RecordService.ts +++ b/src/services/RecordService.ts @@ -482,17 +482,37 @@ export class RecordService extends CrudService { * }) * ``` * - * _Site-note_: when creating the OAuth2 app in the provider dashboard + * Note1: When creating the OAuth2 app in the provider dashboard * you have to configure `https://yourdomain.com/api/oauth2-redirect` * as redirect URL. * + * Note2: Safari may block the default `urlCallback` popup because + * it doesn't allow `window.open` calls as part of an `async` click functions. + * To workaround this you can either change your click handler to not be marked as `async` + * OR manually call `window.open` before your `async` function and use the + * window reference in your own custom `urlCallback` (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061). + * For example: + * ```js + * + * ... + * document.getElementById("btn").addEventListener("click", () => { + * pb.collection("users").authWithOAuth2({ + * provider: "gitlab", + * }).then((authData) => { + * console.log(authData) + * }).catch((err) => { + * console.log(err, err.originalError); + * }); + * }) + * ``` + * * @throws {ClientResponseError} */ async authWithOAuth2( options: OAuth2AuthConfig, ): Promise>; - async authWithOAuth2(...args: any): Promise> { + authWithOAuth2(...args: any): Promise> { // fallback to legacy format if (args.length > 1 || typeof args?.[0] === "string") { console.warn( @@ -511,106 +531,128 @@ export class RecordService extends CrudService { const config = args?.[0] || {}; - const authMethods = await this.listAuthMethods(); - - const provider = authMethods.authProviders.find( - (p) => p.name === config.provider, - ); - if (!provider) { - throw new ClientResponseError( - new Error(`Missing or invalid provider "${config.provider}".`), - ); - } - - const redirectUrl = this.client.buildUrl("/api/oauth2-redirect"); - - // initialize a one-off realtime service - const realtime = new RealtimeService(this.client); - // open a new popup window in case config.urlCallback is not set // - // note: it is opened before the async call due to Safari restrictions + // note: it is opened before any async calls due to Safari restrictions // (see https://github.com/pocketbase/pocketbase/discussions/2429#discussioncomment-5943061) let eagerDefaultPopup: Window | null = null; if (!config.urlCallback) { eagerDefaultPopup = openBrowserPopup(undefined); } + // initialize a one-off realtime service + const realtime = new RealtimeService(this.client); + function cleanup() { eagerDefaultPopup?.close(); realtime.unsubscribe(); } - return new Promise(async (resolve, reject) => { - try { - await realtime.subscribe("@oauth2", async (e) => { - const oldState = realtime.clientId; - - try { - if (!e.state || oldState !== e.state) { - throw new Error("State parameters don't match."); - } + const requestKeyOptions: SendOptions = {}; + const requestKey = config.requestKey + if (requestKey) { + requestKeyOptions.requestKey = requestKey; + } - if (e.error || !e.code) { - throw new Error( - "OAuth2 redirect error or missing code: " + e.error, - ); - } + return this.listAuthMethods(requestKeyOptions).then((authMethods) => { + const provider = authMethods.authProviders.find( + (p) => p.name === config.provider, + ); + if (!provider) { + throw new ClientResponseError( + new Error(`Missing or invalid provider "${config.provider}".`), + ); + } - // clear the non SendOptions props - const options = Object.assign({}, config); - delete options.provider; - delete options.scopes; - delete options.createData; - delete options.urlCallback; - - const authData = await this.authWithOAuth2Code( - provider.name, - e.code, - provider.codeVerifier, - redirectUrl, - config.createData, - options, - ); - - resolve(authData); - } catch (err) { - reject(new ClientResponseError(err)); - } + const redirectUrl = this.client.buildUrl("/api/oauth2-redirect"); + // find the AbortController associated with the current request key (if any) + const cancelController = requestKey ? this.client['cancelControllers']?.[requestKey] : undefined; + if (cancelController) { + cancelController.signal.onabort = () => { cleanup(); - }); - - const replacements: { [key: string]: any } = { - state: realtime.clientId, - }; - if (config.scopes?.length) { - replacements["scope"] = config.scopes.join(" "); } + } - const url = this._replaceQueryParams( - provider.authUrl + redirectUrl, - replacements, - ); + return new Promise(async (resolve, reject) => { + try { + await realtime.subscribe("@oauth2", async (e) => { + const oldState = realtime.clientId; + + try { + if (!e.state || oldState !== e.state) { + throw new Error("State parameters don't match."); + } + + if (e.error || !e.code) { + throw new Error( + "OAuth2 redirect error or missing code: " + e.error, + ); + } + + // clear the non SendOptions props + const options = Object.assign({}, config); + delete options.provider; + delete options.scopes; + delete options.createData; + delete options.urlCallback; + + // reset the cancelController listener as it will be triggered by the next api call + if (cancelController?.signal?.onabort) { + cancelController.signal.onabort = null + } + + const authData = await this.authWithOAuth2Code( + provider.name, + e.code, + provider.codeVerifier, + redirectUrl, + config.createData, + options, + ); - let urlCallback = - config.urlCallback || - function (url: string) { - if (eagerDefaultPopup) { - eagerDefaultPopup.location.href = url; - } else { - // it could have been blocked due to its empty initial url, - // try again... - eagerDefaultPopup = openBrowserPopup(url); + resolve(authData); + } catch (err) { + reject(new ClientResponseError(err)); } + + cleanup(); + }); + + const replacements: { [key: string]: any } = { + state: realtime.clientId, }; + if (config.scopes?.length) { + replacements["scope"] = config.scopes.join(" "); + } - await urlCallback(url); - } catch (err) { - cleanup(); - reject(new ClientResponseError(err)); - } - }); + const url = this._replaceQueryParams( + provider.authUrl + redirectUrl, + replacements, + ); + + let urlCallback = + config.urlCallback || + function (url: string) { + if (eagerDefaultPopup) { + eagerDefaultPopup.location.href = url; + } else { + // it could have been blocked due to its empty initial url, + // try again... + eagerDefaultPopup = openBrowserPopup(url); + } + }; + + await urlCallback(url); + } catch (err) { + cleanup(); + reject(new ClientResponseError(err)); + } + }); + }).catch((err) => { + cleanup(); + throw err // rethrow + }) as Promise>; } /**