@picobase_app/client 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,54 +1,982 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ 'use strict';
2
+
3
+ // node_modules/pocketbase/dist/pocketbase.es.mjs
4
+ var ClientResponseError = class _ClientResponseError extends Error {
5
+ constructor(e2) {
6
+ super("ClientResponseError"), this.url = "", this.status = 0, this.response = {}, this.isAbort = false, this.originalError = null, Object.setPrototypeOf(this, _ClientResponseError.prototype), null !== e2 && "object" == typeof e2 && (this.url = "string" == typeof e2.url ? e2.url : "", this.status = "number" == typeof e2.status ? e2.status : 0, this.isAbort = !!e2.isAbort, this.originalError = e2.originalError, null !== e2.response && "object" == typeof e2.response ? this.response = e2.response : null !== e2.data && "object" == typeof e2.data ? this.response = e2.data : this.response = {}), this.originalError || e2 instanceof _ClientResponseError || (this.originalError = e2), "undefined" != typeof DOMException && e2 instanceof DOMException && (this.isAbort = true), 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.");
7
+ }
8
+ get data() {
9
+ return this.response;
10
+ }
11
+ toJSON() {
12
+ return { ...this };
13
+ }
11
14
  };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ var e = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
16
+ function cookieParse(e2, t2) {
17
+ const s2 = {};
18
+ if ("string" != typeof e2) return s2;
19
+ const i2 = Object.assign({}, {}).decode || defaultDecode;
20
+ let n2 = 0;
21
+ for (; n2 < e2.length; ) {
22
+ const t3 = e2.indexOf("=", n2);
23
+ if (-1 === t3) break;
24
+ let r2 = e2.indexOf(";", n2);
25
+ if (-1 === r2) r2 = e2.length;
26
+ else if (r2 < t3) {
27
+ n2 = e2.lastIndexOf(";", t3 - 1) + 1;
28
+ continue;
29
+ }
30
+ const o = e2.slice(n2, t3).trim();
31
+ if (void 0 === s2[o]) {
32
+ let n3 = e2.slice(t3 + 1, r2).trim();
33
+ 34 === n3.charCodeAt(0) && (n3 = n3.slice(1, -1));
34
+ try {
35
+ s2[o] = i2(n3);
36
+ } catch (e3) {
37
+ s2[o] = n3;
38
+ }
39
+ }
40
+ n2 = r2 + 1;
41
+ }
42
+ return s2;
43
+ }
44
+ function cookieSerialize(t2, s2, i2) {
45
+ const n2 = Object.assign({}, i2 || {}), r2 = n2.encode || defaultEncode;
46
+ if (!e.test(t2)) throw new TypeError("argument name is invalid");
47
+ const o = r2(s2);
48
+ if (o && !e.test(o)) throw new TypeError("argument val is invalid");
49
+ let a = t2 + "=" + o;
50
+ if (null != n2.maxAge) {
51
+ const e2 = n2.maxAge - 0;
52
+ if (isNaN(e2) || !isFinite(e2)) throw new TypeError("option maxAge is invalid");
53
+ a += "; Max-Age=" + Math.floor(e2);
54
+ }
55
+ if (n2.domain) {
56
+ if (!e.test(n2.domain)) throw new TypeError("option domain is invalid");
57
+ a += "; Domain=" + n2.domain;
58
+ }
59
+ if (n2.path) {
60
+ if (!e.test(n2.path)) throw new TypeError("option path is invalid");
61
+ a += "; Path=" + n2.path;
62
+ }
63
+ if (n2.expires) {
64
+ if (!(function isDate(e2) {
65
+ return "[object Date]" === Object.prototype.toString.call(e2) || e2 instanceof Date;
66
+ })(n2.expires) || isNaN(n2.expires.valueOf())) throw new TypeError("option expires is invalid");
67
+ a += "; Expires=" + n2.expires.toUTCString();
68
+ }
69
+ if (n2.httpOnly && (a += "; HttpOnly"), n2.secure && (a += "; Secure"), n2.priority) {
70
+ switch ("string" == typeof n2.priority ? n2.priority.toLowerCase() : n2.priority) {
71
+ case "low":
72
+ a += "; Priority=Low";
73
+ break;
74
+ case "medium":
75
+ a += "; Priority=Medium";
76
+ break;
77
+ case "high":
78
+ a += "; Priority=High";
79
+ break;
80
+ default:
81
+ throw new TypeError("option priority is invalid");
82
+ }
83
+ }
84
+ if (n2.sameSite) {
85
+ switch ("string" == typeof n2.sameSite ? n2.sameSite.toLowerCase() : n2.sameSite) {
86
+ case true:
87
+ a += "; SameSite=Strict";
88
+ break;
89
+ case "lax":
90
+ a += "; SameSite=Lax";
91
+ break;
92
+ case "strict":
93
+ a += "; SameSite=Strict";
94
+ break;
95
+ case "none":
96
+ a += "; SameSite=None";
97
+ break;
98
+ default:
99
+ throw new TypeError("option sameSite is invalid");
100
+ }
101
+ }
102
+ return a;
103
+ }
104
+ function defaultDecode(e2) {
105
+ return -1 !== e2.indexOf("%") ? decodeURIComponent(e2) : e2;
106
+ }
107
+ function defaultEncode(e2) {
108
+ return encodeURIComponent(e2);
109
+ }
110
+ var t = "undefined" != typeof navigator && "ReactNative" === navigator.product || "undefined" != typeof global && global.HermesInternal;
111
+ var s;
112
+ function getTokenPayload(e2) {
113
+ if (e2) try {
114
+ const t2 = decodeURIComponent(s(e2.split(".")[1]).split("").map((function(e3) {
115
+ return "%" + ("00" + e3.charCodeAt(0).toString(16)).slice(-2);
116
+ })).join(""));
117
+ return JSON.parse(t2) || {};
118
+ } catch (e3) {
119
+ }
120
+ return {};
121
+ }
122
+ function isTokenExpired(e2, t2 = 0) {
123
+ let s2 = getTokenPayload(e2);
124
+ return !(Object.keys(s2).length > 0 && (!s2.exp || s2.exp - t2 > Date.now() / 1e3));
125
+ }
126
+ s = "function" != typeof atob || t ? (e2) => {
127
+ let t2 = String(e2).replace(/=+$/, "");
128
+ if (t2.length % 4 == 1) throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
129
+ for (var s2, i2, n2 = 0, r2 = 0, o = ""; i2 = t2.charAt(r2++); ~i2 && (s2 = n2 % 4 ? 64 * s2 + i2 : i2, n2++ % 4) ? o += String.fromCharCode(255 & s2 >> (-2 * n2 & 6)) : 0) i2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i2);
130
+ return o;
131
+ } : atob;
132
+ var i = "pb_auth";
133
+ var BaseAuthStore = class {
134
+ constructor() {
135
+ this.baseToken = "", this.baseModel = null, this._onChangeCallbacks = [];
136
+ }
137
+ get token() {
138
+ return this.baseToken;
139
+ }
140
+ get record() {
141
+ return this.baseModel;
142
+ }
143
+ get model() {
144
+ return this.baseModel;
145
+ }
146
+ get isValid() {
147
+ return !isTokenExpired(this.token);
148
+ }
149
+ get isSuperuser() {
150
+ let e2 = getTokenPayload(this.token);
151
+ return "auth" == e2.type && ("_superusers" == this.record?.collectionName || !this.record?.collectionName && "pbc_3142635823" == e2.collectionId);
152
+ }
153
+ get isAdmin() {
154
+ return console.warn("Please replace pb.authStore.isAdmin with pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName"), this.isSuperuser;
155
+ }
156
+ get isAuthRecord() {
157
+ return console.warn("Please replace pb.authStore.isAuthRecord with !pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName"), "auth" == getTokenPayload(this.token).type && !this.isSuperuser;
158
+ }
159
+ save(e2, t2) {
160
+ this.baseToken = e2 || "", this.baseModel = t2 || null, this.triggerChange();
161
+ }
162
+ clear() {
163
+ this.baseToken = "", this.baseModel = null, this.triggerChange();
164
+ }
165
+ loadFromCookie(e2, t2 = i) {
166
+ const s2 = cookieParse(e2 || "")[t2] || "";
167
+ let n2 = {};
168
+ try {
169
+ n2 = JSON.parse(s2), (null === typeof n2 || "object" != typeof n2 || Array.isArray(n2)) && (n2 = {});
170
+ } catch (e3) {
171
+ }
172
+ this.save(n2.token || "", n2.record || n2.model || null);
173
+ }
174
+ exportToCookie(e2, t2 = i) {
175
+ const s2 = { secure: true, sameSite: true, httpOnly: true, path: "/" }, n2 = getTokenPayload(this.token);
176
+ s2.expires = n2?.exp ? new Date(1e3 * n2.exp) : /* @__PURE__ */ new Date("1970-01-01"), e2 = Object.assign({}, s2, e2);
177
+ const r2 = { token: this.token, record: this.record ? JSON.parse(JSON.stringify(this.record)) : null };
178
+ let o = cookieSerialize(t2, JSON.stringify(r2), e2);
179
+ const a = "undefined" != typeof Blob ? new Blob([o]).size : o.length;
180
+ if (r2.record && a > 4096) {
181
+ r2.record = { id: r2.record?.id, email: r2.record?.email };
182
+ const s3 = ["collectionId", "collectionName", "verified"];
183
+ for (const e3 in this.record) s3.includes(e3) && (r2.record[e3] = this.record[e3]);
184
+ o = cookieSerialize(t2, JSON.stringify(r2), e2);
185
+ }
186
+ return o;
187
+ }
188
+ onChange(e2, t2 = false) {
189
+ return this._onChangeCallbacks.push(e2), t2 && e2(this.token, this.record), () => {
190
+ for (let t3 = this._onChangeCallbacks.length - 1; t3 >= 0; t3--) if (this._onChangeCallbacks[t3] == e2) return delete this._onChangeCallbacks[t3], void this._onChangeCallbacks.splice(t3, 1);
191
+ };
192
+ }
193
+ triggerChange() {
194
+ for (const e2 of this._onChangeCallbacks) e2 && e2(this.token, this.record);
195
+ }
196
+ };
197
+ var LocalAuthStore = class extends BaseAuthStore {
198
+ constructor(e2 = "pocketbase_auth") {
199
+ super(), this.storageFallback = {}, this.storageKey = e2, this._bindStorageEvent();
200
+ }
201
+ get token() {
202
+ return (this._storageGet(this.storageKey) || {}).token || "";
203
+ }
204
+ get record() {
205
+ const e2 = this._storageGet(this.storageKey) || {};
206
+ return e2.record || e2.model || null;
207
+ }
208
+ get model() {
209
+ return this.record;
210
+ }
211
+ save(e2, t2) {
212
+ this._storageSet(this.storageKey, { token: e2, record: t2 }), super.save(e2, t2);
213
+ }
214
+ clear() {
215
+ this._storageRemove(this.storageKey), super.clear();
216
+ }
217
+ _storageGet(e2) {
218
+ if ("undefined" != typeof window && window?.localStorage) {
219
+ const t2 = window.localStorage.getItem(e2) || "";
220
+ try {
221
+ return JSON.parse(t2);
222
+ } catch (e3) {
223
+ return t2;
224
+ }
225
+ }
226
+ return this.storageFallback[e2];
227
+ }
228
+ _storageSet(e2, t2) {
229
+ if ("undefined" != typeof window && window?.localStorage) {
230
+ let s2 = t2;
231
+ "string" != typeof t2 && (s2 = JSON.stringify(t2)), window.localStorage.setItem(e2, s2);
232
+ } else this.storageFallback[e2] = t2;
233
+ }
234
+ _storageRemove(e2) {
235
+ "undefined" != typeof window && window?.localStorage && window.localStorage?.removeItem(e2), delete this.storageFallback[e2];
236
+ }
237
+ _bindStorageEvent() {
238
+ "undefined" != typeof window && window?.localStorage && window.addEventListener && window.addEventListener("storage", ((e2) => {
239
+ if (e2.key != this.storageKey) return;
240
+ const t2 = this._storageGet(this.storageKey) || {};
241
+ super.save(t2.token || "", t2.record || t2.model || null);
242
+ }));
243
+ }
244
+ };
245
+ var BaseService = class {
246
+ constructor(e2) {
247
+ this.client = e2;
248
+ }
249
+ };
250
+ var SettingsService = class extends BaseService {
251
+ async getAll(e2) {
252
+ return e2 = Object.assign({ method: "GET" }, e2), this.client.send("/api/settings", e2);
253
+ }
254
+ async update(e2, t2) {
255
+ return t2 = Object.assign({ method: "PATCH", body: e2 }, t2), this.client.send("/api/settings", t2);
256
+ }
257
+ async testS3(e2 = "storage", t2) {
258
+ return t2 = Object.assign({ method: "POST", body: { filesystem: e2 } }, t2), this.client.send("/api/settings/test/s3", t2).then((() => true));
259
+ }
260
+ async testEmail(e2, t2, s2, i2) {
261
+ return i2 = Object.assign({ method: "POST", body: { email: t2, template: s2, collection: e2 } }, i2), this.client.send("/api/settings/test/email", i2).then((() => true));
262
+ }
263
+ async generateAppleClientSecret(e2, t2, s2, i2, n2, r2) {
264
+ return r2 = Object.assign({ method: "POST", body: { clientId: e2, teamId: t2, keyId: s2, privateKey: i2, duration: n2 } }, r2), this.client.send("/api/settings/apple/generate-client-secret", r2);
265
+ }
266
+ };
267
+ var n = ["requestKey", "$cancelKey", "$autoCancel", "fetch", "headers", "body", "query", "params", "cache", "credentials", "headers", "integrity", "keepalive", "method", "mode", "redirect", "referrer", "referrerPolicy", "signal", "window"];
268
+ function normalizeUnknownQueryParams(e2) {
269
+ if (e2) {
270
+ e2.query = e2.query || {};
271
+ for (let t2 in e2) n.includes(t2) || (e2.query[t2] = e2[t2], delete e2[t2]);
272
+ }
273
+ }
274
+ function serializeQueryParams(e2) {
275
+ const t2 = [];
276
+ for (const s2 in e2) {
277
+ const i2 = encodeURIComponent(s2), n2 = Array.isArray(e2[s2]) ? e2[s2] : [e2[s2]];
278
+ for (let e3 of n2) e3 = prepareQueryParamValue(e3), null !== e3 && t2.push(i2 + "=" + e3);
279
+ }
280
+ return t2.join("&");
281
+ }
282
+ function prepareQueryParamValue(e2) {
283
+ return null == e2 ? null : e2 instanceof Date ? encodeURIComponent(e2.toISOString().replace("T", " ")) : "object" == typeof e2 ? encodeURIComponent(JSON.stringify(e2)) : encodeURIComponent(e2);
284
+ }
285
+ var RealtimeService = class extends BaseService {
286
+ constructor() {
287
+ 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 = [];
288
+ }
289
+ get isConnected() {
290
+ return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;
291
+ }
292
+ async subscribe(e2, t2, s2) {
293
+ if (!e2) throw new Error("topic must be set.");
294
+ let i2 = e2;
295
+ if (s2) {
296
+ normalizeUnknownQueryParams(s2 = Object.assign({}, s2));
297
+ const e3 = "options=" + encodeURIComponent(JSON.stringify({ query: s2.query, headers: s2.headers }));
298
+ i2 += (i2.includes("?") ? "&" : "?") + e3;
299
+ }
300
+ const listener = function(e3) {
301
+ const s3 = e3;
302
+ let i3;
303
+ try {
304
+ i3 = JSON.parse(s3?.data);
305
+ } catch {
306
+ }
307
+ t2(i3 || {});
308
+ };
309
+ return this.subscriptions[i2] || (this.subscriptions[i2] = []), this.subscriptions[i2].push(listener), this.isConnected ? 1 === this.subscriptions[i2].length ? await this.submitSubscriptions() : this.eventSource?.addEventListener(i2, listener) : await this.connect(), async () => this.unsubscribeByTopicAndListener(e2, listener);
310
+ }
311
+ async unsubscribe(e2) {
312
+ let t2 = false;
313
+ if (e2) {
314
+ const s2 = this.getSubscriptionsByTopic(e2);
315
+ for (let e3 in s2) if (this.hasSubscriptionListeners(e3)) {
316
+ for (let t3 of this.subscriptions[e3]) this.eventSource?.removeEventListener(e3, t3);
317
+ delete this.subscriptions[e3], t2 || (t2 = true);
318
+ }
319
+ } else this.subscriptions = {};
320
+ this.hasSubscriptionListeners() ? t2 && await this.submitSubscriptions() : this.disconnect();
321
+ }
322
+ async unsubscribeByPrefix(e2) {
323
+ let t2 = false;
324
+ for (let s2 in this.subscriptions) if ((s2 + "?").startsWith(e2)) {
325
+ t2 = true;
326
+ for (let e3 of this.subscriptions[s2]) this.eventSource?.removeEventListener(s2, e3);
327
+ delete this.subscriptions[s2];
328
+ }
329
+ t2 && (this.hasSubscriptionListeners() ? await this.submitSubscriptions() : this.disconnect());
330
+ }
331
+ async unsubscribeByTopicAndListener(e2, t2) {
332
+ let s2 = false;
333
+ const i2 = this.getSubscriptionsByTopic(e2);
334
+ for (let e3 in i2) {
335
+ if (!Array.isArray(this.subscriptions[e3]) || !this.subscriptions[e3].length) continue;
336
+ let i3 = false;
337
+ for (let s3 = this.subscriptions[e3].length - 1; s3 >= 0; s3--) this.subscriptions[e3][s3] === t2 && (i3 = true, delete this.subscriptions[e3][s3], this.subscriptions[e3].splice(s3, 1), this.eventSource?.removeEventListener(e3, t2));
338
+ i3 && (this.subscriptions[e3].length || delete this.subscriptions[e3], s2 || this.hasSubscriptionListeners(e3) || (s2 = true));
339
+ }
340
+ this.hasSubscriptionListeners() ? s2 && await this.submitSubscriptions() : this.disconnect();
341
+ }
342
+ hasSubscriptionListeners(e2) {
343
+ if (this.subscriptions = this.subscriptions || {}, e2) return !!this.subscriptions[e2]?.length;
344
+ for (let e3 in this.subscriptions) if (this.subscriptions[e3]?.length) return true;
345
+ return false;
346
+ }
347
+ async submitSubscriptions() {
348
+ 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(((e2) => {
349
+ if (!e2?.isAbort) throw e2;
350
+ }));
351
+ }
352
+ getSubscriptionsCancelKey() {
353
+ return "realtime_" + this.clientId;
354
+ }
355
+ getSubscriptionsByTopic(e2) {
356
+ const t2 = {};
357
+ e2 = e2.includes("?") ? e2 : e2 + "?";
358
+ for (let s2 in this.subscriptions) (s2 + "?").startsWith(e2) && (t2[s2] = this.subscriptions[s2]);
359
+ return t2;
360
+ }
361
+ getNonEmptySubscriptionKeys() {
362
+ const e2 = [];
363
+ for (let t2 in this.subscriptions) this.subscriptions[t2].length && e2.push(t2);
364
+ return e2;
365
+ }
366
+ addAllSubscriptionListeners() {
367
+ if (this.eventSource) {
368
+ this.removeAllSubscriptionListeners();
369
+ for (let e2 in this.subscriptions) for (let t2 of this.subscriptions[e2]) this.eventSource.addEventListener(e2, t2);
370
+ }
371
+ }
372
+ removeAllSubscriptionListeners() {
373
+ if (this.eventSource) for (let e2 in this.subscriptions) for (let t2 of this.subscriptions[e2]) this.eventSource.removeEventListener(e2, t2);
374
+ }
375
+ async connect() {
376
+ if (!(this.reconnectAttempts > 0)) return new Promise(((e2, t2) => {
377
+ this.pendingConnects.push({ resolve: e2, reject: t2 }), this.pendingConnects.length > 1 || this.initConnect();
378
+ }));
379
+ }
380
+ initConnect() {
381
+ this.disconnect(true), clearTimeout(this.connectTimeoutId), this.connectTimeoutId = setTimeout((() => {
382
+ this.connectErrorHandler(new Error("EventSource connect took too long."));
383
+ }), this.maxConnectTimeout), this.eventSource = new EventSource(this.client.buildURL("/api/realtime")), this.eventSource.onerror = (e2) => {
384
+ this.connectErrorHandler(new Error("Failed to establish realtime connection."));
385
+ }, this.eventSource.addEventListener("PB_CONNECT", ((e2) => {
386
+ const t2 = e2;
387
+ this.clientId = t2?.lastEventId, this.submitSubscriptions().then((async () => {
388
+ let e3 = 3;
389
+ for (; this.hasUnsentSubscriptions() && e3 > 0; ) e3--, await this.submitSubscriptions();
390
+ })).then((() => {
391
+ for (let e3 of this.pendingConnects) e3.resolve();
392
+ this.pendingConnects = [], this.reconnectAttempts = 0, clearTimeout(this.reconnectTimeoutId), clearTimeout(this.connectTimeoutId);
393
+ const t3 = this.getSubscriptionsByTopic("PB_CONNECT");
394
+ for (let s2 in t3) for (let i2 of t3[s2]) i2(e2);
395
+ })).catch(((e3) => {
396
+ this.clientId = "", this.connectErrorHandler(e3);
397
+ }));
398
+ }));
399
+ }
400
+ hasUnsentSubscriptions() {
401
+ const e2 = this.getNonEmptySubscriptionKeys();
402
+ if (e2.length != this.lastSentSubscriptions.length) return true;
403
+ for (const t2 of e2) if (!this.lastSentSubscriptions.includes(t2)) return true;
404
+ return false;
405
+ }
406
+ connectErrorHandler(e2) {
407
+ if (clearTimeout(this.connectTimeoutId), clearTimeout(this.reconnectTimeoutId), !this.clientId && !this.reconnectAttempts || this.reconnectAttempts > this.maxReconnectAttempts) {
408
+ for (let t3 of this.pendingConnects) t3.reject(new ClientResponseError(e2));
409
+ return this.pendingConnects = [], void this.disconnect();
410
+ }
411
+ this.disconnect(true);
412
+ const t2 = this.predefinedReconnectIntervals[this.reconnectAttempts] || this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length - 1];
413
+ this.reconnectAttempts++, this.reconnectTimeoutId = setTimeout((() => {
414
+ this.initConnect();
415
+ }), t2);
416
+ }
417
+ disconnect(e2 = false) {
418
+ if (this.clientId && this.onDisconnect && this.onDisconnect(Object.keys(this.subscriptions)), clearTimeout(this.connectTimeoutId), clearTimeout(this.reconnectTimeoutId), this.removeAllSubscriptionListeners(), this.client.cancelRequest(this.getSubscriptionsCancelKey()), this.eventSource?.close(), this.eventSource = null, this.clientId = "", !e2) {
419
+ this.reconnectAttempts = 0;
420
+ for (let e3 of this.pendingConnects) e3.resolve();
421
+ this.pendingConnects = [];
422
+ }
423
+ }
424
+ };
425
+ var CrudService = class extends BaseService {
426
+ decode(e2) {
427
+ return e2;
428
+ }
429
+ async getFullList(e2, t2) {
430
+ if ("number" == typeof e2) return this._getFullList(e2, t2);
431
+ let s2 = 500;
432
+ return (t2 = Object.assign({}, e2, t2)).batch && (s2 = t2.batch, delete t2.batch), this._getFullList(s2, t2);
433
+ }
434
+ async getList(e2 = 1, t2 = 30, s2) {
435
+ return (s2 = Object.assign({ method: "GET" }, s2)).query = Object.assign({ page: e2, perPage: t2 }, s2.query), this.client.send(this.baseCrudPath, s2).then(((e3) => (e3.items = e3.items?.map(((e4) => this.decode(e4))) || [], e3)));
436
+ }
437
+ async getFirstListItem(e2, t2) {
438
+ return (t2 = Object.assign({ requestKey: "one_by_filter_" + this.baseCrudPath + "_" + e2 }, t2)).query = Object.assign({ filter: e2, skipTotal: 1 }, t2.query), this.getList(1, 1, t2).then(((e3) => {
439
+ if (!e3?.items?.length) throw new ClientResponseError({ status: 404, response: { code: 404, message: "The requested resource wasn't found.", data: {} } });
440
+ return e3.items[0];
441
+ }));
442
+ }
443
+ async getOne(e2, t2) {
444
+ if (!e2) throw new ClientResponseError({ url: this.client.buildURL(this.baseCrudPath + "/"), status: 404, response: { code: 404, message: "Missing required record id.", data: {} } });
445
+ return t2 = Object.assign({ method: "GET" }, t2), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e2), t2).then(((e3) => this.decode(e3)));
446
+ }
447
+ async create(e2, t2) {
448
+ return t2 = Object.assign({ method: "POST", body: e2 }, t2), this.client.send(this.baseCrudPath, t2).then(((e3) => this.decode(e3)));
449
+ }
450
+ async update(e2, t2, s2) {
451
+ return s2 = Object.assign({ method: "PATCH", body: t2 }, s2), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e2), s2).then(((e3) => this.decode(e3)));
452
+ }
453
+ async delete(e2, t2) {
454
+ return t2 = Object.assign({ method: "DELETE" }, t2), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e2), t2).then((() => true));
455
+ }
456
+ _getFullList(e2 = 500, t2) {
457
+ (t2 = t2 || {}).query = Object.assign({ skipTotal: 1 }, t2.query);
458
+ let s2 = [], request = async (i2) => this.getList(i2, e2 || 500, t2).then(((e3) => {
459
+ const t3 = e3.items;
460
+ return s2 = s2.concat(t3), t3.length == e3.perPage ? request(i2 + 1) : s2;
461
+ }));
462
+ return request(1);
463
+ }
464
+ };
465
+ function normalizeLegacyOptionsArgs(e2, t2, s2, i2) {
466
+ const n2 = void 0 !== i2;
467
+ return n2 || void 0 !== s2 ? n2 ? (console.warn(e2), t2.body = Object.assign({}, t2.body, s2), t2.query = Object.assign({}, t2.query, i2), t2) : Object.assign(t2, s2) : t2;
468
+ }
469
+ function resetAutoRefresh(e2) {
470
+ e2._resetAutoRefresh?.();
471
+ }
472
+ var RecordService = class extends CrudService {
473
+ constructor(e2, t2) {
474
+ super(e2), this.collectionIdOrName = t2;
475
+ }
476
+ get baseCrudPath() {
477
+ return this.baseCollectionPath + "/records";
478
+ }
479
+ get baseCollectionPath() {
480
+ return "/api/collections/" + encodeURIComponent(this.collectionIdOrName);
481
+ }
482
+ get isSuperusers() {
483
+ return "_superusers" == this.collectionIdOrName || "_pbc_2773867675" == this.collectionIdOrName;
484
+ }
485
+ async subscribe(e2, t2, s2) {
486
+ if (!e2) throw new Error("Missing topic.");
487
+ if (!t2) throw new Error("Missing subscription callback.");
488
+ return this.client.realtime.subscribe(this.collectionIdOrName + "/" + e2, t2, s2);
489
+ }
490
+ async unsubscribe(e2) {
491
+ return e2 ? this.client.realtime.unsubscribe(this.collectionIdOrName + "/" + e2) : this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);
492
+ }
493
+ async getFullList(e2, t2) {
494
+ if ("number" == typeof e2) return super.getFullList(e2, t2);
495
+ const s2 = Object.assign({}, e2, t2);
496
+ return super.getFullList(s2);
497
+ }
498
+ async getList(e2 = 1, t2 = 30, s2) {
499
+ return super.getList(e2, t2, s2);
500
+ }
501
+ async getFirstListItem(e2, t2) {
502
+ return super.getFirstListItem(e2, t2);
503
+ }
504
+ async getOne(e2, t2) {
505
+ return super.getOne(e2, t2);
506
+ }
507
+ async create(e2, t2) {
508
+ return super.create(e2, t2);
509
+ }
510
+ async update(e2, t2, s2) {
511
+ return super.update(e2, t2, s2).then(((e3) => {
512
+ if (this.client.authStore.record?.id === e3?.id && (this.client.authStore.record?.collectionId === this.collectionIdOrName || this.client.authStore.record?.collectionName === this.collectionIdOrName)) {
513
+ let t3 = Object.assign({}, this.client.authStore.record.expand), s3 = Object.assign({}, this.client.authStore.record, e3);
514
+ t3 && (s3.expand = Object.assign(t3, e3.expand)), this.client.authStore.save(this.client.authStore.token, s3);
515
+ }
516
+ return e3;
517
+ }));
518
+ }
519
+ async delete(e2, t2) {
520
+ return super.delete(e2, t2).then(((t3) => (!t3 || this.client.authStore.record?.id !== e2 || this.client.authStore.record?.collectionId !== this.collectionIdOrName && this.client.authStore.record?.collectionName !== this.collectionIdOrName || this.client.authStore.clear(), t3)));
521
+ }
522
+ authResponse(e2) {
523
+ const t2 = this.decode(e2?.record || {});
524
+ return this.client.authStore.save(e2?.token, t2), Object.assign({}, e2, { token: e2?.token || "", record: t2 });
525
+ }
526
+ async listAuthMethods(e2) {
527
+ return e2 = Object.assign({ method: "GET", fields: "mfa,otp,password,oauth2" }, e2), this.client.send(this.baseCollectionPath + "/auth-methods", e2);
528
+ }
529
+ async authWithPassword(e2, t2, s2) {
530
+ let i2;
531
+ s2 = Object.assign({ method: "POST", body: { identity: e2, password: t2 } }, s2), this.isSuperusers && (i2 = s2.autoRefreshThreshold, delete s2.autoRefreshThreshold, s2.autoRefresh || resetAutoRefresh(this.client));
532
+ let n2 = await this.client.send(this.baseCollectionPath + "/auth-with-password", s2);
533
+ return n2 = this.authResponse(n2), i2 && this.isSuperusers && (function registerAutoRefresh(e3, t3, s3, i3) {
534
+ resetAutoRefresh(e3);
535
+ const n3 = e3.beforeSend, r2 = e3.authStore.record, o = e3.authStore.onChange(((t4, s4) => {
536
+ (!t4 || s4?.id != r2?.id || (s4?.collectionId || r2?.collectionId) && s4?.collectionId != r2?.collectionId) && resetAutoRefresh(e3);
537
+ }));
538
+ e3._resetAutoRefresh = function() {
539
+ o(), e3.beforeSend = n3, delete e3._resetAutoRefresh;
540
+ }, e3.beforeSend = async (r3, o2) => {
541
+ const a = e3.authStore.token;
542
+ if (o2.query?.autoRefresh) return n3 ? n3(r3, o2) : { url: r3, sendOptions: o2 };
543
+ let c = e3.authStore.isValid;
544
+ if (c && isTokenExpired(e3.authStore.token, t3)) try {
545
+ await s3();
546
+ } catch (e4) {
547
+ c = false;
548
+ }
549
+ c || await i3();
550
+ const l = o2.headers || {};
551
+ for (let t4 in l) if ("authorization" == t4.toLowerCase() && a == l[t4] && e3.authStore.token) {
552
+ l[t4] = e3.authStore.token;
553
+ break;
554
+ }
555
+ return o2.headers = l, n3 ? n3(r3, o2) : { url: r3, sendOptions: o2 };
556
+ };
557
+ })(this.client, i2, (() => this.authRefresh({ autoRefresh: true })), (() => this.authWithPassword(e2, t2, Object.assign({ autoRefresh: true }, s2)))), n2;
558
+ }
559
+ async authWithOAuth2Code(e2, t2, s2, i2, n2, r2, o) {
560
+ let a = { method: "POST", body: { provider: e2, code: t2, codeVerifier: s2, redirectURL: i2, createData: n2 } };
561
+ 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, r2, o), this.client.send(this.baseCollectionPath + "/auth-with-oauth2", a).then(((e3) => this.authResponse(e3)));
562
+ }
563
+ authWithOAuth2(...e2) {
564
+ if (e2.length > 1 || "string" == typeof e2?.[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(e2?.[0] || "", e2?.[1] || "", e2?.[2] || "", e2?.[3] || "", e2?.[4] || {}, e2?.[5] || {}, e2?.[6] || {});
565
+ const t2 = e2?.[0] || {};
566
+ let s2 = null;
567
+ t2.urlCallback || (s2 = openBrowserPopup(void 0));
568
+ const i2 = new RealtimeService(this.client);
569
+ function cleanup() {
570
+ s2?.close(), i2.unsubscribe();
571
+ }
572
+ const n2 = {}, r2 = t2.requestKey;
573
+ return r2 && (n2.requestKey = r2), this.listAuthMethods(n2).then(((e3) => {
574
+ const n3 = e3.oauth2.providers.find(((e4) => e4.name === t2.provider));
575
+ if (!n3) throw new ClientResponseError(new Error(`Missing or invalid provider "${t2.provider}".`));
576
+ const o = this.client.buildURL("/api/oauth2-redirect"), a = r2 ? this.client.cancelControllers?.[r2] : void 0;
577
+ return a && (a.signal.onabort = () => {
578
+ cleanup();
579
+ }), new Promise((async (e4, r3) => {
580
+ try {
581
+ await i2.subscribe("@oauth2", (async (s3) => {
582
+ const c2 = i2.clientId;
583
+ try {
584
+ if (!s3.state || c2 !== s3.state) throw new Error("State parameters don't match.");
585
+ if (s3.error || !s3.code) throw new Error("OAuth2 redirect error or missing code: " + s3.error);
586
+ const i3 = Object.assign({}, t2);
587
+ delete i3.provider, delete i3.scopes, delete i3.createData, delete i3.urlCallback, a?.signal?.onabort && (a.signal.onabort = null);
588
+ const r4 = await this.authWithOAuth2Code(n3.name, s3.code, n3.codeVerifier, o, t2.createData, i3);
589
+ e4(r4);
590
+ } catch (e5) {
591
+ r3(new ClientResponseError(e5));
592
+ }
593
+ cleanup();
594
+ }));
595
+ const c = { state: i2.clientId };
596
+ t2.scopes?.length && (c.scope = t2.scopes.join(" "));
597
+ const l = this._replaceQueryParams(n3.authURL + o, c);
598
+ let h = t2.urlCallback || function(e5) {
599
+ s2 ? s2.location.href = e5 : s2 = openBrowserPopup(e5);
600
+ };
601
+ await h(l);
602
+ } catch (e5) {
603
+ cleanup(), r3(new ClientResponseError(e5));
604
+ }
605
+ }));
606
+ })).catch(((e3) => {
607
+ throw cleanup(), e3;
608
+ }));
609
+ }
610
+ async authRefresh(e2, t2) {
611
+ let s2 = { method: "POST" };
612
+ return s2 = normalizeLegacyOptionsArgs("This form of authRefresh(body?, query?) is deprecated. Consider replacing it with authRefresh(options?).", s2, e2, t2), this.client.send(this.baseCollectionPath + "/auth-refresh", s2).then(((e3) => this.authResponse(e3)));
613
+ }
614
+ async requestPasswordReset(e2, t2, s2) {
615
+ let i2 = { method: "POST", body: { email: e2 } };
616
+ return i2 = normalizeLegacyOptionsArgs("This form of requestPasswordReset(email, body?, query?) is deprecated. Consider replacing it with requestPasswordReset(email, options?).", i2, t2, s2), this.client.send(this.baseCollectionPath + "/request-password-reset", i2).then((() => true));
617
+ }
618
+ async confirmPasswordReset(e2, t2, s2, i2, n2) {
619
+ let r2 = { method: "POST", body: { token: e2, password: t2, passwordConfirm: s2 } };
620
+ return r2 = normalizeLegacyOptionsArgs("This form of confirmPasswordReset(token, password, passwordConfirm, body?, query?) is deprecated. Consider replacing it with confirmPasswordReset(token, password, passwordConfirm, options?).", r2, i2, n2), this.client.send(this.baseCollectionPath + "/confirm-password-reset", r2).then((() => true));
621
+ }
622
+ async requestVerification(e2, t2, s2) {
623
+ let i2 = { method: "POST", body: { email: e2 } };
624
+ return i2 = normalizeLegacyOptionsArgs("This form of requestVerification(email, body?, query?) is deprecated. Consider replacing it with requestVerification(email, options?).", i2, t2, s2), this.client.send(this.baseCollectionPath + "/request-verification", i2).then((() => true));
625
+ }
626
+ async confirmVerification(e2, t2, s2) {
627
+ let i2 = { method: "POST", body: { token: e2 } };
628
+ return i2 = normalizeLegacyOptionsArgs("This form of confirmVerification(token, body?, query?) is deprecated. Consider replacing it with confirmVerification(token, options?).", i2, t2, s2), this.client.send(this.baseCollectionPath + "/confirm-verification", i2).then((() => {
629
+ const t3 = getTokenPayload(e2), s3 = this.client.authStore.record;
630
+ return s3 && !s3.verified && s3.id === t3.id && s3.collectionId === t3.collectionId && (s3.verified = true, this.client.authStore.save(this.client.authStore.token, s3)), true;
631
+ }));
632
+ }
633
+ async requestEmailChange(e2, t2, s2) {
634
+ let i2 = { method: "POST", body: { newEmail: e2 } };
635
+ return i2 = normalizeLegacyOptionsArgs("This form of requestEmailChange(newEmail, body?, query?) is deprecated. Consider replacing it with requestEmailChange(newEmail, options?).", i2, t2, s2), this.client.send(this.baseCollectionPath + "/request-email-change", i2).then((() => true));
636
+ }
637
+ async confirmEmailChange(e2, t2, s2, i2) {
638
+ let n2 = { method: "POST", body: { token: e2, password: t2 } };
639
+ return n2 = normalizeLegacyOptionsArgs("This form of confirmEmailChange(token, password, body?, query?) is deprecated. Consider replacing it with confirmEmailChange(token, password, options?).", n2, s2, i2), this.client.send(this.baseCollectionPath + "/confirm-email-change", n2).then((() => {
640
+ const t3 = getTokenPayload(e2), s3 = this.client.authStore.record;
641
+ return s3 && s3.id === t3.id && s3.collectionId === t3.collectionId && this.client.authStore.clear(), true;
642
+ }));
643
+ }
644
+ async listExternalAuths(e2, t2) {
645
+ return this.client.collection("_externalAuths").getFullList(Object.assign({}, t2, { filter: this.client.filter("recordRef = {:id}", { id: e2 }) }));
646
+ }
647
+ async unlinkExternalAuth(e2, t2, s2) {
648
+ const i2 = await this.client.collection("_externalAuths").getFirstListItem(this.client.filter("recordRef = {:recordId} && provider = {:provider}", { recordId: e2, provider: t2 }));
649
+ return this.client.collection("_externalAuths").delete(i2.id, s2).then((() => true));
650
+ }
651
+ async requestOTP(e2, t2) {
652
+ return t2 = Object.assign({ method: "POST", body: { email: e2 } }, t2), this.client.send(this.baseCollectionPath + "/request-otp", t2);
653
+ }
654
+ async authWithOTP(e2, t2, s2) {
655
+ return s2 = Object.assign({ method: "POST", body: { otpId: e2, password: t2 } }, s2), this.client.send(this.baseCollectionPath + "/auth-with-otp", s2).then(((e3) => this.authResponse(e3)));
656
+ }
657
+ async impersonate(e2, t2, s2) {
658
+ (s2 = Object.assign({ method: "POST", body: { duration: t2 } }, s2)).headers = s2.headers || {}, s2.headers.Authorization || (s2.headers.Authorization = this.client.authStore.token);
659
+ const i2 = new Client(this.client.baseURL, new BaseAuthStore(), this.client.lang), n2 = await i2.send(this.baseCollectionPath + "/impersonate/" + encodeURIComponent(e2), s2);
660
+ return i2.authStore.save(n2?.token, this.decode(n2?.record || {})), i2;
661
+ }
662
+ _replaceQueryParams(e2, t2 = {}) {
663
+ let s2 = e2, i2 = "";
664
+ e2.indexOf("?") >= 0 && (s2 = e2.substring(0, e2.indexOf("?")), i2 = e2.substring(e2.indexOf("?") + 1));
665
+ const n2 = {}, r2 = i2.split("&");
666
+ for (const e3 of r2) {
667
+ if ("" == e3) continue;
668
+ const t3 = e3.split("=");
669
+ n2[decodeURIComponent(t3[0].replace(/\+/g, " "))] = decodeURIComponent((t3[1] || "").replace(/\+/g, " "));
670
+ }
671
+ for (let e3 in t2) t2.hasOwnProperty(e3) && (null == t2[e3] ? delete n2[e3] : n2[e3] = t2[e3]);
672
+ i2 = "";
673
+ for (let e3 in n2) n2.hasOwnProperty(e3) && ("" != i2 && (i2 += "&"), i2 += encodeURIComponent(e3.replace(/%20/g, "+")) + "=" + encodeURIComponent(n2[e3].replace(/%20/g, "+")));
674
+ return "" != i2 ? s2 + "?" + i2 : s2;
675
+ }
676
+ };
677
+ function openBrowserPopup(e2) {
678
+ if ("undefined" == typeof window || !window?.open) throw new ClientResponseError(new Error("Not in a browser context - please pass a custom urlCallback function."));
679
+ let t2 = 1024, s2 = 768, i2 = window.innerWidth, n2 = window.innerHeight;
680
+ t2 = t2 > i2 ? i2 : t2, s2 = s2 > n2 ? n2 : s2;
681
+ let r2 = i2 / 2 - t2 / 2, o = n2 / 2 - s2 / 2;
682
+ return window.open(e2, "popup_window", "width=" + t2 + ",height=" + s2 + ",top=" + o + ",left=" + r2 + ",resizable,menubar=no");
683
+ }
684
+ var CollectionService = class extends CrudService {
685
+ get baseCrudPath() {
686
+ return "/api/collections";
687
+ }
688
+ async import(e2, t2 = false, s2) {
689
+ return s2 = Object.assign({ method: "PUT", body: { collections: e2, deleteMissing: t2 } }, s2), this.client.send(this.baseCrudPath + "/import", s2).then((() => true));
690
+ }
691
+ async getScaffolds(e2) {
692
+ return e2 = Object.assign({ method: "GET" }, e2), this.client.send(this.baseCrudPath + "/meta/scaffolds", e2);
693
+ }
694
+ async truncate(e2, t2) {
695
+ return t2 = Object.assign({ method: "DELETE" }, t2), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e2) + "/truncate", t2).then((() => true));
696
+ }
697
+ };
698
+ var LogService = class extends BaseService {
699
+ async getList(e2 = 1, t2 = 30, s2) {
700
+ return (s2 = Object.assign({ method: "GET" }, s2)).query = Object.assign({ page: e2, perPage: t2 }, s2.query), this.client.send("/api/logs", s2);
701
+ }
702
+ async getOne(e2, t2) {
703
+ if (!e2) throw new ClientResponseError({ url: this.client.buildURL("/api/logs/"), status: 404, response: { code: 404, message: "Missing required log id.", data: {} } });
704
+ return t2 = Object.assign({ method: "GET" }, t2), this.client.send("/api/logs/" + encodeURIComponent(e2), t2);
705
+ }
706
+ async getStats(e2) {
707
+ return e2 = Object.assign({ method: "GET" }, e2), this.client.send("/api/logs/stats", e2);
708
+ }
709
+ };
710
+ var HealthService = class extends BaseService {
711
+ async check(e2) {
712
+ return e2 = Object.assign({ method: "GET" }, e2), this.client.send("/api/health", e2);
713
+ }
714
+ };
715
+ var FileService = class extends BaseService {
716
+ getUrl(e2, t2, s2 = {}) {
717
+ return console.warn("Please replace pb.files.getUrl() with pb.files.getURL()"), this.getURL(e2, t2, s2);
718
+ }
719
+ getURL(e2, t2, s2 = {}) {
720
+ if (!t2 || !e2?.id || !e2?.collectionId && !e2?.collectionName) return "";
721
+ const i2 = [];
722
+ i2.push("api"), i2.push("files"), i2.push(encodeURIComponent(e2.collectionId || e2.collectionName)), i2.push(encodeURIComponent(e2.id)), i2.push(encodeURIComponent(t2));
723
+ let n2 = this.client.buildURL(i2.join("/"));
724
+ if (Object.keys(s2).length) {
725
+ false === s2.download && delete s2.download;
726
+ const e3 = new URLSearchParams(s2);
727
+ n2 += (n2.includes("?") ? "&" : "?") + e3;
728
+ }
729
+ return n2;
730
+ }
731
+ async getToken(e2) {
732
+ return e2 = Object.assign({ method: "POST" }, e2), this.client.send("/api/files/token", e2).then(((e3) => e3?.token || ""));
733
+ }
734
+ };
735
+ var BackupService = class extends BaseService {
736
+ async getFullList(e2) {
737
+ return e2 = Object.assign({ method: "GET" }, e2), this.client.send("/api/backups", e2);
738
+ }
739
+ async create(e2, t2) {
740
+ return t2 = Object.assign({ method: "POST", body: { name: e2 } }, t2), this.client.send("/api/backups", t2).then((() => true));
741
+ }
742
+ async upload(e2, t2) {
743
+ return t2 = Object.assign({ method: "POST", body: e2 }, t2), this.client.send("/api/backups/upload", t2).then((() => true));
744
+ }
745
+ async delete(e2, t2) {
746
+ return t2 = Object.assign({ method: "DELETE" }, t2), this.client.send(`/api/backups/${encodeURIComponent(e2)}`, t2).then((() => true));
747
+ }
748
+ async restore(e2, t2) {
749
+ return t2 = Object.assign({ method: "POST" }, t2), this.client.send(`/api/backups/${encodeURIComponent(e2)}/restore`, t2).then((() => true));
750
+ }
751
+ getDownloadUrl(e2, t2) {
752
+ return console.warn("Please replace pb.backups.getDownloadUrl() with pb.backups.getDownloadURL()"), this.getDownloadURL(e2, t2);
753
+ }
754
+ getDownloadURL(e2, t2) {
755
+ return this.client.buildURL(`/api/backups/${encodeURIComponent(t2)}?token=${encodeURIComponent(e2)}`);
756
+ }
757
+ };
758
+ var CronService = class extends BaseService {
759
+ async getFullList(e2) {
760
+ return e2 = Object.assign({ method: "GET" }, e2), this.client.send("/api/crons", e2);
761
+ }
762
+ async run(e2, t2) {
763
+ return t2 = Object.assign({ method: "POST" }, t2), this.client.send(`/api/crons/${encodeURIComponent(e2)}`, t2).then((() => true));
764
+ }
765
+ };
766
+ function isFile(e2) {
767
+ return "undefined" != typeof Blob && e2 instanceof Blob || "undefined" != typeof File && e2 instanceof File || null !== e2 && "object" == typeof e2 && e2.uri && ("undefined" != typeof navigator && "ReactNative" === navigator.product || "undefined" != typeof global && global.HermesInternal);
768
+ }
769
+ function isFormData(e2) {
770
+ return e2 && ("FormData" === e2.constructor.name || "undefined" != typeof FormData && e2 instanceof FormData);
771
+ }
772
+ function hasFileField(e2) {
773
+ for (const t2 in e2) {
774
+ const s2 = Array.isArray(e2[t2]) ? e2[t2] : [e2[t2]];
775
+ for (const e3 of s2) if (isFile(e3)) return true;
776
+ }
777
+ return false;
778
+ }
779
+ var r = /^[\-\.\d]+$/;
780
+ function inferFormDataValue(e2) {
781
+ if ("string" != typeof e2) return e2;
782
+ if ("true" == e2) return true;
783
+ if ("false" == e2) return false;
784
+ if (("-" === e2[0] || e2[0] >= "0" && e2[0] <= "9") && r.test(e2)) {
785
+ let t2 = +e2;
786
+ if ("" + t2 === e2) return t2;
787
+ }
788
+ return e2;
789
+ }
790
+ var BatchService = class extends BaseService {
791
+ constructor() {
792
+ super(...arguments), this.requests = [], this.subs = {};
793
+ }
794
+ collection(e2) {
795
+ return this.subs[e2] || (this.subs[e2] = new SubBatchService(this.requests, e2)), this.subs[e2];
796
+ }
797
+ async send(e2) {
798
+ const t2 = new FormData(), s2 = [];
799
+ for (let e3 = 0; e3 < this.requests.length; e3++) {
800
+ const i2 = this.requests[e3];
801
+ if (s2.push({ method: i2.method, url: i2.url, headers: i2.headers, body: i2.json }), i2.files) for (let s3 in i2.files) {
802
+ const n2 = i2.files[s3] || [];
803
+ for (let i3 of n2) t2.append("requests." + e3 + "." + s3, i3);
804
+ }
805
+ }
806
+ return t2.append("@jsonPayload", JSON.stringify({ requests: s2 })), e2 = Object.assign({ method: "POST", body: t2 }, e2), this.client.send("/api/batch", e2);
807
+ }
808
+ };
809
+ var SubBatchService = class {
810
+ constructor(e2, t2) {
811
+ this.requests = [], this.requests = e2, this.collectionIdOrName = t2;
812
+ }
813
+ upsert(e2, t2) {
814
+ t2 = Object.assign({ body: e2 || {} }, t2);
815
+ const s2 = { method: "PUT", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records" };
816
+ this.prepareRequest(s2, t2), this.requests.push(s2);
817
+ }
818
+ create(e2, t2) {
819
+ t2 = Object.assign({ body: e2 || {} }, t2);
820
+ const s2 = { method: "POST", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records" };
821
+ this.prepareRequest(s2, t2), this.requests.push(s2);
822
+ }
823
+ update(e2, t2, s2) {
824
+ s2 = Object.assign({ body: t2 || {} }, s2);
825
+ const i2 = { method: "PATCH", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records/" + encodeURIComponent(e2) };
826
+ this.prepareRequest(i2, s2), this.requests.push(i2);
827
+ }
828
+ delete(e2, t2) {
829
+ t2 = Object.assign({}, t2);
830
+ const s2 = { method: "DELETE", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records/" + encodeURIComponent(e2) };
831
+ this.prepareRequest(s2, t2), this.requests.push(s2);
832
+ }
833
+ prepareRequest(e2, t2) {
834
+ if (normalizeUnknownQueryParams(t2), e2.headers = t2.headers, e2.json = {}, e2.files = {}, void 0 !== t2.query) {
835
+ const s3 = serializeQueryParams(t2.query);
836
+ s3 && (e2.url += (e2.url.includes("?") ? "&" : "?") + s3);
837
+ }
838
+ let s2 = t2.body;
839
+ isFormData(s2) && (s2 = (function convertFormDataToObject(e3) {
840
+ let t3 = {};
841
+ return e3.forEach(((e4, s3) => {
842
+ if ("@jsonPayload" === s3 && "string" == typeof e4) try {
843
+ let s4 = JSON.parse(e4);
844
+ Object.assign(t3, s4);
845
+ } catch (e5) {
846
+ console.warn("@jsonPayload error:", e5);
847
+ }
848
+ else void 0 !== t3[s3] ? (Array.isArray(t3[s3]) || (t3[s3] = [t3[s3]]), t3[s3].push(inferFormDataValue(e4))) : t3[s3] = inferFormDataValue(e4);
849
+ })), t3;
850
+ })(s2));
851
+ for (const t3 in s2) {
852
+ const i2 = s2[t3];
853
+ if (isFile(i2)) e2.files[t3] = e2.files[t3] || [], e2.files[t3].push(i2);
854
+ else if (Array.isArray(i2)) {
855
+ const s3 = [], n2 = [];
856
+ for (const e3 of i2) isFile(e3) ? s3.push(e3) : n2.push(e3);
857
+ if (s3.length > 0 && s3.length == i2.length) {
858
+ e2.files[t3] = e2.files[t3] || [];
859
+ for (let i3 of s3) e2.files[t3].push(i3);
860
+ } else if (e2.json[t3] = n2, s3.length > 0) {
861
+ let i3 = t3;
862
+ t3.startsWith("+") || t3.endsWith("+") || (i3 += "+"), e2.files[i3] = e2.files[i3] || [];
863
+ for (let t4 of s3) e2.files[i3].push(t4);
864
+ }
865
+ } else e2.json[t3] = i2;
866
+ }
867
+ }
868
+ };
869
+ var Client = class {
870
+ get baseUrl() {
871
+ return this.baseURL;
872
+ }
873
+ set baseUrl(e2) {
874
+ this.baseURL = e2;
875
+ }
876
+ constructor(e2 = "/", t2, s2 = "en-US") {
877
+ this.cancelControllers = {}, this.recordServices = {}, this.enableAutoCancellation = true, this.baseURL = e2, this.lang = s2, t2 ? this.authStore = t2 : "undefined" != typeof window && window.Deno ? this.authStore = new BaseAuthStore() : this.authStore = new LocalAuthStore(), 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), this.crons = new CronService(this);
878
+ }
879
+ get admins() {
880
+ return this.collection("_superusers");
881
+ }
882
+ createBatch() {
883
+ return new BatchService(this);
884
+ }
885
+ collection(e2) {
886
+ return this.recordServices[e2] || (this.recordServices[e2] = new RecordService(this, e2)), this.recordServices[e2];
887
+ }
888
+ autoCancellation(e2) {
889
+ return this.enableAutoCancellation = !!e2, this;
890
+ }
891
+ cancelRequest(e2) {
892
+ return this.cancelControllers[e2] && (this.cancelControllers[e2].abort(), delete this.cancelControllers[e2]), this;
893
+ }
894
+ cancelAllRequests() {
895
+ for (let e2 in this.cancelControllers) this.cancelControllers[e2].abort();
896
+ return this.cancelControllers = {}, this;
897
+ }
898
+ filter(e2, t2) {
899
+ if (!t2) return e2;
900
+ for (let s2 in t2) {
901
+ let i2 = t2[s2];
902
+ switch (typeof i2) {
903
+ case "boolean":
904
+ case "number":
905
+ i2 = "" + i2;
906
+ break;
907
+ case "string":
908
+ i2 = "'" + i2.replace(/'/g, "\\'") + "'";
909
+ break;
910
+ default:
911
+ i2 = null === i2 ? "null" : i2 instanceof Date ? "'" + i2.toISOString().replace("T", " ") + "'" : "'" + JSON.stringify(i2).replace(/'/g, "\\'") + "'";
912
+ }
913
+ e2 = e2.replaceAll("{:" + s2 + "}", i2);
914
+ }
915
+ return e2;
916
+ }
917
+ getFileUrl(e2, t2, s2 = {}) {
918
+ return console.warn("Please replace pb.getFileUrl() with pb.files.getURL()"), this.files.getURL(e2, t2, s2);
919
+ }
920
+ buildUrl(e2) {
921
+ return console.warn("Please replace pb.buildUrl() with pb.buildURL()"), this.buildURL(e2);
922
+ }
923
+ buildURL(e2) {
924
+ let t2 = this.baseURL;
925
+ return "undefined" == typeof window || !window.location || t2.startsWith("https://") || t2.startsWith("http://") || (t2 = window.location.origin?.endsWith("/") ? window.location.origin.substring(0, window.location.origin.length - 1) : window.location.origin || "", this.baseURL.startsWith("/") || (t2 += window.location.pathname || "/", t2 += t2.endsWith("/") ? "" : "/"), t2 += this.baseURL), e2 && (t2 += t2.endsWith("/") ? "" : "/", t2 += e2.startsWith("/") ? e2.substring(1) : e2), t2;
926
+ }
927
+ async send(e2, t2) {
928
+ t2 = this.initSendOptions(e2, t2);
929
+ let s2 = this.buildURL(e2);
930
+ if (this.beforeSend) {
931
+ const e3 = Object.assign({}, await this.beforeSend(s2, t2));
932
+ void 0 !== e3.url || void 0 !== e3.options ? (s2 = e3.url || s2, t2 = e3.options || t2) : Object.keys(e3).length && (t2 = e3, console?.warn && console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."));
933
+ }
934
+ if (void 0 !== t2.query) {
935
+ const e3 = serializeQueryParams(t2.query);
936
+ e3 && (s2 += (s2.includes("?") ? "&" : "?") + e3), delete t2.query;
937
+ }
938
+ "application/json" == this.getHeader(t2.headers, "Content-Type") && t2.body && "string" != typeof t2.body && (t2.body = JSON.stringify(t2.body));
939
+ return (t2.fetch || fetch)(s2, t2).then((async (e3) => {
940
+ let s3 = {};
941
+ try {
942
+ s3 = await e3.json();
943
+ } catch (e4) {
944
+ }
945
+ if (this.afterSend && (s3 = await this.afterSend(e3, s3, t2)), e3.status >= 400) throw new ClientResponseError({ url: e3.url, status: e3.status, data: s3 });
946
+ return s3;
947
+ })).catch(((e3) => {
948
+ throw new ClientResponseError(e3);
949
+ }));
950
+ }
951
+ initSendOptions(e2, t2) {
952
+ if ((t2 = Object.assign({ method: "GET" }, t2)).body = (function convertToFormDataIfNeeded(e3) {
953
+ if ("undefined" == typeof FormData || void 0 === e3 || "object" != typeof e3 || null === e3 || isFormData(e3) || !hasFileField(e3)) return e3;
954
+ const t3 = new FormData();
955
+ for (const s2 in e3) {
956
+ const i2 = e3[s2];
957
+ if ("object" != typeof i2 || hasFileField({ data: i2 })) {
958
+ const e4 = Array.isArray(i2) ? i2 : [i2];
959
+ for (let i3 of e4) t3.append(s2, i3);
960
+ } else {
961
+ let e4 = {};
962
+ e4[s2] = i2, t3.append("@jsonPayload", JSON.stringify(e4));
963
+ }
964
+ }
965
+ return t3;
966
+ })(t2.body), normalizeUnknownQueryParams(t2), t2.query = Object.assign({}, t2.params, t2.query), void 0 === t2.requestKey && (false === t2.$autoCancel || false === t2.query.$autoCancel ? t2.requestKey = null : (t2.$cancelKey || t2.query.$cancelKey) && (t2.requestKey = t2.$cancelKey || t2.query.$cancelKey)), delete t2.$autoCancel, delete t2.query.$autoCancel, delete t2.$cancelKey, delete t2.query.$cancelKey, null !== this.getHeader(t2.headers, "Content-Type") || isFormData(t2.body) || (t2.headers = Object.assign({}, t2.headers, { "Content-Type": "application/json" })), null === this.getHeader(t2.headers, "Accept-Language") && (t2.headers = Object.assign({}, t2.headers, { "Accept-Language": this.lang })), this.authStore.token && null === this.getHeader(t2.headers, "Authorization") && (t2.headers = Object.assign({}, t2.headers, { Authorization: this.authStore.token })), this.enableAutoCancellation && null !== t2.requestKey) {
967
+ const s2 = t2.requestKey || (t2.method || "GET") + e2;
968
+ delete t2.requestKey, this.cancelRequest(s2);
969
+ const i2 = new AbortController();
970
+ this.cancelControllers[s2] = i2, t2.signal = i2.signal;
971
+ }
972
+ return t2;
973
+ }
974
+ getHeader(e2, t2) {
975
+ e2 = e2 || {}, t2 = t2.toLowerCase();
976
+ for (let s2 in e2) if (s2.toLowerCase() == t2) return e2[s2];
977
+ return null;
17
978
  }
18
- return to;
19
979
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- AuthorizationError: () => AuthorizationError,
34
- CollectionNotFoundError: () => CollectionNotFoundError,
35
- ConfigurationError: () => ConfigurationError,
36
- InstanceUnavailableError: () => InstanceUnavailableError,
37
- PicoBaseAuth: () => PicoBaseAuth,
38
- PicoBaseClient: () => PicoBaseClient,
39
- PicoBaseCollection: () => PicoBaseCollection,
40
- PicoBaseError: () => PicoBaseError,
41
- PicoBaseRealtime: () => PicoBaseRealtime,
42
- PicoBaseStorage: () => PicoBaseStorage,
43
- RecordNotFoundError: () => RecordNotFoundError,
44
- RequestError: () => RequestError,
45
- RpcError: () => RpcError,
46
- createClient: () => createClient
47
- });
48
- module.exports = __toCommonJS(index_exports);
49
-
50
- // src/client.ts
51
- var import_pocketbase = __toESM(require("pocketbase"));
52
980
 
53
981
  // src/auth.ts
54
982
  var PicoBaseAuth = class {
@@ -75,7 +1003,7 @@ var PicoBaseAuth = class {
75
1003
  */
76
1004
  async signUp(options) {
77
1005
  const { email, password, passwordConfirm, ...rest } = options;
78
- const record = await this.pb.collection(this._collection).create({
1006
+ await this.pb.collection(this._collection).create({
79
1007
  email,
80
1008
  password,
81
1009
  passwordConfirm: passwordConfirm ?? password,
@@ -394,10 +1322,10 @@ var PicoBaseError = class extends Error {
394
1322
  }
395
1323
  /** Formatted error string including fix suggestion. */
396
1324
  toString() {
397
- let s = `${this.name} [${this.code}]: ${this.message}`;
398
- if (this.fix) s += `
1325
+ let s2 = `${this.name} [${this.code}]: ${this.message}`;
1326
+ if (this.fix) s2 += `
399
1327
  Fix: ${this.fix}`;
400
- return s;
1328
+ return s2;
401
1329
  }
402
1330
  };
403
1331
  var InstanceUnavailableError = class extends PicoBaseError {
@@ -534,7 +1462,7 @@ var PicoBaseClient = class {
534
1462
  this.apiKey = apiKey;
535
1463
  this.options = { ...DEFAULT_OPTIONS, ...options };
536
1464
  const baseUrl = url.replace(/\/+$/, "");
537
- this.pb = new import_pocketbase.default(baseUrl);
1465
+ this.pb = new Client(baseUrl);
538
1466
  this.pb.autoCancellation(false);
539
1467
  if (this.options.lang) {
540
1468
  this.pb.lang = this.options.lang;
@@ -682,20 +1610,20 @@ function createClient(urlOrOptions, apiKeyOrUndefined, options) {
682
1610
  }
683
1611
  return new PicoBaseClient(urlOrOptions, apiKeyOrUndefined, options);
684
1612
  }
685
- // Annotate the CommonJS export names for ESM import in node:
686
- 0 && (module.exports = {
687
- AuthorizationError,
688
- CollectionNotFoundError,
689
- ConfigurationError,
690
- InstanceUnavailableError,
691
- PicoBaseAuth,
692
- PicoBaseClient,
693
- PicoBaseCollection,
694
- PicoBaseError,
695
- PicoBaseRealtime,
696
- PicoBaseStorage,
697
- RecordNotFoundError,
698
- RequestError,
699
- RpcError,
700
- createClient
701
- });
1613
+
1614
+ exports.AuthorizationError = AuthorizationError;
1615
+ exports.CollectionNotFoundError = CollectionNotFoundError;
1616
+ exports.ConfigurationError = ConfigurationError;
1617
+ exports.InstanceUnavailableError = InstanceUnavailableError;
1618
+ exports.PicoBaseAuth = PicoBaseAuth;
1619
+ exports.PicoBaseClient = PicoBaseClient;
1620
+ exports.PicoBaseCollection = PicoBaseCollection;
1621
+ exports.PicoBaseError = PicoBaseError;
1622
+ exports.PicoBaseRealtime = PicoBaseRealtime;
1623
+ exports.PicoBaseStorage = PicoBaseStorage;
1624
+ exports.RecordNotFoundError = RecordNotFoundError;
1625
+ exports.RequestError = RequestError;
1626
+ exports.RpcError = RpcError;
1627
+ exports.createClient = createClient;
1628
+ //# sourceMappingURL=index.js.map
1629
+ //# sourceMappingURL=index.js.map