spaps-sdk 1.0.1 → 1.1.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.mjs CHANGED
@@ -1,909 +1,443 @@
1
- // types.ts
2
- var SweetPotatoAPIError = class extends Error {
3
- constructor(message, code, status, details) {
4
- super(message);
5
- this.name = "SweetPotatoAPIError";
6
- if (code !== void 0) this.code = code;
7
- if (status !== void 0) this.status = status;
8
- if (details !== void 0) this.details = details;
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
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 });
9
17
  }
18
+ return to;
10
19
  };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
11
21
 
12
- // client.ts
13
- function detectLocalEnvironment() {
14
- var _a;
15
- if (typeof process !== "undefined" && process.env) {
16
- if (process.env.NODE_ENV === "development" || process.env.SPAPS_LOCAL_MODE === "true") {
22
+ // src/permissions.ts
23
+ var permissions_exports = {};
24
+ __export(permissions_exports, {
25
+ DEFAULT_ADMIN_ACCOUNTS: () => DEFAULT_ADMIN_ACCOUNTS,
26
+ PermissionChecker: () => PermissionChecker,
27
+ canAccessAdmin: () => canAccessAdmin,
28
+ createPermissionChecker: () => createPermissionChecker,
29
+ defaultPermissionChecker: () => defaultPermissionChecker,
30
+ getRoleAwareErrorMessage: () => getRoleAwareErrorMessage,
31
+ getUserDisplay: () => getUserDisplay,
32
+ getUserRole: () => getUserRole,
33
+ hasPermission: () => hasPermission,
34
+ isAdminAccount: () => isAdminAccount
35
+ });
36
+ function isAdminAccount(identifier, customAdmins = []) {
37
+ if (!identifier) return false;
38
+ const normalized = identifier.toLowerCase();
39
+ if (normalized === DEFAULT_ADMIN_ACCOUNTS.email.toLowerCase() || normalized === DEFAULT_ADMIN_ACCOUNTS.wallets.ethereum.toLowerCase() || normalized === DEFAULT_ADMIN_ACCOUNTS.wallets.solana.toLowerCase()) {
40
+ return true;
41
+ }
42
+ return customAdmins.some((admin) => {
43
+ if (typeof admin === "string") {
44
+ return admin.toLowerCase() === normalized;
45
+ }
46
+ if ("email" in admin && admin.email.toLowerCase() === normalized) {
17
47
  return true;
18
48
  }
49
+ if ("wallets" in admin) {
50
+ return Object.values(admin.wallets).some(
51
+ (wallet) => wallet.toLowerCase() === normalized
52
+ );
53
+ }
54
+ return false;
55
+ });
56
+ }
57
+ function getUserRole(identifier, customAdmins = []) {
58
+ if (!identifier) return "guest";
59
+ if (isAdminAccount(identifier, customAdmins)) {
60
+ return "admin";
19
61
  }
20
- if (typeof globalThis !== "undefined" && ((_a = globalThis.window) == null ? void 0 : _a.location)) {
21
- const hostname = globalThis.window.location.hostname;
22
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname.endsWith(".local");
62
+ return "user";
63
+ }
64
+ function hasPermission(user, requiredPermissions, customAdmins = []) {
65
+ if (!user) return false;
66
+ const identifier = user.email || user.wallet_address;
67
+ const userRole = getUserRole(identifier, customAdmins);
68
+ if (userRole === "admin") {
69
+ return true;
70
+ }
71
+ if (Array.isArray(requiredPermissions)) {
72
+ return requiredPermissions.every(
73
+ (permission) => user.permissions?.includes(permission)
74
+ );
23
75
  }
24
- return false;
76
+ return user.permissions?.includes(requiredPermissions) || false;
25
77
  }
26
- var HttpClient = class {
27
- constructor(config) {
28
- var _a, _b;
29
- const localMode = (_b = config.localMode) != null ? _b : ((_a = config.apiUrl) == null ? void 0 : _a.includes("localhost")) || detectLocalEnvironment();
30
- this.config = {
31
- timeout: 3e4,
32
- retries: 3,
33
- ...config,
34
- localMode
78
+ function canAccessAdmin(user, customAdmins = []) {
79
+ if (!user) {
80
+ return {
81
+ allowed: false,
82
+ reason: "Authentication required",
83
+ userRole: "guest",
84
+ requiredRole: "admin"
35
85
  };
36
- this.isLocalMode = this.config.localMode || false;
37
- this.accessToken = void 0;
38
- if (this.isLocalMode && typeof console !== "undefined") {
39
- console.log("[SPAPS SDK] Running in local development mode - authentication will be automatic");
40
- }
41
86
  }
42
- /**
43
- * Set the access token for authenticated requests
44
- */
45
- setAccessToken(token) {
46
- this.accessToken = token;
47
- }
48
- /**
49
- * Clear the access token
50
- */
51
- clearAccessToken() {
52
- this.accessToken = void 0;
87
+ const identifier = user.email || user.wallet_address;
88
+ const userRole = getUserRole(identifier, customAdmins);
89
+ const isAdmin = userRole === "admin";
90
+ return {
91
+ allowed: isAdmin,
92
+ reason: isAdmin ? void 0 : "Admin privileges required",
93
+ userRole,
94
+ requiredRole: "admin"
95
+ };
96
+ }
97
+ function getRoleAwareErrorMessage(requiredRole, userRole, action = "perform this action") {
98
+ const messages = {
99
+ admin: {
100
+ user: `\u{1F512} Admin privileges required to ${action}. Please authenticate with an admin account.`,
101
+ guest: `\u{1F510} Authentication required. Please sign in with an admin account to ${action}.`
102
+ },
103
+ user: {
104
+ guest: `\u{1F510} Authentication required. Please sign in to ${action}.`
105
+ }
106
+ };
107
+ return messages[requiredRole]?.[userRole] || `Access denied. Required role: ${requiredRole}, current role: ${userRole}`;
108
+ }
109
+ function getUserDisplay(user, customAdmins = []) {
110
+ if (!user) {
111
+ return {
112
+ displayName: "Guest",
113
+ role: "guest",
114
+ badge: null,
115
+ isAdmin: false
116
+ };
53
117
  }
54
- /**
55
- * Make an HTTP request with automatic retries and error handling
56
- */
57
- async request(options) {
58
- var _a, _b, _c, _d;
59
- const { method, url, data, headers = {}, requiresAuth = false } = options;
60
- const fullUrl = url.startsWith("http") ? url : `${this.config.apiUrl.replace(/\/$/, "")}${url}`;
61
- const requestHeaders = {
62
- "Content-Type": "application/json",
63
- ...headers
118
+ const identifier = user.email || user.wallet_address;
119
+ const role = getUserRole(identifier, customAdmins);
120
+ const isAdmin = role === "admin";
121
+ return {
122
+ displayName: user.email || `${user.wallet_address?.slice(0, 6)}...${user.wallet_address?.slice(-4)}` || "User",
123
+ role,
124
+ badge: isAdmin ? "\u{1F451} Admin" : null,
125
+ isAdmin
126
+ };
127
+ }
128
+ function createPermissionChecker(customAdmins = []) {
129
+ return new PermissionChecker(customAdmins);
130
+ }
131
+ var DEFAULT_ADMIN_ACCOUNTS, PermissionChecker, defaultPermissionChecker;
132
+ var init_permissions = __esm({
133
+ "src/permissions.ts"() {
134
+ "use strict";
135
+ DEFAULT_ADMIN_ACCOUNTS = {
136
+ email: "buildooor@gmail.com",
137
+ wallets: {
138
+ ethereum: "0xa72bb7CeF1e4B2Cc144373d8dE0Add7CCc8DF4Ba",
139
+ solana: "HVEbdiYU3Rr34NHBSgKs7q8cvdTeZLqNL77Z1FB2vjLy"
140
+ }
64
141
  };
65
- if (this.config.apiKey) {
66
- requestHeaders["x-api-key"] = this.config.apiKey;
67
- } else if (this.isLocalMode) {
68
- requestHeaders["x-local-mode"] = "true";
69
- } else {
70
- console.warn("[SPAPS SDK] No API key provided and not in local mode");
71
- }
72
- if (requiresAuth && this.accessToken) {
73
- requestHeaders["Authorization"] = `Bearer ${this.accessToken}`;
74
- }
75
- let lastError = null;
76
- for (let attempt = 1; attempt <= this.config.retries; attempt++) {
77
- try {
78
- const controller = new AbortController();
79
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
80
- const requestInit = {
81
- method,
82
- headers: requestHeaders,
83
- signal: controller.signal
84
- };
85
- if (data && (method === "POST" || method === "PUT" || method === "PATCH")) {
86
- requestInit.body = JSON.stringify(data);
87
- }
88
- const response = await fetch(fullUrl, requestInit);
89
- clearTimeout(timeoutId);
90
- if (!response) {
91
- throw new Error("No response received");
92
- }
93
- let responseData;
94
- const contentType = (_a = response.headers) == null ? void 0 : _a.get("content-type");
95
- if (contentType && contentType.includes("application/json")) {
96
- responseData = await response.json();
97
- } else {
98
- throw new SweetPotatoAPIError(
99
- "Invalid response format: expected JSON",
100
- "INVALID_RESPONSE_FORMAT",
101
- response.status
102
- );
142
+ PermissionChecker = class {
143
+ customAdmins;
144
+ constructor(customAdmins = []) {
145
+ this.customAdmins = customAdmins;
146
+ }
147
+ isAdmin(identifier) {
148
+ return isAdminAccount(identifier, this.customAdmins);
149
+ }
150
+ getRole(identifier) {
151
+ return getUserRole(identifier, this.customAdmins);
152
+ }
153
+ hasPermission(user, permissions) {
154
+ return hasPermission(user, permissions, this.customAdmins);
155
+ }
156
+ canAccessAdmin(user) {
157
+ return canAccessAdmin(user, this.customAdmins);
158
+ }
159
+ getErrorMessage(requiredRole, userRole, action) {
160
+ return getRoleAwareErrorMessage(requiredRole, userRole, action);
161
+ }
162
+ getUserDisplay(user) {
163
+ return getUserDisplay(user, this.customAdmins);
164
+ }
165
+ // Convenience methods
166
+ requiresAuth(user) {
167
+ return !user;
168
+ }
169
+ requiresAdmin(user) {
170
+ return !this.canAccessAdmin(user).allowed;
171
+ }
172
+ addCustomAdmin(admin) {
173
+ this.customAdmins.push(admin);
174
+ }
175
+ removeCustomAdmin(admin) {
176
+ this.customAdmins = this.customAdmins.filter((a) => a !== admin);
177
+ }
178
+ };
179
+ defaultPermissionChecker = new PermissionChecker();
180
+ }
181
+ });
182
+
183
+ // src/index.ts
184
+ init_permissions();
185
+ import axios from "axios";
186
+ var SPAPSClient = class {
187
+ client;
188
+ apiKey;
189
+ accessToken;
190
+ refreshToken;
191
+ _isLocalMode = false;
192
+ // Admin namespace for cleaner API
193
+ admin = {
194
+ createProduct: (productData) => this.createProduct(productData),
195
+ updateProduct: (productId, updates) => this.updateProduct(productId, updates),
196
+ deleteProduct: (productId) => this.deleteProduct(productId),
197
+ createPrice: (priceData) => this.createPrice(priceData),
198
+ syncProducts: () => this.syncProducts(),
199
+ getProducts: () => this.getProducts()
200
+ };
201
+ constructor(config = {}) {
202
+ const apiUrl = config.apiUrl || process.env.SPAPS_API_URL || process.env.NEXT_PUBLIC_SPAPS_API_URL;
203
+ if (!apiUrl || apiUrl.includes("localhost") || apiUrl.includes("127.0.0.1")) {
204
+ this._isLocalMode = true;
205
+ this.client = axios.create({
206
+ baseURL: apiUrl || "http://localhost:3300",
207
+ timeout: config.timeout || 1e4,
208
+ headers: {
209
+ "Content-Type": "application/json"
103
210
  }
104
- if (!(response == null ? void 0 : response.ok)) {
105
- throw new SweetPotatoAPIError(
106
- ((_b = responseData.error) == null ? void 0 : _b.message) || `HTTP ${response == null ? void 0 : response.status}: ${response == null ? void 0 : response.statusText}`,
107
- ((_c = responseData.error) == null ? void 0 : _c.code) || "HTTP_ERROR",
108
- response == null ? void 0 : response.status,
109
- (_d = responseData.error) == null ? void 0 : _d.details
110
- );
211
+ });
212
+ } else {
213
+ if (!config.apiKey && !process.env.SPAPS_API_KEY) {
214
+ console.warn("\u26A0\uFE0F SPAPS: No API key provided. Some features may not work.");
215
+ }
216
+ this.apiKey = config.apiKey || process.env.SPAPS_API_KEY;
217
+ this.client = axios.create({
218
+ baseURL: apiUrl,
219
+ timeout: config.timeout || 1e4,
220
+ headers: {
221
+ "Content-Type": "application/json",
222
+ ...this.apiKey && { "X-API-Key": this.apiKey }
111
223
  }
112
- return responseData;
113
- } catch (error) {
114
- lastError = error;
115
- if (error instanceof SweetPotatoAPIError) {
116
- if (error.status && error.status >= 400 && error.status < 500) {
117
- throw error;
224
+ });
225
+ }
226
+ this.client.interceptors.request.use((config2) => {
227
+ if (this.accessToken && !config2.headers.Authorization) {
228
+ config2.headers.Authorization = `Bearer ${this.accessToken}`;
229
+ }
230
+ return config2;
231
+ });
232
+ this.client.interceptors.response.use(
233
+ (response) => response,
234
+ async (error) => {
235
+ if (error.response?.status === 401 && this.refreshToken) {
236
+ try {
237
+ const { data } = await this.refresh(this.refreshToken);
238
+ this.accessToken = data.access_token;
239
+ this.refreshToken = data.refresh_token;
240
+ if (error.config) {
241
+ error.config.headers.Authorization = `Bearer ${this.accessToken}`;
242
+ return this.client.request(error.config);
243
+ }
244
+ } catch (refreshError) {
245
+ this.accessToken = void 0;
246
+ this.refreshToken = void 0;
118
247
  }
119
248
  }
120
- if (attempt === this.config.retries) {
121
- break;
122
- }
123
- const delayMs = Math.min(1e3 * Math.pow(2, attempt - 1), 1e4);
124
- await new Promise((resolve) => setTimeout(resolve, delayMs));
249
+ return Promise.reject(error);
125
250
  }
126
- }
127
- if (lastError instanceof SweetPotatoAPIError) {
128
- throw lastError;
129
- }
130
- throw new SweetPotatoAPIError(
131
- (lastError == null ? void 0 : lastError.message) || "Request failed after all retries",
132
- "REQUEST_FAILED",
133
- void 0,
134
- { originalError: lastError }
135
251
  );
136
252
  }
137
- /**
138
- * Convenience method for GET requests
139
- */
140
- async get(url, requiresAuth = false) {
141
- return this.request({
142
- method: "GET",
143
- url,
144
- requiresAuth
145
- });
146
- }
147
- /**
148
- * Convenience method for POST requests
149
- */
150
- async post(url, data, requiresAuth = false) {
151
- return this.request({
152
- method: "POST",
153
- url,
154
- data,
155
- requiresAuth
253
+ // Authentication Methods
254
+ async login(email, password) {
255
+ const response = await this.client.post("/api/auth/login", {
256
+ email,
257
+ password
156
258
  });
157
- }
158
- /**
159
- * Convenience method for PUT requests
160
- */
161
- async put(url, data, requiresAuth = false) {
162
- return this.request({
163
- method: "PUT",
164
- url,
165
- data,
166
- requiresAuth
259
+ this.accessToken = response.data.access_token;
260
+ this.refreshToken = response.data.refresh_token;
261
+ return response;
262
+ }
263
+ async register(email, password) {
264
+ const response = await this.client.post("/api/auth/register", {
265
+ email,
266
+ password
167
267
  });
268
+ this.accessToken = response.data.access_token;
269
+ this.refreshToken = response.data.refresh_token;
270
+ return response;
168
271
  }
169
- /**
170
- * Convenience method for DELETE requests
171
- */
172
- async delete(url, requiresAuth = false) {
173
- return this.request({
174
- method: "DELETE",
175
- url,
176
- requiresAuth
177
- });
178
- }
179
- };
180
-
181
- // auth.ts
182
- var AuthService = class {
183
- constructor(httpClient) {
184
- this.httpClient = httpClient;
185
- }
186
- /**
187
- * Get a nonce for wallet signature
188
- * @param walletAddress - The wallet address to generate a nonce for
189
- * @returns Promise<NonceResponse>
190
- */
191
- async getNonce(walletAddress) {
192
- var _a;
193
- const response = await this.httpClient.post("/api/auth/nonce", {
194
- wallet_address: walletAddress
195
- });
196
- if (!response.success || !response.data) {
197
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to generate nonce");
198
- }
199
- return response.data;
200
- }
201
- /**
202
- * Sign in with wallet signature
203
- * @param request - Wallet sign-in request data
204
- * @returns Promise<AuthResponse>
205
- */
206
- async signInWithWallet(request) {
207
- var _a;
208
- const response = await this.httpClient.post("/api/auth/wallet-sign-in", request);
209
- if (!response.success || !response.data) {
210
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Wallet sign-in failed");
211
- }
212
- this.httpClient.setAccessToken(response.data.access_token);
213
- return response.data;
214
- }
215
- /**
216
- * Complete wallet authentication flow
217
- * This is a convenience method that combines getNonce and signInWithWallet
218
- * @param walletAddress - The wallet address
219
- * @param signatureFunction - Function that signs the auth message
220
- * @param chainType - Optional chain type (will be auto-detected if not provided)
221
- * @param username - Optional username for new users
222
- * @returns Promise<AuthResponse>
223
- */
224
- async authenticateWallet(walletAddress, signatureFunction, chainType, username) {
225
- const nonceData = await this.getNonce(walletAddress);
226
- const signature = await signatureFunction(nonceData.message);
227
- const request = {
272
+ async walletSignIn(walletAddress, signature, message, chainType = "solana") {
273
+ const response = await this.client.post("/api/auth/wallet-sign-in", {
228
274
  wallet_address: walletAddress,
229
275
  signature,
230
- message: nonceData.message
231
- };
232
- if (chainType) {
233
- request.chain_type = chainType;
234
- }
235
- if (username) {
236
- request.username = username;
237
- }
238
- return this.signInWithWallet(request);
239
- }
240
- /**
241
- * Sign in with email and password
242
- * @param request - Traditional login request data
243
- * @returns Promise<AuthResponse>
244
- */
245
- async signInWithPassword(request) {
246
- var _a;
247
- const response = await this.httpClient.post("/api/auth/login", request);
248
- if (!response.success || !response.data) {
249
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Login failed");
250
- }
251
- this.httpClient.setAccessToken(response.data.access_token);
252
- return response.data;
253
- }
254
- /**
255
- * Request a magic link for email authentication
256
- * @param request - Magic link request data
257
- * @returns Promise<void>
258
- */
259
- async requestMagicLink(request) {
260
- var _a;
261
- const response = await this.httpClient.post("/api/auth/magic-link", request);
262
- if (!response.success) {
263
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to send magic link");
264
- }
276
+ message,
277
+ chain_type: chainType
278
+ });
279
+ this.accessToken = response.data.access_token;
280
+ this.refreshToken = response.data.refresh_token;
281
+ return response;
265
282
  }
266
- /**
267
- * Refresh access token using refresh token
268
- * @param refreshToken - The refresh token
269
- * @returns Promise<TokenPair>
270
- */
271
- async refreshToken(refreshToken) {
272
- var _a;
273
- const response = await this.httpClient.post("/api/auth/refresh", {
274
- refresh_token: refreshToken
283
+ async refresh(refreshToken) {
284
+ const response = await this.client.post("/api/auth/refresh", {
285
+ refresh_token: refreshToken || this.refreshToken
275
286
  });
276
- if (!response.success || !response.data) {
277
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Token refresh failed");
278
- }
279
- this.httpClient.setAccessToken(response.data.access_token);
280
- return response.data;
287
+ this.accessToken = response.data.access_token;
288
+ this.refreshToken = response.data.refresh_token;
289
+ return response;
281
290
  }
282
- /**
283
- * Log out and invalidate tokens
284
- * @returns Promise<void>
285
- */
286
291
  async logout() {
287
- var _a;
288
- try {
289
- const response = await this.httpClient.post("/api/auth/logout", {}, true);
290
- if (!response.success) {
291
- console.warn("Logout API call failed:", ((_a = response.error) == null ? void 0 : _a.message) || "Unknown error");
292
- }
293
- } catch (error) {
294
- console.warn("Logout API call failed:", error);
295
- } finally {
296
- this.httpClient.clearAccessToken();
297
- }
298
- }
299
- /**
300
- * Get current user profile
301
- * @returns Promise<User>
302
- */
303
- async getCurrentUser() {
304
- var _a;
305
- const response = await this.httpClient.get("/api/auth/user", true);
306
- if (!response.success || !response.data) {
307
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to get user profile");
308
- }
309
- return response.data.user;
310
- }
311
- /**
312
- * Check if user is currently authenticated
313
- * @returns boolean
314
- */
315
- isAuthenticated() {
316
- return this.httpClient["accessToken"] !== void 0;
317
- }
318
- /**
319
- * Clear authentication state (useful for client-side logout)
320
- */
321
- clearAuth() {
322
- this.httpClient.clearAccessToken();
323
- }
324
- };
325
-
326
- // payments.ts
327
- var PaymentsService = class {
328
- constructor(httpClient) {
329
- this.httpClient = httpClient;
330
- }
331
- // Checkout Sessions
332
- /**
333
- * Create a new Stripe checkout session
334
- * @param request - Checkout session creation parameters
335
- * @returns Promise<CheckoutSession>
336
- */
337
- async createCheckoutSession(request) {
338
- var _a;
339
- const response = await this.httpClient.post(
340
- "/api/stripe/checkout-sessions",
341
- request,
342
- true
343
- );
344
- if (!response.success || !response.data) {
345
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create checkout session");
346
- }
347
- return response.data;
348
- }
349
- /**
350
- * Retrieve a checkout session by ID
351
- * @param sessionId - The checkout session ID
352
- * @returns Promise<CheckoutSession>
353
- */
354
- async getCheckoutSession(sessionId) {
355
- var _a;
356
- const response = await this.httpClient.get(
357
- `/api/stripe/checkout-sessions/${sessionId}`,
358
- true
359
- );
360
- if (!response.success || !response.data) {
361
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to retrieve checkout session");
362
- }
363
- return response.data;
364
- }
365
- /**
366
- * Expire a checkout session
367
- * @param sessionId - The checkout session ID to expire
368
- * @returns Promise<{id: string, status: string, expired: boolean}>
369
- */
370
- async expireCheckoutSession(sessionId) {
371
- var _a;
372
- const response = await this.httpClient.post(
373
- `/api/stripe/checkout-sessions/${sessionId}/expire`,
374
- {},
375
- true
376
- );
377
- if (!response.success || !response.data) {
378
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to expire checkout session");
379
- }
380
- return response.data;
381
- }
382
- /**
383
- * List checkout sessions for the current user
384
- * @param options - List options (limit, pagination)
385
- * @returns Promise<CheckoutSessionListResponse>
386
- */
387
- async listCheckoutSessions(options = {}) {
388
- var _a;
389
- const params = new URLSearchParams();
390
- if (options.limit) params.append("limit", options.limit.toString());
391
- if (options.starting_after) params.append("starting_after", options.starting_after);
392
- const url = `/api/stripe/checkout-sessions${params.toString() ? `?${params.toString()}` : ""}`;
393
- const response = await this.httpClient.get(url, true);
394
- if (!response.success || !response.data) {
395
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to list checkout sessions");
396
- }
397
- return response.data;
398
- }
399
- // Products
400
- /**
401
- * List available products
402
- * @param request - Product list filters
403
- * @returns Promise<ProductsListResponse>
404
- */
405
- async listProducts(request = {}) {
406
- var _a;
407
- const params = new URLSearchParams();
408
- if (request.category) params.append("category", request.category);
409
- if (request.active !== void 0) params.append("active", request.active.toString());
410
- if (request.limit) params.append("limit", request.limit.toString());
411
- if (request.starting_after) params.append("starting_after", request.starting_after);
412
- const url = `/api/stripe/products${params.toString() ? `?${params.toString()}` : ""}`;
413
- const response = await this.httpClient.get(url, true);
414
- if (!response.success || !response.data) {
415
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to list products");
416
- }
417
- return response.data;
418
- }
419
- /**
420
- * Get a specific product by ID
421
- * @param productId - The product ID
422
- * @param includePrices - Whether to include associated prices (default: true)
423
- * @returns Promise<StripeProduct>
424
- */
425
- async getProduct(productId, includePrices = true) {
426
- var _a;
427
- const params = new URLSearchParams();
428
- if (!includePrices) params.append("include_prices", "false");
429
- const url = `/api/stripe/products/${productId}${params.toString() ? `?${params.toString()}` : ""}`;
430
- const response = await this.httpClient.get(url, true);
431
- if (!response.success || !response.data) {
432
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to retrieve product");
433
- }
434
- return response.data;
435
- }
436
- /**
437
- * Create a new product (Admin only)
438
- * @param request - Product creation parameters
439
- * @returns Promise<StripeProduct>
440
- */
441
- async createProduct(request) {
442
- var _a;
443
- const response = await this.httpClient.post(
444
- "/api/stripe/products",
445
- request,
446
- true
447
- );
448
- if (!response.success || !response.data) {
449
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create product");
450
- }
451
- return response.data;
452
- }
453
- /**
454
- * Update an existing product (Admin only)
455
- * @param productId - The product ID to update
456
- * @param request - Product update parameters
457
- * @returns Promise<StripeProduct>
458
- */
459
- async updateProduct(productId, request) {
460
- var _a;
461
- const response = await this.httpClient.put(
462
- `/api/stripe/products/${productId}`,
463
- request,
464
- true
465
- );
466
- if (!response.success || !response.data) {
467
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to update product");
468
- }
469
- return response.data;
470
- }
471
- /**
472
- * Archive a product (Admin only)
473
- * @param productId - The product ID to archive
474
- * @returns Promise<{id: string, archived: boolean, active: boolean}>
475
- */
476
- async archiveProduct(productId) {
477
- var _a;
478
- const response = await this.httpClient.delete(
479
- `/api/stripe/products/${productId}`,
480
- true
481
- );
482
- if (!response.success || !response.data) {
483
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to archive product");
484
- }
485
- return response.data;
486
- }
487
- /**
488
- * Sync products from Stripe (Admin only)
489
- * @returns Promise<{synced_count: number, message: string}>
490
- */
491
- async syncProducts() {
492
- var _a;
493
- const response = await this.httpClient.post(
494
- "/api/stripe/products/sync",
495
- {},
496
- true
497
- );
498
- if (!response.success || !response.data) {
499
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to sync products");
500
- }
501
- return response.data;
292
+ await this.client.post("/api/auth/logout");
293
+ this.accessToken = void 0;
294
+ this.refreshToken = void 0;
502
295
  }
503
- // Prices
504
- /**
505
- * Create a new price for a product (Admin only)
506
- * @param request - Price creation parameters
507
- * @returns Promise<StripePrice>
508
- */
509
- async createPrice(request) {
510
- var _a;
511
- const response = await this.httpClient.post(
512
- "/api/stripe/prices",
513
- request,
514
- true
515
- );
516
- if (!response.success || !response.data) {
517
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create price");
518
- }
519
- return response.data;
296
+ async getUser() {
297
+ return this.client.get("/api/auth/user");
520
298
  }
521
- // Subscriptions
522
- /**
523
- * Create a new subscription
524
- * @param request - Subscription creation parameters
525
- * @returns Promise<Subscription>
526
- */
527
- async createSubscription(request) {
528
- var _a;
529
- const response = await this.httpClient.post(
530
- "/api/stripe/subscriptions",
531
- request,
532
- true
533
- );
534
- if (!response.success || !response.data) {
535
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create subscription");
536
- }
537
- return response.data;
299
+ // Stripe Methods
300
+ async createCheckoutSession(priceId, successUrl, cancelUrl) {
301
+ return this.client.post("/api/stripe/create-checkout-session", {
302
+ price_id: priceId,
303
+ success_url: successUrl,
304
+ cancel_url: cancelUrl
305
+ });
538
306
  }
539
- /**
540
- * Get a subscription by ID
541
- * @param subscriptionId - The subscription ID
542
- * @returns Promise<Subscription>
543
- */
544
- async getSubscription(subscriptionId) {
545
- var _a;
546
- const response = await this.httpClient.get(
547
- `/api/stripe/subscriptions/${subscriptionId}`,
548
- true
549
- );
550
- if (!response.success || !response.data) {
551
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to retrieve subscription");
552
- }
553
- return response.data;
307
+ async getSubscription() {
308
+ return this.client.get("/api/stripe/subscription");
554
309
  }
555
- /**
556
- * List subscriptions for the current user
557
- * @param options - List options
558
- * @returns Promise<{subscriptions: Subscription[], has_more: boolean}>
559
- */
560
- async listSubscriptions(options = {}) {
561
- var _a;
562
- const params = new URLSearchParams();
563
- if (options.limit) params.append("limit", options.limit.toString());
564
- if (options.starting_after) params.append("starting_after", options.starting_after);
565
- if (options.status) params.append("status", options.status);
566
- const url = `/api/stripe/subscriptions${params.toString() ? `?${params.toString()}` : ""}`;
567
- const response = await this.httpClient.get(url, true);
568
- if (!response.success || !response.data) {
569
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to list subscriptions");
570
- }
571
- return response.data;
310
+ async cancelSubscription() {
311
+ await this.client.delete("/api/stripe/subscription");
572
312
  }
573
- /**
574
- * Cancel a subscription
575
- * @param subscriptionId - The subscription ID to cancel
576
- * @returns Promise<Subscription>
577
- */
578
- async cancelSubscription(subscriptionId) {
579
- var _a;
580
- const response = await this.httpClient.post(
581
- `/api/stripe/subscriptions/${subscriptionId}/cancel`,
582
- {},
583
- true
584
- );
585
- if (!response.success || !response.data) {
586
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to cancel subscription");
587
- }
588
- return response.data;
313
+ // Usage Methods
314
+ async getUsageBalance() {
315
+ return this.client.get("/api/usage/balance");
589
316
  }
590
- /**
591
- * Update a subscription
592
- * @param subscriptionId - The subscription ID to update
593
- * @param request - Update parameters
594
- * @returns Promise<Subscription>
595
- */
596
- async updateSubscription(subscriptionId, request) {
597
- var _a;
598
- const response = await this.httpClient.put(
599
- `/api/stripe/subscriptions/${subscriptionId}`,
600
- request,
601
- true
602
- );
603
- if (!response.success || !response.data) {
604
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to update subscription");
605
- }
606
- return response.data;
317
+ async recordUsage(feature, amount) {
318
+ await this.client.post("/api/usage/record", {
319
+ feature,
320
+ amount
321
+ });
607
322
  }
608
- // Customer Portal
323
+ // Admin Methods (Require admin privileges)
609
324
  /**
610
- * Create a customer portal session
611
- * @param request - Portal session parameters
612
- * @returns Promise<CustomerPortalSession>
325
+ * Create a new Stripe product (Admin required)
613
326
  */
614
- async createCustomerPortalSession(request) {
615
- var _a;
616
- const response = await this.httpClient.post(
617
- "/api/stripe/customer-portal",
618
- request,
619
- true
620
- );
621
- if (!response.success || !response.data) {
622
- throw new Error(((_a = response.error) == null ? void 0 : _a.message) || "Failed to create customer portal session");
327
+ async createProduct(productData) {
328
+ if (!this.accessToken) {
329
+ throw new Error("Authentication required. Please authenticate first.");
623
330
  }
624
- return response.data;
331
+ return this.client.post("/api/stripe/products", productData, {
332
+ headers: {
333
+ "Authorization": `Bearer ${this.accessToken}`
334
+ }
335
+ });
625
336
  }
626
- // Utility Methods
627
337
  /**
628
- * Create a one-time payment checkout session
629
- * Convenience method for simple one-time payments
630
- * @param params - Payment parameters
631
- * @returns Promise<CheckoutSession>
338
+ * Update an existing Stripe product (Admin required)
632
339
  */
633
- async createPaymentCheckout(params) {
634
- const lineItems = [];
635
- if (params.price_id) {
636
- lineItems.push({
637
- price_id: params.price_id,
638
- quantity: params.quantity || 1
639
- });
640
- } else if (params.product_name && params.amount && params.currency) {
641
- lineItems.push({
642
- quantity: params.quantity || 1,
643
- price_data: {
644
- currency: params.currency,
645
- unit_amount: params.amount,
646
- product_data: {
647
- name: params.product_name
648
- }
649
- }
650
- });
651
- } else {
652
- throw new Error("Either price_id or (product_name, amount, currency) must be provided");
340
+ async updateProduct(productId, updates) {
341
+ if (!this.accessToken) {
342
+ throw new Error("Authentication required. Please authenticate first.");
653
343
  }
654
- return this.createCheckoutSession({
655
- mode: "payment",
656
- line_items: lineItems,
657
- success_url: params.success_url,
658
- cancel_url: params.cancel_url,
659
- ...params.metadata && { metadata: params.metadata }
344
+ return this.client.put(`/api/stripe/products/${productId}`, updates, {
345
+ headers: {
346
+ "Authorization": `Bearer ${this.accessToken}`
347
+ }
660
348
  });
661
349
  }
662
350
  /**
663
- * Create a subscription checkout session
664
- * Convenience method for subscription creation
665
- * @param params - Subscription parameters
666
- * @returns Promise<CheckoutSession>
351
+ * Archive (soft delete) a Stripe product (Admin required)
667
352
  */
668
- async createSubscriptionCheckout(params) {
669
- return this.createCheckoutSession({
670
- mode: "subscription",
671
- line_items: [{
672
- price_id: params.price_id,
673
- quantity: 1
674
- }],
675
- success_url: params.success_url,
676
- cancel_url: params.cancel_url,
677
- subscription_data: {
678
- ...params.trial_period_days !== void 0 && { trial_period_days: params.trial_period_days },
679
- ...params.metadata && { metadata: params.metadata }
353
+ async deleteProduct(productId) {
354
+ if (!this.accessToken) {
355
+ throw new Error("Authentication required. Please authenticate first.");
356
+ }
357
+ return this.client.delete(`/api/stripe/products/${productId}`, {
358
+ headers: {
359
+ "Authorization": `Bearer ${this.accessToken}`
680
360
  }
681
361
  });
682
362
  }
683
- };
684
-
685
- // index.ts
686
- var SweetPotatoSDK = class {
687
- constructor(config) {
688
- if (!config.apiUrl) {
689
- throw new Error("apiUrl is required");
690
- }
691
- this.httpClient = new HttpClient(config);
692
- this.auth = new AuthService(this.httpClient);
693
- this.payments = new PaymentsService(this.httpClient);
694
- this.isLocalMode = this.httpClient["isLocalMode"] || false;
695
- if (this.isLocalMode) {
696
- console.log("[SPAPS SDK] Initialized in local development mode");
697
- console.log("[SPAPS SDK] API URL:", config.apiUrl);
698
- console.log("[SPAPS SDK] Authentication will be automatic");
699
- }
700
- }
701
363
  /**
702
- * Set access token for authenticated requests
703
- * @param token - Access token
364
+ * Create a new price for a product (Admin required)
704
365
  */
705
- setAccessToken(token) {
706
- this.httpClient.setAccessToken(token);
707
- }
708
- /**
709
- * Clear access token
710
- */
711
- clearAccessToken() {
712
- this.httpClient.clearAccessToken();
713
- }
714
- /**
715
- * Get SDK configuration
716
- */
717
- getConfig() {
718
- return {
719
- apiUrl: this.httpClient["config"].apiUrl,
720
- timeout: this.httpClient["config"].timeout,
721
- retries: this.httpClient["config"].retries
722
- };
723
- }
724
- /**
725
- * Health check endpoint
726
- * @returns Promise<boolean>
727
- */
728
- async healthCheck() {
729
- try {
730
- const response = await this.httpClient.get("/api/health");
731
- return response.success;
732
- } catch (e) {
733
- return false;
366
+ async createPrice(priceData) {
367
+ if (!this.accessToken) {
368
+ throw new Error("Authentication required. Please authenticate first.");
734
369
  }
735
- }
736
- /**
737
- * Make a custom authenticated request
738
- * This allows advanced users to make direct API calls not covered by the SDK
739
- */
740
- async request(method, url, data, requiresAuth = false) {
741
- return this.httpClient.request({
742
- method,
743
- url,
744
- data,
745
- requiresAuth
370
+ return this.client.post("/api/stripe/prices", priceData, {
371
+ headers: {
372
+ "Authorization": `Bearer ${this.accessToken}`
373
+ }
746
374
  });
747
375
  }
748
- };
749
- function createSweetPotatoSDK(config) {
750
- return new SweetPotatoSDK(config);
751
- }
752
- var _TokenManager = class _TokenManager {
753
376
  /**
754
- * Get localStorage instance (browser or test environment)
377
+ * Sync all products from Stripe to local database (Super Admin required)
755
378
  */
756
- static getStorage() {
757
- var _a, _b;
758
- if (typeof globalThis !== "undefined" && globalThis.localStorage) {
759
- return globalThis.localStorage;
760
- }
761
- if (typeof globalThis !== "undefined" && ((_a = globalThis.window) == null ? void 0 : _a.localStorage)) {
762
- return globalThis.window.localStorage;
763
- }
764
- if (typeof global !== "undefined" && ((_b = global.window) == null ? void 0 : _b.localStorage)) {
765
- return global.window.localStorage;
379
+ async syncProducts() {
380
+ if (!this.accessToken) {
381
+ throw new Error("Authentication required. Please authenticate first.");
766
382
  }
767
- return null;
383
+ return this.client.post("/api/stripe/products/sync", {}, {
384
+ headers: {
385
+ "Authorization": `Bearer ${this.accessToken}`
386
+ }
387
+ });
768
388
  }
769
389
  /**
770
- * Store tokens in localStorage (browser only)
390
+ * Get products with admin metadata (if user is admin)
771
391
  */
772
- static storeTokens(tokens) {
773
- const localStorage = _TokenManager.getStorage();
774
- if (localStorage) {
775
- localStorage.setItem(_TokenManager.ACCESS_TOKEN_KEY, tokens.access_token);
776
- localStorage.setItem(_TokenManager.REFRESH_TOKEN_KEY, tokens.refresh_token);
777
- localStorage.setItem(_TokenManager.USER_KEY, JSON.stringify(tokens.user));
392
+ async getProducts() {
393
+ const headers = {};
394
+ if (this.accessToken) {
395
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
778
396
  }
397
+ return this.client.get("/api/stripe/products", { headers });
779
398
  }
780
- /**
781
- * Get stored access token (browser only)
782
- */
783
- static getAccessToken() {
784
- const localStorage = _TokenManager.getStorage();
785
- return localStorage ? localStorage.getItem(_TokenManager.ACCESS_TOKEN_KEY) : null;
786
- }
787
- /**
788
- * Get stored refresh token (browser only)
789
- */
790
- static getRefreshToken() {
791
- const localStorage = _TokenManager.getStorage();
792
- return localStorage ? localStorage.getItem(_TokenManager.REFRESH_TOKEN_KEY) : null;
793
- }
794
- /**
795
- * Get stored user data (browser only)
796
- */
797
- static getStoredUser() {
798
- const localStorage = _TokenManager.getStorage();
799
- if (localStorage) {
800
- const userData = localStorage.getItem(_TokenManager.USER_KEY);
801
- return userData ? JSON.parse(userData) : null;
802
- }
803
- return null;
399
+ // Utility Methods
400
+ isAuthenticated() {
401
+ return !!this.accessToken;
804
402
  }
805
- /**
806
- * Clear all stored tokens and user data (browser only)
807
- */
808
- static clearTokens() {
809
- const localStorage = _TokenManager.getStorage();
810
- if (localStorage) {
811
- localStorage.removeItem(_TokenManager.ACCESS_TOKEN_KEY);
812
- localStorage.removeItem(_TokenManager.REFRESH_TOKEN_KEY);
813
- localStorage.removeItem(_TokenManager.USER_KEY);
814
- }
403
+ getAccessToken() {
404
+ return this.accessToken;
815
405
  }
816
- /**
817
- * Check if access token is expired (basic check, doesn't verify signature)
818
- */
819
- static isTokenExpired(token) {
820
- try {
821
- const parts = token.split(".");
822
- if (parts.length !== 3 || !parts[1]) return true;
823
- const payload = JSON.parse(atob(parts[1]));
824
- const currentTime = Math.floor(Date.now() / 1e3);
825
- return payload.exp < currentTime;
826
- } catch (e) {
827
- return true;
828
- }
406
+ setAccessToken(token) {
407
+ this.accessToken = token;
829
408
  }
830
- /**
831
- * Auto-refresh token if needed
832
- */
833
- static async autoRefreshToken(sdk) {
834
- const accessToken = _TokenManager.getAccessToken();
835
- const refreshToken = _TokenManager.getRefreshToken();
836
- if (!accessToken || !refreshToken) {
837
- return false;
838
- }
839
- if (!_TokenManager.isTokenExpired(accessToken)) {
840
- sdk.setAccessToken(accessToken);
841
- return true;
842
- }
843
- try {
844
- const newTokens = await sdk.auth.refreshToken(refreshToken);
845
- _TokenManager.storeTokens(newTokens);
846
- return true;
847
- } catch (e) {
848
- _TokenManager.clearTokens();
849
- return false;
850
- }
409
+ isLocalMode() {
410
+ return this._isLocalMode;
851
411
  }
852
- };
853
- _TokenManager.ACCESS_TOKEN_KEY = "sweet_potato_access_token";
854
- _TokenManager.REFRESH_TOKEN_KEY = "sweet_potato_refresh_token";
855
- _TokenManager.USER_KEY = "sweet_potato_user";
856
- var TokenManager = _TokenManager;
857
- var WalletUtils = class _WalletUtils {
858
412
  /**
859
- * Detect chain type from wallet address
413
+ * Check if current user has admin privileges
414
+ * Note: This requires the user object from authentication
860
415
  */
861
- static detectChainType(address) {
862
- if (/^0x[a-fA-F0-9]{40}$/.test(address)) {
863
- return "ethereum";
864
- }
865
- if (/^bc1[a-z0-9]{39,59}$/.test(address)) {
866
- return "bitcoin";
867
- }
868
- if (/^[1-9A-HJ-NP-Za-km-z]{32}$/.test(address) || /^[1-9A-HJ-NP-Za-km-z]{44}$/.test(address)) {
869
- return "solana";
870
- }
871
- if (/^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(address) && address.length >= 26 && address.length <= 35) {
872
- return "bitcoin";
873
- }
874
- if (/^[1-9A-HJ-NP-Za-km-z]{35,44}$/.test(address)) {
875
- return "solana";
876
- }
877
- return null;
416
+ isAdmin(user) {
417
+ if (!user) return false;
418
+ const identifier = user.email || user.wallet_address;
419
+ if (!identifier) return false;
420
+ const { isAdminAccount: isAdminAccount2 } = (init_permissions(), __toCommonJS(permissions_exports));
421
+ return isAdminAccount2(identifier);
878
422
  }
879
- /**
880
- * Validate wallet address format
881
- */
882
- static isValidAddress(address, chainType) {
883
- if (!chainType) {
884
- chainType = _WalletUtils.detectChainType(address) || "ethereum";
885
- }
886
- switch (chainType) {
887
- case "solana":
888
- return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
889
- case "ethereum":
890
- case "base":
891
- return /^0x[a-fA-F0-9]{40}$/.test(address);
892
- case "bitcoin":
893
- return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(address) || /^bc1[a-z0-9]{39,59}$/.test(address);
894
- default:
895
- return false;
896
- }
423
+ async health() {
424
+ return this.client.get("/health");
897
425
  }
898
426
  };
427
+ var index_default = SPAPSClient;
899
428
  export {
900
- AuthService,
901
- HttpClient,
902
- PaymentsService,
903
- SweetPotatoAPIError,
904
- SweetPotatoSDK,
905
- TokenManager,
906
- WalletUtils,
907
- createSweetPotatoSDK,
908
- SweetPotatoSDK as default
429
+ DEFAULT_ADMIN_ACCOUNTS,
430
+ PermissionChecker,
431
+ SPAPSClient as SPAPS,
432
+ SPAPSClient,
433
+ SPAPSClient as SweetPotatoSDK,
434
+ canAccessAdmin,
435
+ createPermissionChecker,
436
+ index_default as default,
437
+ defaultPermissionChecker,
438
+ getRoleAwareErrorMessage,
439
+ getUserDisplay,
440
+ getUserRole,
441
+ hasPermission,
442
+ isAdminAccount
909
443
  };