@cartive/js-sdk 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ import { AddressesRecord, CartItemsResponseWithRelations, CartsResponseWithRelations, Collections, OrderItemsResponseWithRelations, OrdersResponse, OrdersViewResponseWithRelations, ProductCollectionsResponseWithRelations, ProductsViewResponseWithRelations, TypedPocketBase } from '@cartive/lib/types';
2
+ import { FileOptions, ListResult, RecordListOptions, RecordOptions } from 'pocketbase';
3
+ import { Config } from './types';
4
+ export declare class Cartive {
5
+ private client;
6
+ product: Product;
7
+ collection: Collection;
8
+ cart: Cart;
9
+ checkout: Checkout;
10
+ payment: Payment;
11
+ order: Order;
12
+ auth: Auth;
13
+ constructor(config: Config);
14
+ getFileURL(record: {
15
+ id: string;
16
+ collectionName: Collections;
17
+ }, fileName: string, queryParams?: FileOptions): string;
18
+ }
19
+ declare abstract class CartiveResource {
20
+ protected readonly client: TypedPocketBase;
21
+ protected readonly config: Config;
22
+ protected constructor(client: TypedPocketBase, config: Config);
23
+ protected businessFilter(): string;
24
+ protected buildFilter(...filters: (string | undefined)[]): string;
25
+ protected getBusiness(): Promise<import('@cartive/lib/types').BusinessesResponse<unknown>>;
26
+ }
27
+ declare class Product extends CartiveResource {
28
+ constructor(client: TypedPocketBase, config: Config);
29
+ getList: ({ page, limit, options, }: {
30
+ page?: number | undefined;
31
+ limit?: number | undefined;
32
+ options?: RecordListOptions | undefined;
33
+ }) => Promise<ListResult<ProductsViewResponseWithRelations>>;
34
+ getByHandle: ({ handle, options, }: {
35
+ handle: string;
36
+ options?: RecordListOptions;
37
+ }) => Promise<ProductsViewResponseWithRelations>;
38
+ }
39
+ declare class Collection extends CartiveResource {
40
+ constructor(client: TypedPocketBase, config: Config);
41
+ getList: ({ page, limit, options, }: {
42
+ page?: number | undefined;
43
+ limit?: number | undefined;
44
+ options?: RecordListOptions | undefined;
45
+ }) => Promise<ListResult<ProductCollectionsResponseWithRelations>>;
46
+ getByHandle: ({ handle, options, }: {
47
+ handle: string;
48
+ options?: RecordListOptions;
49
+ }) => Promise<ProductCollectionsResponseWithRelations>;
50
+ }
51
+ declare class Cart extends CartiveResource {
52
+ constructor(client: TypedPocketBase, config: Config);
53
+ create: () => Promise<import('@cartive/lib/types').CartsResponse<unknown>>;
54
+ getById: ({ id, options, }: {
55
+ id: string;
56
+ options?: RecordOptions;
57
+ }) => Promise<CartsResponseWithRelations>;
58
+ getCartItems: ({ cartId, options, }: {
59
+ cartId: string;
60
+ options?: RecordListOptions;
61
+ }) => Promise<CartItemsResponseWithRelations[]>;
62
+ addToCart: (data: {
63
+ quantity: number;
64
+ variant: string;
65
+ product: string;
66
+ cart: string;
67
+ }) => Promise<import('@cartive/lib/types').CartItemsResponse<unknown>>;
68
+ updateItem: (data: {
69
+ cartItemId: string;
70
+ quantity: number;
71
+ }) => Promise<import('@cartive/lib/types').CartItemsResponse<unknown>>;
72
+ removeItem: (data: {
73
+ cartItemId: string;
74
+ }) => Promise<boolean>;
75
+ complete: (data: {
76
+ cartId: string;
77
+ }) => Promise<OrdersResponse>;
78
+ saveCartAddress(data: {
79
+ cartId: string;
80
+ email: string;
81
+ shippingAddress: Partial<AddressesRecord>;
82
+ billingAddress?: Partial<AddressesRecord>;
83
+ billingSameAsShipping: boolean;
84
+ }): Promise<any>;
85
+ }
86
+ declare class Checkout extends CartiveResource {
87
+ constructor(client: TypedPocketBase, config: Config);
88
+ }
89
+ declare class Payment extends CartiveResource {
90
+ constructor(client: TypedPocketBase, config: Config);
91
+ initialize(data: {
92
+ orderId: string;
93
+ }): Promise<{
94
+ access_code: string;
95
+ reference: string;
96
+ authorization_url: string;
97
+ }>;
98
+ verify(data: {
99
+ reference: string;
100
+ }): Promise<{
101
+ status: string;
102
+ amount: number;
103
+ reference: string;
104
+ paid_at: string;
105
+ }>;
106
+ }
107
+ declare class Order extends CartiveResource {
108
+ constructor(client: TypedPocketBase, config: Config);
109
+ getList({ page, limit, options, }: {
110
+ page?: number | undefined;
111
+ limit?: number | undefined;
112
+ options?: RecordListOptions | undefined;
113
+ }): Promise<ListResult<OrdersResponse<unknown>>>;
114
+ getById({ id, options }: {
115
+ id: string;
116
+ options?: RecordOptions;
117
+ }): Promise<OrdersViewResponseWithRelations>;
118
+ getOrderItems({ id, options, }: {
119
+ id: string;
120
+ options?: RecordOptions;
121
+ }): Promise<OrderItemsResponseWithRelations[]>;
122
+ }
123
+ declare class Auth extends CartiveResource {
124
+ constructor(client: TypedPocketBase, config: Config);
125
+ refresh(): Promise<{
126
+ customer: import('@cartive/lib/types').CustomersViewResponse<unknown>;
127
+ record: import('@cartive/lib/types').CustomersResponse<unknown>;
128
+ token: string;
129
+ meta?: {
130
+ [key: string]: any;
131
+ };
132
+ } | null>;
133
+ requestOTP(data: {
134
+ email: string;
135
+ }): Promise<import('pocketbase').OTPResponse>;
136
+ authWithOTP(data: {
137
+ otpId: string;
138
+ code: string;
139
+ }): Promise<import('pocketbase').RecordAuthResponse<import('@cartive/lib/types').CustomersResponse<unknown>>>;
140
+ logout(): Promise<void>;
141
+ }
142
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,1221 @@
1
+ var J = Object.defineProperty;
2
+ var z = (o, e, t) => e in o ? J(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var u = (o, e, t) => z(o, typeof e != "symbol" ? e + "" : e, t);
4
+ const d = {
5
+ Businesses: "businesses",
6
+ CartItems: "cartItems",
7
+ Carts: "carts",
8
+ Customers: "customers",
9
+ CustomersView: "customersView",
10
+ OrderItems: "orderItems",
11
+ Orders: "orders",
12
+ OrdersView: "ordersView",
13
+ ProductCollections: "productCollections",
14
+ ProductsView: "productsView"
15
+ };
16
+ class f extends Error {
17
+ constructor(e) {
18
+ var t, s, i, n;
19
+ super("ClientResponseError"), this.url = "", this.status = 0, this.response = {}, this.isAbort = !1, this.originalError = null, Object.setPrototypeOf(this, f.prototype), e !== null && typeof e == "object" && (this.url = typeof e.url == "string" ? e.url : "", this.status = typeof e.status == "number" ? e.status : 0, this.isAbort = !!e.isAbort, this.originalError = e.originalError, e.response !== null && typeof e.response == "object" ? this.response = e.response : e.data !== null && typeof e.data == "object" ? this.response = e.data : this.response = {}), this.originalError || e instanceof f || (this.originalError = e), typeof DOMException < "u" && e instanceof DOMException && (this.isAbort = !0), this.name = "ClientResponseError " + this.status, this.message = (t = this.response) == null ? void 0 : t.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." : (n = (i = (s = this.originalError) == null ? void 0 : s.cause) == null ? void 0 : i.message) != null && n.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.");
20
+ }
21
+ get data() {
22
+ return this.response;
23
+ }
24
+ toJSON() {
25
+ return { ...this };
26
+ }
27
+ }
28
+ const L = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
29
+ function Q(o, e) {
30
+ const t = {};
31
+ if (typeof o != "string") return t;
32
+ const s = Object.assign({}, {}).decode || Y;
33
+ let i = 0;
34
+ for (; i < o.length; ) {
35
+ const n = o.indexOf("=", i);
36
+ if (n === -1) break;
37
+ let r = o.indexOf(";", i);
38
+ if (r === -1) r = o.length;
39
+ else if (r < n) {
40
+ i = o.lastIndexOf(";", n - 1) + 1;
41
+ continue;
42
+ }
43
+ const c = o.slice(i, n).trim();
44
+ if (t[c] === void 0) {
45
+ let a = o.slice(n + 1, r).trim();
46
+ a.charCodeAt(0) === 34 && (a = a.slice(1, -1));
47
+ try {
48
+ t[c] = s(a);
49
+ } catch {
50
+ t[c] = a;
51
+ }
52
+ }
53
+ i = r + 1;
54
+ }
55
+ return t;
56
+ }
57
+ function N(o, e, t) {
58
+ const s = Object.assign({}, t || {}), i = s.encode || X;
59
+ if (!L.test(o)) throw new TypeError("argument name is invalid");
60
+ const n = i(e);
61
+ if (n && !L.test(n)) throw new TypeError("argument val is invalid");
62
+ let r = o + "=" + n;
63
+ if (s.maxAge != null) {
64
+ const c = s.maxAge - 0;
65
+ if (isNaN(c) || !isFinite(c)) throw new TypeError("option maxAge is invalid");
66
+ r += "; Max-Age=" + Math.floor(c);
67
+ }
68
+ if (s.domain) {
69
+ if (!L.test(s.domain)) throw new TypeError("option domain is invalid");
70
+ r += "; Domain=" + s.domain;
71
+ }
72
+ if (s.path) {
73
+ if (!L.test(s.path)) throw new TypeError("option path is invalid");
74
+ r += "; Path=" + s.path;
75
+ }
76
+ if (s.expires) {
77
+ if (!(function(a) {
78
+ return Object.prototype.toString.call(a) === "[object Date]" || a instanceof Date;
79
+ })(s.expires) || isNaN(s.expires.valueOf())) throw new TypeError("option expires is invalid");
80
+ r += "; Expires=" + s.expires.toUTCString();
81
+ }
82
+ if (s.httpOnly && (r += "; HttpOnly"), s.secure && (r += "; Secure"), s.priority)
83
+ switch (typeof s.priority == "string" ? s.priority.toLowerCase() : s.priority) {
84
+ case "low":
85
+ r += "; Priority=Low";
86
+ break;
87
+ case "medium":
88
+ r += "; Priority=Medium";
89
+ break;
90
+ case "high":
91
+ r += "; Priority=High";
92
+ break;
93
+ default:
94
+ throw new TypeError("option priority is invalid");
95
+ }
96
+ if (s.sameSite)
97
+ switch (typeof s.sameSite == "string" ? s.sameSite.toLowerCase() : s.sameSite) {
98
+ case !0:
99
+ r += "; SameSite=Strict";
100
+ break;
101
+ case "lax":
102
+ r += "; SameSite=Lax";
103
+ break;
104
+ case "strict":
105
+ r += "; SameSite=Strict";
106
+ break;
107
+ case "none":
108
+ r += "; SameSite=None";
109
+ break;
110
+ default:
111
+ throw new TypeError("option sameSite is invalid");
112
+ }
113
+ return r;
114
+ }
115
+ function Y(o) {
116
+ return o.indexOf("%") !== -1 ? decodeURIComponent(o) : o;
117
+ }
118
+ function X(o) {
119
+ return encodeURIComponent(o);
120
+ }
121
+ const Z = typeof navigator < "u" && navigator.product === "ReactNative" || typeof global < "u" && global.HermesInternal;
122
+ let K;
123
+ function T(o) {
124
+ if (o) try {
125
+ const e = decodeURIComponent(K(o.split(".")[1]).split("").map((function(t) {
126
+ return "%" + ("00" + t.charCodeAt(0).toString(16)).slice(-2);
127
+ })).join(""));
128
+ return JSON.parse(e) || {};
129
+ } catch {
130
+ }
131
+ return {};
132
+ }
133
+ function $(o, e = 0) {
134
+ let t = T(o);
135
+ return !(Object.keys(t).length > 0 && (!t.exp || t.exp - e > Date.now() / 1e3));
136
+ }
137
+ K = typeof atob != "function" || Z ? (o) => {
138
+ let e = String(o).replace(/=+$/, "");
139
+ if (e.length % 4 == 1) throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
140
+ for (var t, s, i = 0, n = 0, r = ""; s = e.charAt(n++); ~s && (t = i % 4 ? 64 * t + s : s, i++ % 4) ? r += String.fromCharCode(255 & t >> (-2 * i & 6)) : 0) s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);
141
+ return r;
142
+ } : atob;
143
+ const F = "pb_auth";
144
+ class q {
145
+ constructor() {
146
+ this.baseToken = "", this.baseModel = null, this._onChangeCallbacks = [];
147
+ }
148
+ get token() {
149
+ return this.baseToken;
150
+ }
151
+ get record() {
152
+ return this.baseModel;
153
+ }
154
+ get model() {
155
+ return this.baseModel;
156
+ }
157
+ get isValid() {
158
+ return !$(this.token);
159
+ }
160
+ get isSuperuser() {
161
+ var t, s;
162
+ let e = T(this.token);
163
+ return e.type == "auth" && (((t = this.record) == null ? void 0 : t.collectionName) == "_superusers" || !((s = this.record) != null && s.collectionName) && e.collectionId == "pbc_3142635823");
164
+ }
165
+ get isAdmin() {
166
+ return console.warn("Please replace pb.authStore.isAdmin with pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName"), this.isSuperuser;
167
+ }
168
+ get isAuthRecord() {
169
+ return console.warn("Please replace pb.authStore.isAuthRecord with !pb.authStore.isSuperuser OR simply check the value of pb.authStore.record?.collectionName"), T(this.token).type == "auth" && !this.isSuperuser;
170
+ }
171
+ save(e, t) {
172
+ this.baseToken = e || "", this.baseModel = t || null, this.triggerChange();
173
+ }
174
+ clear() {
175
+ this.baseToken = "", this.baseModel = null, this.triggerChange();
176
+ }
177
+ loadFromCookie(e, t = F) {
178
+ const s = Q(e || "")[t] || "";
179
+ let i = {};
180
+ try {
181
+ i = JSON.parse(s), (typeof i === null || typeof i != "object" || Array.isArray(i)) && (i = {});
182
+ } catch {
183
+ }
184
+ this.save(i.token || "", i.record || i.model || null);
185
+ }
186
+ exportToCookie(e, t = F) {
187
+ var a, l;
188
+ const s = { secure: !0, sameSite: !0, httpOnly: !0, path: "/" }, i = T(this.token);
189
+ s.expires = i != null && i.exp ? new Date(1e3 * i.exp) : /* @__PURE__ */ new Date("1970-01-01"), e = Object.assign({}, s, e);
190
+ const n = { token: this.token, record: this.record ? JSON.parse(JSON.stringify(this.record)) : null };
191
+ let r = N(t, JSON.stringify(n), e);
192
+ const c = typeof Blob < "u" ? new Blob([r]).size : r.length;
193
+ if (n.record && c > 4096) {
194
+ n.record = { id: (a = n.record) == null ? void 0 : a.id, email: (l = n.record) == null ? void 0 : l.email };
195
+ const O = ["collectionId", "collectionName", "verified"];
196
+ for (const p in this.record) O.includes(p) && (n.record[p] = this.record[p]);
197
+ r = N(t, JSON.stringify(n), e);
198
+ }
199
+ return r;
200
+ }
201
+ onChange(e, t = !1) {
202
+ return this._onChangeCallbacks.push(e), t && e(this.token, this.record), () => {
203
+ for (let s = this._onChangeCallbacks.length - 1; s >= 0; s--) if (this._onChangeCallbacks[s] == e) return delete this._onChangeCallbacks[s], void this._onChangeCallbacks.splice(s, 1);
204
+ };
205
+ }
206
+ triggerChange() {
207
+ for (const e of this._onChangeCallbacks) e && e(this.token, this.record);
208
+ }
209
+ }
210
+ class ee extends q {
211
+ constructor(e = "pocketbase_auth") {
212
+ super(), this.storageFallback = {}, this.storageKey = e, this._bindStorageEvent();
213
+ }
214
+ get token() {
215
+ return (this._storageGet(this.storageKey) || {}).token || "";
216
+ }
217
+ get record() {
218
+ const e = this._storageGet(this.storageKey) || {};
219
+ return e.record || e.model || null;
220
+ }
221
+ get model() {
222
+ return this.record;
223
+ }
224
+ save(e, t) {
225
+ this._storageSet(this.storageKey, { token: e, record: t }), super.save(e, t);
226
+ }
227
+ clear() {
228
+ this._storageRemove(this.storageKey), super.clear();
229
+ }
230
+ _storageGet(e) {
231
+ if (typeof window < "u" && (window != null && window.localStorage)) {
232
+ const t = window.localStorage.getItem(e) || "";
233
+ try {
234
+ return JSON.parse(t);
235
+ } catch {
236
+ return t;
237
+ }
238
+ }
239
+ return this.storageFallback[e];
240
+ }
241
+ _storageSet(e, t) {
242
+ if (typeof window < "u" && (window != null && window.localStorage)) {
243
+ let s = t;
244
+ typeof t != "string" && (s = JSON.stringify(t)), window.localStorage.setItem(e, s);
245
+ } else this.storageFallback[e] = t;
246
+ }
247
+ _storageRemove(e) {
248
+ var t;
249
+ typeof window < "u" && (window != null && window.localStorage) && ((t = window.localStorage) == null || t.removeItem(e)), delete this.storageFallback[e];
250
+ }
251
+ _bindStorageEvent() {
252
+ typeof window < "u" && (window != null && window.localStorage) && window.addEventListener && window.addEventListener("storage", ((e) => {
253
+ if (e.key != this.storageKey) return;
254
+ const t = this._storageGet(this.storageKey) || {};
255
+ super.save(t.token || "", t.record || t.model || null);
256
+ }));
257
+ }
258
+ }
259
+ class y {
260
+ constructor(e) {
261
+ this.client = e;
262
+ }
263
+ }
264
+ class te extends y {
265
+ async getAll(e) {
266
+ return e = Object.assign({ method: "GET" }, e), this.client.send("/api/settings", e);
267
+ }
268
+ async update(e, t) {
269
+ return t = Object.assign({ method: "PATCH", body: e }, t), this.client.send("/api/settings", t);
270
+ }
271
+ async testS3(e = "storage", t) {
272
+ return t = Object.assign({ method: "POST", body: { filesystem: e } }, t), this.client.send("/api/settings/test/s3", t).then((() => !0));
273
+ }
274
+ async testEmail(e, t, s, i) {
275
+ return i = Object.assign({ method: "POST", body: { email: t, template: s, collection: e } }, i), this.client.send("/api/settings/test/email", i).then((() => !0));
276
+ }
277
+ async generateAppleClientSecret(e, t, s, i, n, r) {
278
+ 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);
279
+ }
280
+ }
281
+ const se = ["requestKey", "$cancelKey", "$autoCancel", "fetch", "headers", "body", "query", "params", "cache", "credentials", "headers", "integrity", "keepalive", "method", "mode", "redirect", "referrer", "referrerPolicy", "signal", "window"];
282
+ function U(o) {
283
+ if (o) {
284
+ o.query = o.query || {};
285
+ for (let e in o) se.includes(e) || (o.query[e] = o[e], delete o[e]);
286
+ }
287
+ }
288
+ function V(o) {
289
+ const e = [];
290
+ for (const t in o) {
291
+ const s = encodeURIComponent(t), i = Array.isArray(o[t]) ? o[t] : [o[t]];
292
+ for (let n of i) n = ie(n), n !== null && e.push(s + "=" + n);
293
+ }
294
+ return e.join("&");
295
+ }
296
+ function ie(o) {
297
+ return o == null ? null : o instanceof Date ? encodeURIComponent(o.toISOString().replace("T", " ")) : encodeURIComponent(typeof o == "object" ? JSON.stringify(o) : o);
298
+ }
299
+ class W extends y {
300
+ constructor() {
301
+ 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 = [];
302
+ }
303
+ get isConnected() {
304
+ return !!this.eventSource && !!this.clientId && !this.pendingConnects.length;
305
+ }
306
+ async subscribe(e, t, s) {
307
+ var r;
308
+ if (!e) throw new Error("topic must be set.");
309
+ let i = e;
310
+ if (s) {
311
+ U(s = Object.assign({}, s));
312
+ const c = "options=" + encodeURIComponent(JSON.stringify({ query: s.query, headers: s.headers }));
313
+ i += (i.includes("?") ? "&" : "?") + c;
314
+ }
315
+ const n = function(c) {
316
+ const a = c;
317
+ let l;
318
+ try {
319
+ l = JSON.parse(a == null ? void 0 : a.data);
320
+ } catch {
321
+ }
322
+ t(l || {});
323
+ };
324
+ return this.subscriptions[i] || (this.subscriptions[i] = []), this.subscriptions[i].push(n), this.isConnected ? this.subscriptions[i].length === 1 ? await this.submitSubscriptions() : (r = this.eventSource) == null || r.addEventListener(i, n) : await this.connect(), async () => this.unsubscribeByTopicAndListener(e, n);
325
+ }
326
+ async unsubscribe(e) {
327
+ var s;
328
+ let t = !1;
329
+ if (e) {
330
+ const i = this.getSubscriptionsByTopic(e);
331
+ for (let n in i) if (this.hasSubscriptionListeners(n)) {
332
+ for (let r of this.subscriptions[n]) (s = this.eventSource) == null || s.removeEventListener(n, r);
333
+ delete this.subscriptions[n], t || (t = !0);
334
+ }
335
+ } else this.subscriptions = {};
336
+ this.hasSubscriptionListeners() ? t && await this.submitSubscriptions() : this.disconnect();
337
+ }
338
+ async unsubscribeByPrefix(e) {
339
+ var s;
340
+ let t = !1;
341
+ for (let i in this.subscriptions) if ((i + "?").startsWith(e)) {
342
+ t = !0;
343
+ for (let n of this.subscriptions[i]) (s = this.eventSource) == null || s.removeEventListener(i, n);
344
+ delete this.subscriptions[i];
345
+ }
346
+ t && (this.hasSubscriptionListeners() ? await this.submitSubscriptions() : this.disconnect());
347
+ }
348
+ async unsubscribeByTopicAndListener(e, t) {
349
+ var n;
350
+ let s = !1;
351
+ const i = this.getSubscriptionsByTopic(e);
352
+ for (let r in i) {
353
+ if (!Array.isArray(this.subscriptions[r]) || !this.subscriptions[r].length) continue;
354
+ let c = !1;
355
+ for (let a = this.subscriptions[r].length - 1; a >= 0; a--) this.subscriptions[r][a] === t && (c = !0, delete this.subscriptions[r][a], this.subscriptions[r].splice(a, 1), (n = this.eventSource) == null || n.removeEventListener(r, t));
356
+ c && (this.subscriptions[r].length || delete this.subscriptions[r], s || this.hasSubscriptionListeners(r) || (s = !0));
357
+ }
358
+ this.hasSubscriptionListeners() ? s && await this.submitSubscriptions() : this.disconnect();
359
+ }
360
+ hasSubscriptionListeners(e) {
361
+ var t, s;
362
+ if (this.subscriptions = this.subscriptions || {}, e) return !!((t = this.subscriptions[e]) != null && t.length);
363
+ for (let i in this.subscriptions) if ((s = this.subscriptions[i]) != null && s.length) return !0;
364
+ return !1;
365
+ }
366
+ async submitSubscriptions() {
367
+ 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) => {
368
+ if (!(e != null && e.isAbort)) throw e;
369
+ }));
370
+ }
371
+ getSubscriptionsCancelKey() {
372
+ return "realtime_" + this.clientId;
373
+ }
374
+ getSubscriptionsByTopic(e) {
375
+ const t = {};
376
+ e = e.includes("?") ? e : e + "?";
377
+ for (let s in this.subscriptions) (s + "?").startsWith(e) && (t[s] = this.subscriptions[s]);
378
+ return t;
379
+ }
380
+ getNonEmptySubscriptionKeys() {
381
+ const e = [];
382
+ for (let t in this.subscriptions) this.subscriptions[t].length && e.push(t);
383
+ return e;
384
+ }
385
+ addAllSubscriptionListeners() {
386
+ if (this.eventSource) {
387
+ this.removeAllSubscriptionListeners();
388
+ for (let e in this.subscriptions) for (let t of this.subscriptions[e]) this.eventSource.addEventListener(e, t);
389
+ }
390
+ }
391
+ removeAllSubscriptionListeners() {
392
+ if (this.eventSource) for (let e in this.subscriptions) for (let t of this.subscriptions[e]) this.eventSource.removeEventListener(e, t);
393
+ }
394
+ async connect() {
395
+ if (!(this.reconnectAttempts > 0)) return new Promise(((e, t) => {
396
+ this.pendingConnects.push({ resolve: e, reject: t }), this.pendingConnects.length > 1 || this.initConnect();
397
+ }));
398
+ }
399
+ initConnect() {
400
+ this.disconnect(!0), clearTimeout(this.connectTimeoutId), this.connectTimeoutId = setTimeout((() => {
401
+ this.connectErrorHandler(new Error("EventSource connect took too long."));
402
+ }), this.maxConnectTimeout), this.eventSource = new EventSource(this.client.buildURL("/api/realtime")), this.eventSource.onerror = (e) => {
403
+ this.connectErrorHandler(new Error("Failed to establish realtime connection."));
404
+ }, this.eventSource.addEventListener("PB_CONNECT", ((e) => {
405
+ const t = e;
406
+ this.clientId = t == null ? void 0 : t.lastEventId, this.submitSubscriptions().then((async () => {
407
+ let s = 3;
408
+ for (; this.hasUnsentSubscriptions() && s > 0; ) s--, await this.submitSubscriptions();
409
+ })).then((() => {
410
+ for (let i of this.pendingConnects) i.resolve();
411
+ this.pendingConnects = [], this.reconnectAttempts = 0, clearTimeout(this.reconnectTimeoutId), clearTimeout(this.connectTimeoutId);
412
+ const s = this.getSubscriptionsByTopic("PB_CONNECT");
413
+ for (let i in s) for (let n of s[i]) n(e);
414
+ })).catch(((s) => {
415
+ this.clientId = "", this.connectErrorHandler(s);
416
+ }));
417
+ }));
418
+ }
419
+ hasUnsentSubscriptions() {
420
+ const e = this.getNonEmptySubscriptionKeys();
421
+ if (e.length != this.lastSentSubscriptions.length) return !0;
422
+ for (const t of e) if (!this.lastSentSubscriptions.includes(t)) return !0;
423
+ return !1;
424
+ }
425
+ connectErrorHandler(e) {
426
+ if (clearTimeout(this.connectTimeoutId), clearTimeout(this.reconnectTimeoutId), !this.clientId && !this.reconnectAttempts || this.reconnectAttempts > this.maxReconnectAttempts) {
427
+ for (let s of this.pendingConnects) s.reject(new f(e));
428
+ return this.pendingConnects = [], void this.disconnect();
429
+ }
430
+ this.disconnect(!0);
431
+ const t = this.predefinedReconnectIntervals[this.reconnectAttempts] || this.predefinedReconnectIntervals[this.predefinedReconnectIntervals.length - 1];
432
+ this.reconnectAttempts++, this.reconnectTimeoutId = setTimeout((() => {
433
+ this.initConnect();
434
+ }), t);
435
+ }
436
+ disconnect(e = !1) {
437
+ var t;
438
+ if (this.clientId && this.onDisconnect && this.onDisconnect(Object.keys(this.subscriptions)), clearTimeout(this.connectTimeoutId), clearTimeout(this.reconnectTimeoutId), this.removeAllSubscriptionListeners(), this.client.cancelRequest(this.getSubscriptionsCancelKey()), (t = this.eventSource) == null || t.close(), this.eventSource = null, this.clientId = "", !e) {
439
+ this.reconnectAttempts = 0;
440
+ for (let s of this.pendingConnects) s.resolve();
441
+ this.pendingConnects = [];
442
+ }
443
+ }
444
+ }
445
+ class H extends y {
446
+ decode(e) {
447
+ return e;
448
+ }
449
+ async getFullList(e, t) {
450
+ if (typeof e == "number") return this._getFullList(e, t);
451
+ let s = 500;
452
+ return (t = Object.assign({}, e, t)).batch && (s = t.batch, delete t.batch), this._getFullList(s, t);
453
+ }
454
+ async getList(e = 1, t = 30, s) {
455
+ return (s = Object.assign({ method: "GET" }, s)).query = Object.assign({ page: e, perPage: t }, s.query), this.client.send(this.baseCrudPath, s).then(((i) => {
456
+ var n;
457
+ return i.items = ((n = i.items) == null ? void 0 : n.map(((r) => this.decode(r)))) || [], i;
458
+ }));
459
+ }
460
+ async getFirstListItem(e, t) {
461
+ 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(((s) => {
462
+ var i;
463
+ if (!((i = s == null ? void 0 : s.items) != null && i.length)) throw new f({ status: 404, response: { code: 404, message: "The requested resource wasn't found.", data: {} } });
464
+ return s.items[0];
465
+ }));
466
+ }
467
+ async getOne(e, t) {
468
+ if (!e) throw new f({ url: this.client.buildURL(this.baseCrudPath + "/"), status: 404, response: { code: 404, message: "Missing required record id.", data: {} } });
469
+ return t = Object.assign({ method: "GET" }, t), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e), t).then(((s) => this.decode(s)));
470
+ }
471
+ async create(e, t) {
472
+ return t = Object.assign({ method: "POST", body: e }, t), this.client.send(this.baseCrudPath, t).then(((s) => this.decode(s)));
473
+ }
474
+ async update(e, t, s) {
475
+ return s = Object.assign({ method: "PATCH", body: t }, s), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e), s).then(((i) => this.decode(i)));
476
+ }
477
+ async delete(e, t) {
478
+ return t = Object.assign({ method: "DELETE" }, t), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e), t).then((() => !0));
479
+ }
480
+ _getFullList(e = 500, t) {
481
+ (t = t || {}).query = Object.assign({ skipTotal: 1 }, t.query);
482
+ let s = [], i = async (n) => this.getList(n, e || 500, t).then(((r) => {
483
+ const c = r.items;
484
+ return s = s.concat(c), c.length == r.perPage ? i(n + 1) : s;
485
+ }));
486
+ return i(1);
487
+ }
488
+ }
489
+ function w(o, e, t, s) {
490
+ const i = s !== void 0;
491
+ return i || t !== void 0 ? i ? (console.warn(o), e.body = Object.assign({}, e.body, t), e.query = Object.assign({}, e.query, s), e) : Object.assign(e, t) : e;
492
+ }
493
+ function j(o) {
494
+ var e;
495
+ (e = o._resetAutoRefresh) == null || e.call(o);
496
+ }
497
+ class ne extends H {
498
+ constructor(e, t) {
499
+ super(e), this.collectionIdOrName = t;
500
+ }
501
+ get baseCrudPath() {
502
+ return this.baseCollectionPath + "/records";
503
+ }
504
+ get baseCollectionPath() {
505
+ return "/api/collections/" + encodeURIComponent(this.collectionIdOrName);
506
+ }
507
+ get isSuperusers() {
508
+ return this.collectionIdOrName == "_superusers" || this.collectionIdOrName == "_pbc_2773867675";
509
+ }
510
+ async subscribe(e, t, s) {
511
+ if (!e) throw new Error("Missing topic.");
512
+ if (!t) throw new Error("Missing subscription callback.");
513
+ return this.client.realtime.subscribe(this.collectionIdOrName + "/" + e, t, s);
514
+ }
515
+ async unsubscribe(e) {
516
+ return e ? this.client.realtime.unsubscribe(this.collectionIdOrName + "/" + e) : this.client.realtime.unsubscribeByPrefix(this.collectionIdOrName);
517
+ }
518
+ async getFullList(e, t) {
519
+ if (typeof e == "number") return super.getFullList(e, t);
520
+ const s = Object.assign({}, e, t);
521
+ return super.getFullList(s);
522
+ }
523
+ async getList(e = 1, t = 30, s) {
524
+ return super.getList(e, t, s);
525
+ }
526
+ async getFirstListItem(e, t) {
527
+ return super.getFirstListItem(e, t);
528
+ }
529
+ async getOne(e, t) {
530
+ return super.getOne(e, t);
531
+ }
532
+ async create(e, t) {
533
+ return super.create(e, t);
534
+ }
535
+ async update(e, t, s) {
536
+ return super.update(e, t, s).then(((i) => {
537
+ var n, r, c;
538
+ if (((n = this.client.authStore.record) == null ? void 0 : n.id) === (i == null ? void 0 : i.id) && (((r = this.client.authStore.record) == null ? void 0 : r.collectionId) === this.collectionIdOrName || ((c = this.client.authStore.record) == null ? void 0 : c.collectionName) === this.collectionIdOrName)) {
539
+ let a = Object.assign({}, this.client.authStore.record.expand), l = Object.assign({}, this.client.authStore.record, i);
540
+ a && (l.expand = Object.assign(a, i.expand)), this.client.authStore.save(this.client.authStore.token, l);
541
+ }
542
+ return i;
543
+ }));
544
+ }
545
+ async delete(e, t) {
546
+ return super.delete(e, t).then(((s) => {
547
+ var i, n, r;
548
+ return !s || ((i = this.client.authStore.record) == null ? void 0 : i.id) !== e || ((n = this.client.authStore.record) == null ? void 0 : n.collectionId) !== this.collectionIdOrName && ((r = this.client.authStore.record) == null ? void 0 : r.collectionName) !== this.collectionIdOrName || this.client.authStore.clear(), s;
549
+ }));
550
+ }
551
+ authResponse(e) {
552
+ const t = this.decode((e == null ? void 0 : e.record) || {});
553
+ return this.client.authStore.save(e == null ? void 0 : e.token, t), Object.assign({}, e, { token: (e == null ? void 0 : e.token) || "", record: t });
554
+ }
555
+ async listAuthMethods(e) {
556
+ return e = Object.assign({ method: "GET", fields: "mfa,otp,password,oauth2" }, e), this.client.send(this.baseCollectionPath + "/auth-methods", e);
557
+ }
558
+ async authWithPassword(e, t, s) {
559
+ let i;
560
+ s = Object.assign({ method: "POST", body: { identity: e, password: t } }, s), this.isSuperusers && (i = s.autoRefreshThreshold, delete s.autoRefreshThreshold, s.autoRefresh || j(this.client));
561
+ let n = await this.client.send(this.baseCollectionPath + "/auth-with-password", s);
562
+ return n = this.authResponse(n), i && this.isSuperusers && (function(c, a, l, O) {
563
+ j(c);
564
+ const p = c.beforeSend, b = c.authStore.record, R = c.authStore.onChange(((m, h) => {
565
+ (!m || (h == null ? void 0 : h.id) != (b == null ? void 0 : b.id) || (h != null && h.collectionId || b != null && b.collectionId) && (h == null ? void 0 : h.collectionId) != (b == null ? void 0 : b.collectionId)) && j(c);
566
+ }));
567
+ c._resetAutoRefresh = function() {
568
+ R(), c.beforeSend = p, delete c._resetAutoRefresh;
569
+ }, c.beforeSend = async (m, h) => {
570
+ var g;
571
+ const I = c.authStore.token;
572
+ if ((g = h.query) != null && g.autoRefresh) return p ? p(m, h) : { url: m, sendOptions: h };
573
+ let P = c.authStore.isValid;
574
+ if (P && $(c.authStore.token, a)) try {
575
+ await l();
576
+ } catch {
577
+ P = !1;
578
+ }
579
+ P || await O();
580
+ const k = h.headers || {};
581
+ for (let v in k) if (v.toLowerCase() == "authorization" && I == k[v] && c.authStore.token) {
582
+ k[v] = c.authStore.token;
583
+ break;
584
+ }
585
+ return h.headers = k, p ? p(m, h) : { url: m, sendOptions: h };
586
+ };
587
+ })(this.client, i, (() => this.authRefresh({ autoRefresh: !0 })), (() => this.authWithPassword(e, t, Object.assign({ autoRefresh: !0 }, s)))), n;
588
+ }
589
+ async authWithOAuth2Code(e, t, s, i, n, r, c) {
590
+ let a = { method: "POST", body: { provider: e, code: t, codeVerifier: s, redirectURL: i, createData: n } };
591
+ return a = w("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, c), this.client.send(this.baseCollectionPath + "/auth-with-oauth2", a).then(((l) => this.authResponse(l)));
592
+ }
593
+ authWithOAuth2(...e) {
594
+ if (e.length > 1 || typeof (e == null ? void 0 : e[0]) == "string") 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 == null ? void 0 : e[0]) || "", (e == null ? void 0 : e[1]) || "", (e == null ? void 0 : e[2]) || "", (e == null ? void 0 : e[3]) || "", (e == null ? void 0 : e[4]) || {}, (e == null ? void 0 : e[5]) || {}, (e == null ? void 0 : e[6]) || {});
595
+ const t = (e == null ? void 0 : e[0]) || {};
596
+ let s = null;
597
+ t.urlCallback || (s = D(void 0));
598
+ const i = new W(this.client);
599
+ function n() {
600
+ s == null || s.close(), i.unsubscribe();
601
+ }
602
+ const r = {}, c = t.requestKey;
603
+ return c && (r.requestKey = c), this.listAuthMethods(r).then(((a) => {
604
+ var b;
605
+ const l = a.oauth2.providers.find(((R) => R.name === t.provider));
606
+ if (!l) throw new f(new Error(`Missing or invalid provider "${t.provider}".`));
607
+ const O = this.client.buildURL("/api/oauth2-redirect"), p = c ? (b = this.client.cancelControllers) == null ? void 0 : b[c] : void 0;
608
+ return p && (p.signal.onabort = () => {
609
+ n();
610
+ }), new Promise((async (R, m) => {
611
+ var h;
612
+ try {
613
+ await i.subscribe("@oauth2", (async (g) => {
614
+ var x;
615
+ const v = i.clientId;
616
+ try {
617
+ if (!g.state || v !== g.state) throw new Error("State parameters don't match.");
618
+ if (g.error || !g.code) throw new Error("OAuth2 redirect error or missing code: " + g.error);
619
+ const S = Object.assign({}, t);
620
+ delete S.provider, delete S.scopes, delete S.createData, delete S.urlCallback, (x = p == null ? void 0 : p.signal) != null && x.onabort && (p.signal.onabort = null);
621
+ const G = await this.authWithOAuth2Code(l.name, g.code, l.codeVerifier, O, t.createData, S);
622
+ R(G);
623
+ } catch (S) {
624
+ m(new f(S));
625
+ }
626
+ n();
627
+ }));
628
+ const I = { state: i.clientId };
629
+ (h = t.scopes) != null && h.length && (I.scope = t.scopes.join(" "));
630
+ const P = this._replaceQueryParams(l.authURL + O, I);
631
+ await (t.urlCallback || function(g) {
632
+ s ? s.location.href = g : s = D(g);
633
+ })(P);
634
+ } catch (I) {
635
+ n(), m(new f(I));
636
+ }
637
+ }));
638
+ })).catch(((a) => {
639
+ throw n(), a;
640
+ }));
641
+ }
642
+ async authRefresh(e, t) {
643
+ let s = { method: "POST" };
644
+ return s = w("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(((i) => this.authResponse(i)));
645
+ }
646
+ async requestPasswordReset(e, t, s) {
647
+ let i = { method: "POST", body: { email: e } };
648
+ return i = w("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));
649
+ }
650
+ async confirmPasswordReset(e, t, s, i, n) {
651
+ let r = { method: "POST", body: { token: e, password: t, passwordConfirm: s } };
652
+ return r = w("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));
653
+ }
654
+ async requestVerification(e, t, s) {
655
+ let i = { method: "POST", body: { email: e } };
656
+ return i = w("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));
657
+ }
658
+ async confirmVerification(e, t, s) {
659
+ let i = { method: "POST", body: { token: e } };
660
+ return i = w("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((() => {
661
+ const n = T(e), r = this.client.authStore.record;
662
+ return r && !r.verified && r.id === n.id && r.collectionId === n.collectionId && (r.verified = !0, this.client.authStore.save(this.client.authStore.token, r)), !0;
663
+ }));
664
+ }
665
+ async requestEmailChange(e, t, s) {
666
+ let i = { method: "POST", body: { newEmail: e } };
667
+ return i = w("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));
668
+ }
669
+ async confirmEmailChange(e, t, s, i) {
670
+ let n = { method: "POST", body: { token: e, password: t } };
671
+ return n = w("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((() => {
672
+ const r = T(e), c = this.client.authStore.record;
673
+ return c && c.id === r.id && c.collectionId === r.collectionId && this.client.authStore.clear(), !0;
674
+ }));
675
+ }
676
+ async listExternalAuths(e, t) {
677
+ return this.client.collection("_externalAuths").getFullList(Object.assign({}, t, { filter: this.client.filter("recordRef = {:id}", { id: e }) }));
678
+ }
679
+ async unlinkExternalAuth(e, t, s) {
680
+ const i = await this.client.collection("_externalAuths").getFirstListItem(this.client.filter("recordRef = {:recordId} && provider = {:provider}", { recordId: e, provider: t }));
681
+ return this.client.collection("_externalAuths").delete(i.id, s).then((() => !0));
682
+ }
683
+ async requestOTP(e, t) {
684
+ return t = Object.assign({ method: "POST", body: { email: e } }, t), this.client.send(this.baseCollectionPath + "/request-otp", t);
685
+ }
686
+ async authWithOTP(e, t, s) {
687
+ return s = Object.assign({ method: "POST", body: { otpId: e, password: t } }, s), this.client.send(this.baseCollectionPath + "/auth-with-otp", s).then(((i) => this.authResponse(i)));
688
+ }
689
+ async impersonate(e, t, s) {
690
+ (s = Object.assign({ method: "POST", body: { duration: t } }, s)).headers = s.headers || {}, s.headers.Authorization || (s.headers.Authorization = this.client.authStore.token);
691
+ const i = new M(this.client.baseURL, new q(), this.client.lang), n = await i.send(this.baseCollectionPath + "/impersonate/" + encodeURIComponent(e), s);
692
+ return i.authStore.save(n == null ? void 0 : n.token, this.decode((n == null ? void 0 : n.record) || {})), i;
693
+ }
694
+ _replaceQueryParams(e, t = {}) {
695
+ let s = e, i = "";
696
+ e.indexOf("?") >= 0 && (s = e.substring(0, e.indexOf("?")), i = e.substring(e.indexOf("?") + 1));
697
+ const n = {}, r = i.split("&");
698
+ for (const c of r) {
699
+ if (c == "") continue;
700
+ const a = c.split("=");
701
+ n[decodeURIComponent(a[0].replace(/\+/g, " "))] = decodeURIComponent((a[1] || "").replace(/\+/g, " "));
702
+ }
703
+ for (let c in t) t.hasOwnProperty(c) && (t[c] == null ? delete n[c] : n[c] = t[c]);
704
+ i = "";
705
+ for (let c in n) n.hasOwnProperty(c) && (i != "" && (i += "&"), i += encodeURIComponent(c.replace(/%20/g, "+")) + "=" + encodeURIComponent(n[c].replace(/%20/g, "+")));
706
+ return i != "" ? s + "?" + i : s;
707
+ }
708
+ }
709
+ function D(o) {
710
+ if (typeof window > "u" || !(window != null && window.open)) throw new f(new Error("Not in a browser context - please pass a custom urlCallback function."));
711
+ let e = 1024, t = 768, s = window.innerWidth, i = window.innerHeight;
712
+ e = e > s ? s : e, t = t > i ? i : t;
713
+ let n = s / 2 - e / 2, r = i / 2 - t / 2;
714
+ return window.open(o, "popup_window", "width=" + e + ",height=" + t + ",top=" + r + ",left=" + n + ",resizable,menubar=no");
715
+ }
716
+ class re extends H {
717
+ get baseCrudPath() {
718
+ return "/api/collections";
719
+ }
720
+ async import(e, t = !1, s) {
721
+ return s = Object.assign({ method: "PUT", body: { collections: e, deleteMissing: t } }, s), this.client.send(this.baseCrudPath + "/import", s).then((() => !0));
722
+ }
723
+ async getScaffolds(e) {
724
+ return e = Object.assign({ method: "GET" }, e), this.client.send(this.baseCrudPath + "/meta/scaffolds", e);
725
+ }
726
+ async truncate(e, t) {
727
+ return t = Object.assign({ method: "DELETE" }, t), this.client.send(this.baseCrudPath + "/" + encodeURIComponent(e) + "/truncate", t).then((() => !0));
728
+ }
729
+ }
730
+ class oe extends y {
731
+ async getList(e = 1, t = 30, s) {
732
+ return (s = Object.assign({ method: "GET" }, s)).query = Object.assign({ page: e, perPage: t }, s.query), this.client.send("/api/logs", s);
733
+ }
734
+ async getOne(e, t) {
735
+ if (!e) throw new f({ url: this.client.buildURL("/api/logs/"), status: 404, response: { code: 404, message: "Missing required log id.", data: {} } });
736
+ return t = Object.assign({ method: "GET" }, t), this.client.send("/api/logs/" + encodeURIComponent(e), t);
737
+ }
738
+ async getStats(e) {
739
+ return e = Object.assign({ method: "GET" }, e), this.client.send("/api/logs/stats", e);
740
+ }
741
+ }
742
+ class ce extends y {
743
+ async check(e) {
744
+ return e = Object.assign({ method: "GET" }, e), this.client.send("/api/health", e);
745
+ }
746
+ }
747
+ class ae extends y {
748
+ getUrl(e, t, s = {}) {
749
+ return console.warn("Please replace pb.files.getUrl() with pb.files.getURL()"), this.getURL(e, t, s);
750
+ }
751
+ getURL(e, t, s = {}) {
752
+ if (!t || !(e != null && e.id) || !(e != null && e.collectionId) && !(e != null && e.collectionName)) return "";
753
+ const i = [];
754
+ i.push("api"), i.push("files"), i.push(encodeURIComponent(e.collectionId || e.collectionName)), i.push(encodeURIComponent(e.id)), i.push(encodeURIComponent(t));
755
+ let n = this.client.buildURL(i.join("/"));
756
+ if (Object.keys(s).length) {
757
+ s.download === !1 && delete s.download;
758
+ const r = new URLSearchParams(s);
759
+ n += (n.includes("?") ? "&" : "?") + r;
760
+ }
761
+ return n;
762
+ }
763
+ async getToken(e) {
764
+ return e = Object.assign({ method: "POST" }, e), this.client.send("/api/files/token", e).then(((t) => (t == null ? void 0 : t.token) || ""));
765
+ }
766
+ }
767
+ class le extends y {
768
+ async getFullList(e) {
769
+ return e = Object.assign({ method: "GET" }, e), this.client.send("/api/backups", e);
770
+ }
771
+ async create(e, t) {
772
+ return t = Object.assign({ method: "POST", body: { name: e } }, t), this.client.send("/api/backups", t).then((() => !0));
773
+ }
774
+ async upload(e, t) {
775
+ return t = Object.assign({ method: "POST", body: e }, t), this.client.send("/api/backups/upload", t).then((() => !0));
776
+ }
777
+ async delete(e, t) {
778
+ return t = Object.assign({ method: "DELETE" }, t), this.client.send(`/api/backups/${encodeURIComponent(e)}`, t).then((() => !0));
779
+ }
780
+ async restore(e, t) {
781
+ return t = Object.assign({ method: "POST" }, t), this.client.send(`/api/backups/${encodeURIComponent(e)}/restore`, t).then((() => !0));
782
+ }
783
+ getDownloadUrl(e, t) {
784
+ return console.warn("Please replace pb.backups.getDownloadUrl() with pb.backups.getDownloadURL()"), this.getDownloadURL(e, t);
785
+ }
786
+ getDownloadURL(e, t) {
787
+ return this.client.buildURL(`/api/backups/${encodeURIComponent(t)}?token=${encodeURIComponent(e)}`);
788
+ }
789
+ }
790
+ class he extends y {
791
+ async getFullList(e) {
792
+ return e = Object.assign({ method: "GET" }, e), this.client.send("/api/crons", e);
793
+ }
794
+ async run(e, t) {
795
+ return t = Object.assign({ method: "POST" }, t), this.client.send(`/api/crons/${encodeURIComponent(e)}`, t).then((() => !0));
796
+ }
797
+ }
798
+ function A(o) {
799
+ return typeof Blob < "u" && o instanceof Blob || typeof File < "u" && o instanceof File || o !== null && typeof o == "object" && o.uri && (typeof navigator < "u" && navigator.product === "ReactNative" || typeof global < "u" && global.HermesInternal);
800
+ }
801
+ function E(o) {
802
+ return o && (o.constructor.name === "FormData" || typeof FormData < "u" && o instanceof FormData);
803
+ }
804
+ function _(o) {
805
+ for (const e in o) {
806
+ const t = Array.isArray(o[e]) ? o[e] : [o[e]];
807
+ for (const s of t) if (A(s)) return !0;
808
+ }
809
+ return !1;
810
+ }
811
+ const ue = /^[\-\.\d]+$/;
812
+ function B(o) {
813
+ if (typeof o != "string") return o;
814
+ if (o == "true") return !0;
815
+ if (o == "false") return !1;
816
+ if ((o[0] === "-" || o[0] >= "0" && o[0] <= "9") && ue.test(o)) {
817
+ let e = +o;
818
+ if ("" + e === o) return e;
819
+ }
820
+ return o;
821
+ }
822
+ class de extends y {
823
+ constructor() {
824
+ super(...arguments), this.requests = [], this.subs = {};
825
+ }
826
+ collection(e) {
827
+ return this.subs[e] || (this.subs[e] = new pe(this.requests, e)), this.subs[e];
828
+ }
829
+ async send(e) {
830
+ const t = new FormData(), s = [];
831
+ for (let i = 0; i < this.requests.length; i++) {
832
+ const n = this.requests[i];
833
+ if (s.push({ method: n.method, url: n.url, headers: n.headers, body: n.json }), n.files) for (let r in n.files) {
834
+ const c = n.files[r] || [];
835
+ for (let a of c) t.append("requests." + i + "." + r, a);
836
+ }
837
+ }
838
+ return t.append("@jsonPayload", JSON.stringify({ requests: s })), e = Object.assign({ method: "POST", body: t }, e), this.client.send("/api/batch", e);
839
+ }
840
+ }
841
+ class pe {
842
+ constructor(e, t) {
843
+ this.requests = [], this.requests = e, this.collectionIdOrName = t;
844
+ }
845
+ upsert(e, t) {
846
+ t = Object.assign({ body: e || {} }, t);
847
+ const s = { method: "PUT", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records" };
848
+ this.prepareRequest(s, t), this.requests.push(s);
849
+ }
850
+ create(e, t) {
851
+ t = Object.assign({ body: e || {} }, t);
852
+ const s = { method: "POST", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records" };
853
+ this.prepareRequest(s, t), this.requests.push(s);
854
+ }
855
+ update(e, t, s) {
856
+ s = Object.assign({ body: t || {} }, s);
857
+ const i = { method: "PATCH", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records/" + encodeURIComponent(e) };
858
+ this.prepareRequest(i, s), this.requests.push(i);
859
+ }
860
+ delete(e, t) {
861
+ t = Object.assign({}, t);
862
+ const s = { method: "DELETE", url: "/api/collections/" + encodeURIComponent(this.collectionIdOrName) + "/records/" + encodeURIComponent(e) };
863
+ this.prepareRequest(s, t), this.requests.push(s);
864
+ }
865
+ prepareRequest(e, t) {
866
+ if (U(t), e.headers = t.headers, e.json = {}, e.files = {}, t.query !== void 0) {
867
+ const i = V(t.query);
868
+ i && (e.url += (e.url.includes("?") ? "&" : "?") + i);
869
+ }
870
+ let s = t.body;
871
+ E(s) && (s = (function(n) {
872
+ let r = {};
873
+ return n.forEach(((c, a) => {
874
+ if (a === "@jsonPayload" && typeof c == "string") try {
875
+ let l = JSON.parse(c);
876
+ Object.assign(r, l);
877
+ } catch (l) {
878
+ console.warn("@jsonPayload error:", l);
879
+ }
880
+ else r[a] !== void 0 ? (Array.isArray(r[a]) || (r[a] = [r[a]]), r[a].push(B(c))) : r[a] = B(c);
881
+ })), r;
882
+ })(s));
883
+ for (const i in s) {
884
+ const n = s[i];
885
+ if (A(n)) e.files[i] = e.files[i] || [], e.files[i].push(n);
886
+ else if (Array.isArray(n)) {
887
+ const r = [], c = [];
888
+ for (const a of n) A(a) ? r.push(a) : c.push(a);
889
+ if (r.length > 0 && r.length == n.length) {
890
+ e.files[i] = e.files[i] || [];
891
+ for (let a of r) e.files[i].push(a);
892
+ } else if (e.json[i] = c, r.length > 0) {
893
+ let a = i;
894
+ i.startsWith("+") || i.endsWith("+") || (a += "+"), e.files[a] = e.files[a] || [];
895
+ for (let l of r) e.files[a].push(l);
896
+ }
897
+ } else e.json[i] = n;
898
+ }
899
+ }
900
+ }
901
+ class M {
902
+ get baseUrl() {
903
+ return this.baseURL;
904
+ }
905
+ set baseUrl(e) {
906
+ this.baseURL = e;
907
+ }
908
+ constructor(e = "/", t, s = "en-US") {
909
+ this.cancelControllers = {}, this.recordServices = {}, this.enableAutoCancellation = !0, this.baseURL = e, this.lang = s, t ? this.authStore = t : typeof window < "u" && window.Deno ? this.authStore = new q() : this.authStore = new ee(), this.collections = new re(this), this.files = new ae(this), this.logs = new oe(this), this.settings = new te(this), this.realtime = new W(this), this.health = new ce(this), this.backups = new le(this), this.crons = new he(this);
910
+ }
911
+ get admins() {
912
+ return this.collection("_superusers");
913
+ }
914
+ createBatch() {
915
+ return new de(this);
916
+ }
917
+ collection(e) {
918
+ return this.recordServices[e] || (this.recordServices[e] = new ne(this, e)), this.recordServices[e];
919
+ }
920
+ autoCancellation(e) {
921
+ return this.enableAutoCancellation = !!e, this;
922
+ }
923
+ cancelRequest(e) {
924
+ return this.cancelControllers[e] && (this.cancelControllers[e].abort(), delete this.cancelControllers[e]), this;
925
+ }
926
+ cancelAllRequests() {
927
+ for (let e in this.cancelControllers) this.cancelControllers[e].abort();
928
+ return this.cancelControllers = {}, this;
929
+ }
930
+ filter(e, t) {
931
+ if (!t) return e;
932
+ for (let s in t) {
933
+ let i = t[s];
934
+ switch (typeof i) {
935
+ case "boolean":
936
+ case "number":
937
+ i = "" + i;
938
+ break;
939
+ case "string":
940
+ i = "'" + i.replace(/'/g, "\\'") + "'";
941
+ break;
942
+ default:
943
+ i = i === null ? "null" : i instanceof Date ? "'" + i.toISOString().replace("T", " ") + "'" : "'" + JSON.stringify(i).replace(/'/g, "\\'") + "'";
944
+ }
945
+ e = e.replaceAll("{:" + s + "}", i);
946
+ }
947
+ return e;
948
+ }
949
+ getFileUrl(e, t, s = {}) {
950
+ return console.warn("Please replace pb.getFileUrl() with pb.files.getURL()"), this.files.getURL(e, t, s);
951
+ }
952
+ buildUrl(e) {
953
+ return console.warn("Please replace pb.buildUrl() with pb.buildURL()"), this.buildURL(e);
954
+ }
955
+ buildURL(e) {
956
+ var s;
957
+ let t = this.baseURL;
958
+ return typeof window > "u" || !window.location || t.startsWith("https://") || t.startsWith("http://") || (t = (s = window.location.origin) != null && s.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;
959
+ }
960
+ async send(e, t) {
961
+ t = this.initSendOptions(e, t);
962
+ let s = this.buildURL(e);
963
+ if (this.beforeSend) {
964
+ const i = Object.assign({}, await this.beforeSend(s, t));
965
+ i.url !== void 0 || i.options !== void 0 ? (s = i.url || s, t = i.options || t) : Object.keys(i).length && (t = i, console != null && console.warn && console.warn("Deprecated format of beforeSend return: please use `return { url, options }`, instead of `return options`."));
966
+ }
967
+ if (t.query !== void 0) {
968
+ const i = V(t.query);
969
+ i && (s += (s.includes("?") ? "&" : "?") + i), delete t.query;
970
+ }
971
+ return this.getHeader(t.headers, "Content-Type") == "application/json" && t.body && typeof t.body != "string" && (t.body = JSON.stringify(t.body)), (t.fetch || fetch)(s, t).then((async (i) => {
972
+ let n = {};
973
+ try {
974
+ n = await i.json();
975
+ } catch {
976
+ }
977
+ if (this.afterSend && (n = await this.afterSend(i, n, t)), i.status >= 400) throw new f({ url: i.url, status: i.status, data: n });
978
+ return n;
979
+ })).catch(((i) => {
980
+ throw new f(i);
981
+ }));
982
+ }
983
+ initSendOptions(e, t) {
984
+ if ((t = Object.assign({ method: "GET" }, t)).body = (function(i) {
985
+ if (typeof FormData > "u" || i === void 0 || typeof i != "object" || i === null || E(i) || !_(i)) return i;
986
+ const n = new FormData();
987
+ for (const r in i) {
988
+ const c = i[r];
989
+ if (typeof c != "object" || _({ data: c })) {
990
+ const a = Array.isArray(c) ? c : [c];
991
+ for (let l of a) n.append(r, l);
992
+ } else {
993
+ let a = {};
994
+ a[r] = c, n.append("@jsonPayload", JSON.stringify(a));
995
+ }
996
+ }
997
+ return n;
998
+ })(t.body), U(t), t.query = Object.assign({}, t.params, t.query), t.requestKey === void 0 && (t.$autoCancel === !1 || t.query.$autoCancel === !1 ? 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, this.getHeader(t.headers, "Content-Type") !== null || E(t.body) || (t.headers = Object.assign({}, t.headers, { "Content-Type": "application/json" })), this.getHeader(t.headers, "Accept-Language") === null && (t.headers = Object.assign({}, t.headers, { "Accept-Language": this.lang })), this.authStore.token && this.getHeader(t.headers, "Authorization") === null && (t.headers = Object.assign({}, t.headers, { Authorization: this.authStore.token })), this.enableAutoCancellation && t.requestKey !== null) {
999
+ const s = t.requestKey || (t.method || "GET") + e;
1000
+ delete t.requestKey, this.cancelRequest(s);
1001
+ const i = new AbortController();
1002
+ this.cancelControllers[s] = i, t.signal = i.signal;
1003
+ }
1004
+ return t;
1005
+ }
1006
+ getHeader(e, t) {
1007
+ e = e || {}, t = t.toLowerCase();
1008
+ for (let s in e) if (s.toLowerCase() == t) return e[s];
1009
+ return null;
1010
+ }
1011
+ }
1012
+ class Oe {
1013
+ constructor(e) {
1014
+ u(this, "client");
1015
+ u(this, "product");
1016
+ u(this, "collection");
1017
+ u(this, "cart");
1018
+ u(this, "checkout");
1019
+ u(this, "payment");
1020
+ u(this, "order");
1021
+ u(this, "auth");
1022
+ this.client = new M(e.baseUrl), this.client.autoCancellation(!1), this.product = new fe(this.client, e), this.collection = new be(this.client, e), this.cart = new ge(this.client, e), this.checkout = new me(this.client, e), this.payment = new ye(this.client, e), this.order = new we(this.client, e), this.auth = new Se(this.client, e);
1023
+ }
1024
+ getFileURL(e, t, s) {
1025
+ return this.client.files.getURL(e, t, s);
1026
+ }
1027
+ }
1028
+ class C {
1029
+ constructor(e, t) {
1030
+ this.client = e, this.config = t;
1031
+ }
1032
+ businessFilter() {
1033
+ return `business.handle = "${this.config.business}"`;
1034
+ }
1035
+ buildFilter(...e) {
1036
+ return [this.businessFilter(), ...e].filter(Boolean).join(" && ");
1037
+ }
1038
+ getBusiness() {
1039
+ return this.client.collection(d.Businesses).getFirstListItem(`handle = "${this.config.business}"`);
1040
+ }
1041
+ }
1042
+ class fe extends C {
1043
+ constructor(t, s) {
1044
+ super(t, s);
1045
+ u(this, "getList", async ({
1046
+ page: t = 1,
1047
+ limit: s = 20,
1048
+ options: i = {}
1049
+ }) => {
1050
+ const { filter: n, ...r } = i;
1051
+ return await this.client.collection(d.ProductsView).getList(t, s, {
1052
+ filter: this.buildFilter(n, 'status = "active"'),
1053
+ expand: "business,images",
1054
+ ...r
1055
+ });
1056
+ });
1057
+ u(this, "getByHandle", async ({
1058
+ handle: t,
1059
+ options: s
1060
+ }) => await this.client.collection(d.ProductsView).getFirstListItem(
1061
+ this.buildFilter(`handle = "${t}"`),
1062
+ {
1063
+ expand: "business,images",
1064
+ ...s
1065
+ }
1066
+ ));
1067
+ }
1068
+ }
1069
+ class be extends C {
1070
+ constructor(t, s) {
1071
+ super(t, s);
1072
+ u(this, "getList", async ({
1073
+ page: t = 1,
1074
+ limit: s = 20,
1075
+ options: i = {}
1076
+ }) => {
1077
+ const { filter: n, ...r } = i;
1078
+ return await this.client.collection(d.ProductCollections).getList(t, s, {
1079
+ filter: this.buildFilter(n),
1080
+ ...r
1081
+ });
1082
+ });
1083
+ u(this, "getByHandle", async ({
1084
+ handle: t,
1085
+ options: s
1086
+ }) => await this.client.collection(d.ProductCollections).getFirstListItem(
1087
+ this.buildFilter(`handle = "${t}"`),
1088
+ s
1089
+ ));
1090
+ }
1091
+ }
1092
+ class ge extends C {
1093
+ constructor(t, s) {
1094
+ super(t, s);
1095
+ u(this, "create", async () => {
1096
+ const t = await this.getBusiness();
1097
+ return await this.client.collection(d.Carts).create({ business: t.id });
1098
+ });
1099
+ u(this, "getById", async ({
1100
+ id: t,
1101
+ options: s
1102
+ }) => await this.client.collection(d.Carts).getOne(t, {
1103
+ expand: "shippingAddress,billingAddress",
1104
+ ...s
1105
+ }));
1106
+ u(this, "getCartItems", async ({
1107
+ cartId: t,
1108
+ options: s = {}
1109
+ }) => {
1110
+ const { filter: i, expand: n, ...r } = s;
1111
+ return await this.client.collection(d.CartItems).getFullList({
1112
+ filter: `cart = "${t}"`,
1113
+ expand: "variant,product.images",
1114
+ ...r
1115
+ });
1116
+ });
1117
+ u(this, "addToCart", async (t) => await this.client.collection(d.CartItems).create(t));
1118
+ u(this, "updateItem", async (t) => this.client.collection(d.CartItems).update(t.cartItemId, { quantity: t.quantity }));
1119
+ u(this, "removeItem", async (t) => this.client.collection(d.CartItems).delete(t.cartItemId));
1120
+ u(this, "complete", async (t) => await this.client.send(
1121
+ `/api/carts/${t.cartId}/complete`,
1122
+ {
1123
+ method: "POST"
1124
+ }
1125
+ ));
1126
+ }
1127
+ async saveCartAddress(t) {
1128
+ return this.client.send(`/api/carts/${t.cartId}/address`, {
1129
+ method: "POST",
1130
+ body: t
1131
+ });
1132
+ }
1133
+ }
1134
+ class me extends C {
1135
+ constructor(e, t) {
1136
+ super(e, t);
1137
+ }
1138
+ }
1139
+ class ye extends C {
1140
+ constructor(e, t) {
1141
+ super(e, t);
1142
+ }
1143
+ async initialize(e) {
1144
+ const t = await this.getBusiness();
1145
+ return this.client.send("/api/orders/payments/initialize", {
1146
+ method: "POST",
1147
+ body: { business: t.id, order: e.orderId }
1148
+ });
1149
+ }
1150
+ async verify(e) {
1151
+ const t = await this.getBusiness();
1152
+ return this.client.send("/api/orders/payments/verify", {
1153
+ method: "POST",
1154
+ body: { reference: e.reference, business: t.id }
1155
+ });
1156
+ }
1157
+ }
1158
+ class we extends C {
1159
+ constructor(e, t) {
1160
+ super(e, t);
1161
+ }
1162
+ async getList({
1163
+ page: e = 1,
1164
+ limit: t = 20,
1165
+ options: s = {}
1166
+ }) {
1167
+ var c;
1168
+ if (!this.client.authStore.isValid)
1169
+ return {
1170
+ page: 0,
1171
+ items: [],
1172
+ perPage: t,
1173
+ totalItems: 0,
1174
+ totalPages: 0
1175
+ };
1176
+ const i = (c = this.client.authStore.record) == null ? void 0 : c.id, { filter: n, ...r } = s;
1177
+ return this.client.collection(d.Orders).getList(e, t, {
1178
+ filter: this.buildFilter(`customer = "${i}"`, n),
1179
+ ...r
1180
+ });
1181
+ }
1182
+ async getById({ id: e, options: t }) {
1183
+ return await this.client.collection(d.OrdersView).getOne(e, {
1184
+ expand: "customer,shippingAddress,billingAddress",
1185
+ ...t
1186
+ });
1187
+ }
1188
+ async getOrderItems({
1189
+ id: e,
1190
+ options: t
1191
+ }) {
1192
+ return this.client.collection(d.OrderItems).getFullList({
1193
+ filter: `order = "${e}"`,
1194
+ expand: "product.images,variant.product",
1195
+ ...t
1196
+ });
1197
+ }
1198
+ }
1199
+ class Se extends C {
1200
+ constructor(e, t) {
1201
+ super(e, t);
1202
+ }
1203
+ async refresh() {
1204
+ if (!this.client.authStore.isValid) return null;
1205
+ const e = await this.client.collection(d.Customers).authRefresh(), t = await this.client.collection(d.CustomersView).getFirstListItem(this.buildFilter(`customer = "${e.record.id}"`));
1206
+ return { ...e, customer: t };
1207
+ }
1208
+ async requestOTP(e) {
1209
+ return this.client.collection(d.Customers).requestOTP(e.email);
1210
+ }
1211
+ async authWithOTP(e) {
1212
+ const t = await this.getBusiness();
1213
+ return this.client.collection(d.Customers).authWithOTP(e.otpId, e.code, { query: { business: t.id } });
1214
+ }
1215
+ async logout() {
1216
+ return this.client.authStore.clear();
1217
+ }
1218
+ }
1219
+ export {
1220
+ Oe as Cartive
1221
+ };
@@ -0,0 +1,5 @@
1
+ export type Config = {
2
+ baseUrl: string;
3
+ business: string;
4
+ apiKey?: string;
5
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cartive/js-sdk",
3
3
  "private": false,
4
- "version": "0.0.5",
4
+ "version": "0.0.6",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"