spaps-sdk 1.1.7 → 1.1.8

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/README.md CHANGED
@@ -193,6 +193,57 @@ console.log(`Credits: ${balance.data.balance}`);
193
193
  await spaps.recordUsage('api-call', 1);
194
194
  ```
195
195
 
196
+ ### ✉️ Secure Messaging
197
+ ```javascript
198
+ // Create a secure message (content encrypted server-side when pii_enabled)
199
+ const message = await spaps.secureMessages.create({
200
+ patientId: 'patient-123',
201
+ practitionerId: 'practitioner-456',
202
+ content: 'Patient is experiencing intermittent headaches.',
203
+ metadata: { urgency: 'high' }
204
+ });
205
+
206
+ // List secure messages for the current application
207
+ const messages = await spaps.secureMessages.list();
208
+ console.log(messages[0].content);
209
+ ```
210
+ > Ensure your application has `settings.pii_enabled = true` so payloads are encrypted automatically.
211
+
212
+ ```typescript
213
+ // Provide a strongly typed metadata shape for downstream usage
214
+ type SecureMessageMetadata = { urgency: 'low' | 'high'; tags?: string[] };
215
+
216
+ const spaps = new SPAPSClient<SecureMessageMetadata>({ apiKey: process.env.SPAPS_API_KEY });
217
+
218
+ await spaps.secureMessages.create({
219
+ patientId: 'patient-123',
220
+ practitionerId: 'practitioner-456',
221
+ content: 'Follow up scheduled for next week.',
222
+ metadata: { urgency: 'low', tags: ['follow-up'] }
223
+ });
224
+
225
+ const typedMessages = await spaps.secureMessages.list();
226
+ typedMessages[0].metadata.urgency; // "low" | "high"
227
+ ```
228
+
229
+ Need runtime validation too? Reuse the shared schemas that ship with the SDK:
230
+
231
+ ```typescript
232
+ import { z } from 'zod';
233
+ import { createSecureMessageRequestSchema } from 'spaps-sdk';
234
+
235
+ const secureMessageRequestSchema = createSecureMessageRequestSchema(
236
+ z.object({ urgency: z.enum(['low', 'high']), tags: z.array(z.string()).optional() })
237
+ );
238
+
239
+ secureMessageRequestSchema.parse({
240
+ patientId: 'patient-123',
241
+ practitionerId: 'practitioner-456',
242
+ content: 'All clear.',
243
+ metadata: { urgency: 'low' }
244
+ });
245
+ ```
246
+
196
247
  ## Configuration
197
248
 
198
249
  ### Production Mode
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as spaps_types from 'spaps-types';
2
- import { CreateProductRequest, Product, UpdateProductRequest, CreatePriceRequest, Price, ProductSyncResult, CryptoReconcileRequest, AuthResponse, User as User$1, CreateCryptoInvoiceRequest, CryptoInvoiceStatusSnapshot, CheckoutSession, Subscription, UsageBalance, VerifyCryptoWebhookSignatureOptions } from 'spaps-types';
3
- export { AdminPermission, AdminRole, AdminUser, ApiResponse, AuthResponse, CheckoutSession, CreateCryptoInvoiceRequest, CreatePriceRequest, CreateProductRequest, CryptoInvoice, CryptoInvoiceResponse, CryptoInvoiceStatusSnapshot, CryptoReconcileRequest, Price, Product, ProductSyncResult, Subscription, TokenPair, UpdateProductRequest, UsageBalance, User, UserProfile, UserRole, UserWallet, VerifyCryptoWebhookSignatureOptions } from 'spaps-types';
2
+ import { CreateProductRequest, Product, UpdateProductRequest, CreatePriceRequest, Price, ProductSyncResult, CryptoReconcileRequest, CreateSecureMessageRequest, SecureMessage, AuthResponse, User as User$1, CreateCryptoInvoiceRequest, CryptoInvoiceStatusSnapshot, CheckoutSession, Subscription, UsageBalance, VerifyCryptoWebhookSignatureOptions } from 'spaps-types';
3
+ export { AdminPermission, AdminRole, AdminUser, ApiResponse, AuthResponse, CheckoutSession, CreateCryptoInvoiceRequest, CreatePriceRequest, CreateProductRequest, CreateSecureMessageInput, CreateSecureMessageRequest, CryptoInvoice, CryptoInvoiceResponse, CryptoInvoiceStatusSnapshot, CryptoReconcileRequest, Price, Product, ProductSyncResult, SecureMessage, SecureMessageOutput, Subscription, TokenPair, UpdateProductRequest, UsageBalance, User, UserProfile, UserRole, UserWallet, VerifyCryptoWebhookSignatureOptions, createSecureMessageRequestSchema, secureMessageMetadataSchema, secureMessageSchema } from 'spaps-types';
4
4
 
5
5
  /**
6
6
  * Permission checking utilities for SPAPS SDK
@@ -92,13 +92,16 @@ interface SPAPSConfig {
92
92
  timeout?: number;
93
93
  }
94
94
 
95
- declare class SPAPSClient {
95
+ declare class SPAPSClient<SecureMessageMetadata extends Record<string, any> = Record<string, any>> {
96
96
  private client;
97
97
  private apiKey?;
98
98
  private accessToken?;
99
99
  private refreshToken?;
100
100
  private _isLocalMode;
101
101
  private unwrapApiResponse;
102
+ private isAxiosResponse;
103
+ private isResponseLikeWithData;
104
+ private isApiResponse;
102
105
  admin: {
103
106
  createProduct: (productData: CreateProductRequest) => Promise<{
104
107
  data: Product;
@@ -132,6 +135,10 @@ declare class SPAPSClient {
132
135
  cursor?: Record<string, unknown>;
133
136
  }>;
134
137
  };
138
+ secureMessages: {
139
+ create: (payload: CreateSecureMessageRequest<SecureMessageMetadata>) => Promise<SecureMessage<SecureMessageMetadata>>;
140
+ list: () => Promise<SecureMessage<SecureMessageMetadata>[]>;
141
+ };
135
142
  constructor(config?: SPAPSConfig);
136
143
  /** Raw API request helper that returns an ApiResponse-like shape */
137
144
  request<T = any>(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', url: string, data?: any, requiresAuth?: boolean): Promise<{
@@ -275,12 +282,20 @@ declare class SPAPSClient {
275
282
  cancel_url: string;
276
283
  trial_period_days?: number;
277
284
  }) => Promise<CheckoutSession>;
278
- getCheckoutSession: (sessionId: string) => Promise<any>;
285
+ getCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
279
286
  listCheckoutSessions: (query?: {
280
287
  limit?: number;
281
288
  starting_after?: string;
282
- }) => Promise<any>;
283
- expireCheckoutSession: (sessionId: string) => Promise<any>;
289
+ }) => Promise<{
290
+ sessions: any[];
291
+ has_more: boolean;
292
+ next_cursor?: string;
293
+ }>;
294
+ expireCheckoutSession: (sessionId: string) => Promise<{
295
+ id: string;
296
+ status: string;
297
+ expired: boolean;
298
+ }>;
284
299
  listProducts: (query?: {
285
300
  category?: string;
286
301
  active?: boolean;
@@ -289,6 +304,7 @@ declare class SPAPSClient {
289
304
  }) => Promise<{
290
305
  products: Product[];
291
306
  total: number;
307
+ adminMetadata?: any;
292
308
  }>;
293
309
  getProduct: (productId: string) => Promise<Product>;
294
310
  createCustomerPortalSession: (payload: {
@@ -352,6 +368,8 @@ declare class SPAPSClient {
352
368
  data: UsageBalance;
353
369
  }>;
354
370
  recordUsage(feature: string, amount: number): Promise<void>;
371
+ private createSecureMessage;
372
+ private listSecureMessages;
355
373
  /**
356
374
  * Create a new Stripe product (Admin required)
357
375
  */
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as spaps_types from 'spaps-types';
2
- import { CreateProductRequest, Product, UpdateProductRequest, CreatePriceRequest, Price, ProductSyncResult, CryptoReconcileRequest, AuthResponse, User as User$1, CreateCryptoInvoiceRequest, CryptoInvoiceStatusSnapshot, CheckoutSession, Subscription, UsageBalance, VerifyCryptoWebhookSignatureOptions } from 'spaps-types';
3
- export { AdminPermission, AdminRole, AdminUser, ApiResponse, AuthResponse, CheckoutSession, CreateCryptoInvoiceRequest, CreatePriceRequest, CreateProductRequest, CryptoInvoice, CryptoInvoiceResponse, CryptoInvoiceStatusSnapshot, CryptoReconcileRequest, Price, Product, ProductSyncResult, Subscription, TokenPair, UpdateProductRequest, UsageBalance, User, UserProfile, UserRole, UserWallet, VerifyCryptoWebhookSignatureOptions } from 'spaps-types';
2
+ import { CreateProductRequest, Product, UpdateProductRequest, CreatePriceRequest, Price, ProductSyncResult, CryptoReconcileRequest, CreateSecureMessageRequest, SecureMessage, AuthResponse, User as User$1, CreateCryptoInvoiceRequest, CryptoInvoiceStatusSnapshot, CheckoutSession, Subscription, UsageBalance, VerifyCryptoWebhookSignatureOptions } from 'spaps-types';
3
+ export { AdminPermission, AdminRole, AdminUser, ApiResponse, AuthResponse, CheckoutSession, CreateCryptoInvoiceRequest, CreatePriceRequest, CreateProductRequest, CreateSecureMessageInput, CreateSecureMessageRequest, CryptoInvoice, CryptoInvoiceResponse, CryptoInvoiceStatusSnapshot, CryptoReconcileRequest, Price, Product, ProductSyncResult, SecureMessage, SecureMessageOutput, Subscription, TokenPair, UpdateProductRequest, UsageBalance, User, UserProfile, UserRole, UserWallet, VerifyCryptoWebhookSignatureOptions, createSecureMessageRequestSchema, secureMessageMetadataSchema, secureMessageSchema } from 'spaps-types';
4
4
 
5
5
  /**
6
6
  * Permission checking utilities for SPAPS SDK
@@ -92,13 +92,16 @@ interface SPAPSConfig {
92
92
  timeout?: number;
93
93
  }
94
94
 
95
- declare class SPAPSClient {
95
+ declare class SPAPSClient<SecureMessageMetadata extends Record<string, any> = Record<string, any>> {
96
96
  private client;
97
97
  private apiKey?;
98
98
  private accessToken?;
99
99
  private refreshToken?;
100
100
  private _isLocalMode;
101
101
  private unwrapApiResponse;
102
+ private isAxiosResponse;
103
+ private isResponseLikeWithData;
104
+ private isApiResponse;
102
105
  admin: {
103
106
  createProduct: (productData: CreateProductRequest) => Promise<{
104
107
  data: Product;
@@ -132,6 +135,10 @@ declare class SPAPSClient {
132
135
  cursor?: Record<string, unknown>;
133
136
  }>;
134
137
  };
138
+ secureMessages: {
139
+ create: (payload: CreateSecureMessageRequest<SecureMessageMetadata>) => Promise<SecureMessage<SecureMessageMetadata>>;
140
+ list: () => Promise<SecureMessage<SecureMessageMetadata>[]>;
141
+ };
135
142
  constructor(config?: SPAPSConfig);
136
143
  /** Raw API request helper that returns an ApiResponse-like shape */
137
144
  request<T = any>(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', url: string, data?: any, requiresAuth?: boolean): Promise<{
@@ -275,12 +282,20 @@ declare class SPAPSClient {
275
282
  cancel_url: string;
276
283
  trial_period_days?: number;
277
284
  }) => Promise<CheckoutSession>;
278
- getCheckoutSession: (sessionId: string) => Promise<any>;
285
+ getCheckoutSession: (sessionId: string) => Promise<CheckoutSession>;
279
286
  listCheckoutSessions: (query?: {
280
287
  limit?: number;
281
288
  starting_after?: string;
282
- }) => Promise<any>;
283
- expireCheckoutSession: (sessionId: string) => Promise<any>;
289
+ }) => Promise<{
290
+ sessions: any[];
291
+ has_more: boolean;
292
+ next_cursor?: string;
293
+ }>;
294
+ expireCheckoutSession: (sessionId: string) => Promise<{
295
+ id: string;
296
+ status: string;
297
+ expired: boolean;
298
+ }>;
284
299
  listProducts: (query?: {
285
300
  category?: string;
286
301
  active?: boolean;
@@ -289,6 +304,7 @@ declare class SPAPSClient {
289
304
  }) => Promise<{
290
305
  products: Product[];
291
306
  total: number;
307
+ adminMetadata?: any;
292
308
  }>;
293
309
  getProduct: (productId: string) => Promise<Product>;
294
310
  createCustomerPortalSession: (payload: {
@@ -352,6 +368,8 @@ declare class SPAPSClient {
352
368
  data: UsageBalance;
353
369
  }>;
354
370
  recordUsage(feature: string, amount: number): Promise<void>;
371
+ private createSecureMessage;
372
+ private listSecureMessages;
355
373
  /**
356
374
  * Create a new Stripe product (Admin required)
357
375
  */
package/dist/index.js CHANGED
@@ -202,6 +202,7 @@ __export(index_exports, {
202
202
  WalletUtils: () => WalletUtils,
203
203
  canAccessAdmin: () => canAccessAdmin,
204
204
  createPermissionChecker: () => createPermissionChecker,
205
+ createSecureMessageRequestSchema: () => import_spaps_types.createSecureMessageRequestSchema,
205
206
  default: () => index_default,
206
207
  defaultPermissionChecker: () => defaultPermissionChecker,
207
208
  getRoleAwareErrorMessage: () => getRoleAwareErrorMessage,
@@ -209,11 +210,14 @@ __export(index_exports, {
209
210
  getUserRole: () => getUserRole,
210
211
  hasPermission: () => hasPermission,
211
212
  isAdminAccount: () => isAdminAccount,
213
+ secureMessageMetadataSchema: () => import_spaps_types.secureMessageMetadataSchema,
214
+ secureMessageSchema: () => import_spaps_types.secureMessageSchema,
212
215
  verifyCryptoWebhookSignature: () => verifyCryptoWebhookSignature
213
216
  });
214
217
  module.exports = __toCommonJS(index_exports);
215
218
  var import_crypto = __toESM(require("crypto"));
216
219
  var import_axios = __toESM(require("axios"));
220
+ var import_spaps_types = require("spaps-types");
217
221
  init_permissions();
218
222
  if (typeof globalThis.fetch === "undefined") {
219
223
  require("cross-fetch/polyfill");
@@ -225,11 +229,39 @@ var SPAPSClient = class {
225
229
  refreshToken;
226
230
  _isLocalMode = false;
227
231
  unwrapApiResponse(response, fallback) {
228
- const body = response?.data ?? response;
229
- if (body?.success === false) {
230
- throw new Error(body?.error?.message || fallback);
232
+ if (!response) {
233
+ throw new Error(fallback);
231
234
  }
232
- return body?.data ?? body;
235
+ const payload = this.isAxiosResponse(response) ? response.data : this.isResponseLikeWithData(response) ? response.data : response;
236
+ if (this.isApiResponse(payload)) {
237
+ if (payload.success === false) {
238
+ throw new Error(payload.error?.message || fallback);
239
+ }
240
+ if (payload.data !== void 0) {
241
+ return payload.data;
242
+ }
243
+ return void 0;
244
+ }
245
+ return payload;
246
+ }
247
+ isAxiosResponse(value) {
248
+ if (!value || typeof value !== "object") {
249
+ return false;
250
+ }
251
+ const record = value;
252
+ return "data" in record && "status" in record;
253
+ }
254
+ isResponseLikeWithData(value) {
255
+ if (!value || typeof value !== "object") return false;
256
+ const record = value;
257
+ return "data" in record && !("success" in record);
258
+ }
259
+ isApiResponse(value) {
260
+ if (!value || typeof value !== "object") {
261
+ return false;
262
+ }
263
+ const record = value;
264
+ return "success" in record && typeof record.success === "boolean";
233
265
  }
234
266
  // Admin namespace for cleaner API
235
267
  admin = {
@@ -241,6 +273,10 @@ var SPAPSClient = class {
241
273
  getProducts: () => this.getProducts(),
242
274
  triggerCryptoReconcile: (opts) => this.payments.crypto.reconcile(opts || {})
243
275
  };
276
+ secureMessages = {
277
+ create: (payload) => this.createSecureMessage(payload),
278
+ list: () => this.listSecureMessages()
279
+ };
244
280
  constructor(config = {}) {
245
281
  const apiUrl = config.apiUrl || process.env.SPAPS_API_URL || process.env.NEXT_PUBLIC_SPAPS_API_URL;
246
282
  if (!apiUrl || apiUrl.includes("localhost") || apiUrl.includes("127.0.0.1")) {
@@ -422,68 +458,66 @@ var SPAPSClient = class {
422
458
  */
423
459
  verifyMagicLink: async (payload) => {
424
460
  const res = await this.client.post("/api/auth/verify-magic-link", payload);
425
- const body = res.data;
426
- if (body?.success === false) throw new Error(body?.error?.message || "Failed to verify magic link");
427
- return body?.data || body || { success: true };
461
+ return this.unwrapApiResponse(res, "Failed to verify magic link");
428
462
  },
429
463
  solana: {
430
464
  linkWallet: async (payload) => {
431
465
  const res = await this.client.post("/api/auth/solana/link-wallet", payload);
432
- return res.data;
466
+ return this.unwrapApiResponse(res, "Failed to link Solana wallet");
433
467
  },
434
468
  verifySignature: async (payload) => {
435
469
  const res = await this.client.post("/api/auth/solana/verify-signature", payload);
436
- return res.data;
470
+ return this.unwrapApiResponse(res, "Failed to verify Solana signature");
437
471
  },
438
472
  generateMessage: async (wallet_address) => {
439
473
  const res = await this.client.get(`/api/auth/solana/generate-message/${wallet_address}`);
440
- return res.data;
474
+ return this.unwrapApiResponse(res, "Failed to generate Solana auth message");
441
475
  },
442
476
  getWallets: async () => {
443
477
  const res = await this.client.get("/api/auth/solana/wallets");
444
- return res.data;
478
+ return this.unwrapApiResponse(res, "Failed to fetch Solana wallets");
445
479
  },
446
480
  networkInfo: async () => {
447
481
  const res = await this.client.get("/api/auth/solana/network-info");
448
- return res.data;
482
+ return this.unwrapApiResponse(res, "Failed to fetch Solana network info");
449
483
  }
450
484
  },
451
485
  ethereum: {
452
486
  linkWallet: async (payload) => {
453
487
  const res = await this.client.post("/api/auth/ethereum/link-wallet", payload);
454
- return res.data;
488
+ return this.unwrapApiResponse(res, "Failed to link Ethereum wallet");
455
489
  },
456
490
  verifySignature: async (payload) => {
457
491
  const res = await this.client.post("/api/auth/ethereum/verify-signature", payload);
458
- return res.data;
492
+ return this.unwrapApiResponse(res, "Failed to verify Ethereum signature");
459
493
  },
460
494
  verifyTypedData: async (payload) => {
461
495
  const res = await this.client.post("/api/auth/ethereum/verify-typed-data", payload);
462
- return res.data;
496
+ return this.unwrapApiResponse(res, "Failed to verify EIP-712 typed data");
463
497
  },
464
498
  generateMessage: async (wallet_address) => {
465
499
  const res = await this.client.get(`/api/auth/ethereum/generate-message/${wallet_address}`);
466
- return res.data;
500
+ return this.unwrapApiResponse(res, "Failed to generate Ethereum auth message");
467
501
  },
468
502
  generateTypedData: async (wallet_address) => {
469
503
  const res = await this.client.get(`/api/auth/ethereum/generate-typed-data/${wallet_address}`);
470
- return res.data;
504
+ return this.unwrapApiResponse(res, "Failed to generate Ethereum typed data");
471
505
  },
472
506
  getWallets: async () => {
473
507
  const res = await this.client.get("/api/auth/ethereum/wallets");
474
- return res.data;
508
+ return this.unwrapApiResponse(res, "Failed to fetch Ethereum wallets");
475
509
  },
476
510
  networkInfo: async () => {
477
511
  const res = await this.client.get("/api/auth/ethereum/network-info");
478
- return res.data;
512
+ return this.unwrapApiResponse(res, "Failed to fetch Ethereum network info");
479
513
  },
480
514
  balance: async (wallet_address) => {
481
515
  const res = await this.client.get(`/api/auth/ethereum/balance/${wallet_address}`);
482
- return res.data;
516
+ return this.unwrapApiResponse(res, "Failed to fetch Ethereum balance");
483
517
  },
484
518
  contractCheck: async (wallet_address, contract_address) => {
485
519
  const res = await this.client.get(`/api/auth/ethereum/contract-check/${wallet_address}/${contract_address}`);
486
- return res.data;
520
+ return this.unwrapApiResponse(res, "Failed to check contract");
487
521
  }
488
522
  },
489
523
  refreshToken: async (refreshToken) => {
@@ -563,7 +597,7 @@ var SPAPSClient = class {
563
597
  const headers = {};
564
598
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
565
599
  const res = await this.client.post("/api/stripe/checkout-sessions", payload, { headers });
566
- return res.data;
600
+ return this.unwrapApiResponse(res, "Failed to create checkout session");
567
601
  },
568
602
  createPaymentCheckout: async (params) => {
569
603
  const payload = { mode: "payment", line_items: [{ price_id: params.price_id, quantity: params.quantity ?? 1 }], success_url: params.success_url, cancel_url: params.cancel_url };
@@ -576,18 +610,18 @@ var SPAPSClient = class {
576
610
  },
577
611
  getCheckoutSession: async (sessionId) => {
578
612
  const res = await this.client.get(`/api/stripe/checkout-sessions/${sessionId}`);
579
- return res.data;
613
+ return this.unwrapApiResponse(res, "Failed to get checkout session");
580
614
  },
581
615
  listCheckoutSessions: async (query = {}) => {
582
616
  const q = new URLSearchParams();
583
617
  if (query.limit) q.append("limit", String(query.limit));
584
618
  if (query.starting_after) q.append("starting_after", query.starting_after);
585
619
  const res = await this.client.get(`/api/stripe/checkout-sessions${q.toString() ? `?${q.toString()}` : ""}`);
586
- return res.data;
620
+ return this.unwrapApiResponse(res, "Failed to list checkout sessions");
587
621
  },
588
622
  expireCheckoutSession: async (sessionId) => {
589
623
  const res = await this.client.post(`/api/stripe/checkout-sessions/${sessionId}/expire`);
590
- return res.data;
624
+ return this.unwrapApiResponse(res, "Failed to expire checkout session");
591
625
  },
592
626
  listProducts: async (query = {}) => {
593
627
  const q = new URLSearchParams();
@@ -598,32 +632,32 @@ var SPAPSClient = class {
598
632
  const headers = {};
599
633
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
600
634
  const res = await this.client.get(`/api/stripe/products${q.toString() ? `?${q.toString()}` : ""}`, { headers });
601
- return res.data;
635
+ return this.unwrapApiResponse(res, "Failed to list products");
602
636
  },
603
637
  getProduct: async (productId) => {
604
638
  const headers = {};
605
639
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
606
640
  const res = await this.client.get(`/api/stripe/products/${productId}`, { headers });
607
- return res.data;
641
+ return this.unwrapApiResponse(res, "Failed to get product");
608
642
  },
609
643
  createCustomerPortalSession: async (payload) => {
610
644
  const headers = {};
611
645
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
612
646
  const res = await this.client.post("/api/stripe/portal-session", payload, { headers });
613
- return res.data;
647
+ return this.unwrapApiResponse(res, "Failed to create portal session");
614
648
  },
615
649
  // Guest checkout helpers
616
650
  createGuestCheckoutSession: async (payload) => {
617
651
  const headers = {};
618
652
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
619
653
  const res = await this.client.post("/api/stripe/guest-checkout-sessions", payload, { headers });
620
- return res.data;
654
+ return this.unwrapApiResponse(res, "Failed to create guest checkout session");
621
655
  },
622
656
  getGuestCheckoutSession: async (sessionId) => {
623
657
  const headers = {};
624
658
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
625
659
  const res = await this.client.get(`/api/stripe/guest-checkout-sessions/${sessionId}`, { headers });
626
- return res.data;
660
+ return this.unwrapApiResponse(res, "Failed to get guest checkout session");
627
661
  },
628
662
  listGuestCheckoutSessions: async (query = {}) => {
629
663
  const q = new URLSearchParams();
@@ -632,55 +666,55 @@ var SPAPSClient = class {
632
666
  const headers = {};
633
667
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
634
668
  const res = await this.client.get(`/api/stripe/guest-checkout-sessions${q.toString() ? `?${q.toString()}` : ""}`, { headers });
635
- return res.data;
669
+ return this.unwrapApiResponse(res, "Failed to list guest checkout sessions");
636
670
  },
637
671
  convertGuestCheckoutSession: async (payload) => {
638
672
  const headers = {};
639
673
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
640
674
  const res = await this.client.post("/api/stripe/guest-checkout-sessions/convert", payload, { headers });
641
- return res.data;
675
+ return this.unwrapApiResponse(res, "Failed to convert guest checkout session");
642
676
  },
643
677
  convertGuestCheckout: async (payload) => this.payments.convertGuestCheckoutSession(payload),
644
678
  // Super-admin product helpers (admin token required)
645
679
  listAllProductsSuperAdmin: async () => {
646
680
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
647
681
  const res = await this.client.get("/api/stripe/products/super-admin/all", { headers: { Authorization: `Bearer ${this.accessToken}` } });
648
- return res.data;
682
+ return this.unwrapApiResponse(res, "Failed to list all products (super admin)");
649
683
  },
650
684
  updateProductSuperAdmin: async (productId, updates) => {
651
685
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
652
686
  const res = await this.client.put(`/api/stripe/products/super-admin/${productId}`, updates, { headers: { Authorization: `Bearer ${this.accessToken}` } });
653
- return res.data;
687
+ return this.unwrapApiResponse(res, "Failed to update product (super admin)");
654
688
  },
655
689
  deleteProductSuperAdmin: async (productId) => {
656
690
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
657
691
  const res = await this.client.delete(`/api/stripe/products/super-admin/${productId}`, { headers: { Authorization: `Bearer ${this.accessToken}` } });
658
- return res.data;
692
+ return this.unwrapApiResponse(res, "Failed to archive product (super admin)");
659
693
  },
660
694
  createProductWithPrice: async (payload) => {
661
695
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
662
696
  const res = await this.client.post("/api/stripe/products/with-price", payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
663
- return res.data;
697
+ return this.unwrapApiResponse(res, "Failed to create product with price");
664
698
  },
665
699
  createProductWithPriceSuperAdmin: async (productId, payload) => {
666
700
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
667
701
  const res = await this.client.post(`/api/stripe/products/super-admin/${productId}/with-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
668
- return res.data;
702
+ return this.unwrapApiResponse(res, "Failed to create product with price (super admin)");
669
703
  },
670
704
  setDefaultPrice: async (productId, payload) => {
671
705
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
672
706
  const res = await this.client.post(`/api/stripe/products/${productId}/default-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
673
- return res.data;
707
+ return this.unwrapApiResponse(res, "Failed to set default price");
674
708
  },
675
709
  setDefaultPriceSuperAdmin: async (productId, payload) => {
676
710
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
677
711
  const res = await this.client.put(`/api/stripe/products/super-admin/${productId}/default-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
678
- return res.data;
712
+ return this.unwrapApiResponse(res, "Failed to set default price (super admin)");
679
713
  },
680
714
  createDefaultNewPrice: async (productId, payload) => {
681
715
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
682
716
  const res = await this.client.post(`/api/stripe/products/${productId}/prices/default-new`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
683
- return res.data;
717
+ return this.unwrapApiResponse(res, "Failed to create default price");
684
718
  },
685
719
  superAdminListAllProducts: async () => this.payments.listAllProductsSuperAdmin(),
686
720
  superAdminUpdateProduct: async (productId, updates) => this.payments.updateProductSuperAdmin(productId, updates),
@@ -688,42 +722,42 @@ var SPAPSClient = class {
688
722
  superAdminCreateProductWithPrice: async (applicationId, payload) => {
689
723
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
690
724
  const res = await this.client.post(`/api/stripe/products/super-admin/${applicationId}/with-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
691
- return res.data;
725
+ return this.unwrapApiResponse(res, "Failed to create product with price for application (super admin)");
692
726
  },
693
727
  superAdminCreatePriceAndSetDefault: async (productId, payload) => {
694
728
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
695
729
  const res = await this.client.post(`/api/stripe/products/super-admin/${productId}/prices/default-new`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
696
- return res.data;
730
+ return this.unwrapApiResponse(res, "Failed to create price and set default (super admin)");
697
731
  },
698
732
  superAdminSetDefaultPrice: async (productId, payload) => this.payments.setDefaultPriceSuperAdmin(productId, payload)
699
733
  };
700
734
  sessions = {
701
735
  getCurrent: async () => {
702
736
  const res = await this.client.get("/api/sessions/current", this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
703
- return res.data;
737
+ return this.unwrapApiResponse(res, "Failed to get current session");
704
738
  },
705
739
  list: async (params = {}) => {
706
740
  const q = new URLSearchParams();
707
741
  if (params.limit) q.append("limit", String(params.limit));
708
742
  if (params.starting_after) q.append("starting_after", params.starting_after);
709
743
  const res = await this.client.get(`/api/sessions${q.toString() ? `?${q.toString()}` : ""}`, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
710
- return res.data;
744
+ return this.unwrapApiResponse(res, "Failed to list sessions");
711
745
  },
712
746
  validate: async () => {
713
747
  const res = await this.client.post("/api/sessions/validate", {}, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
714
- return res.data || { valid: true };
748
+ return this.unwrapApiResponse(res, "Failed to validate session");
715
749
  },
716
750
  revoke: async (sessionId) => {
717
751
  const res = await this.client.delete(`/api/sessions/${sessionId}`, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
718
- return res.data || { revoked: true };
752
+ return this.unwrapApiResponse(res, "Failed to revoke session");
719
753
  },
720
754
  revokeAll: async () => {
721
755
  const res = await this.client.delete("/api/sessions/all", this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
722
- return res.data || { revoked: true };
756
+ return this.unwrapApiResponse(res, "Failed to revoke all sessions");
723
757
  },
724
758
  touch: async () => {
725
759
  const res = await this.client.post("/api/sessions/touch", {}, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
726
- return res.data || { touched: true };
760
+ return this.unwrapApiResponse(res, "Failed to touch session");
727
761
  }
728
762
  };
729
763
  // Stripe Methods
@@ -750,6 +784,19 @@ var SPAPSClient = class {
750
784
  amount
751
785
  });
752
786
  }
787
+ // Secure Messaging Methods
788
+ async createSecureMessage(payload) {
789
+ const response = await this.client.post("/api/secure-messages", payload);
790
+ return this.unwrapApiResponse(response, "Failed to create secure message");
791
+ }
792
+ async listSecureMessages() {
793
+ const response = await this.client.get("/api/secure-messages");
794
+ const payload = this.unwrapApiResponse(response, "Failed to list secure messages");
795
+ if (payload && Array.isArray(payload.messages)) {
796
+ return payload.messages;
797
+ }
798
+ return payload;
799
+ }
753
800
  // Admin Methods (Require admin privileges)
754
801
  /**
755
802
  * Create a new Stripe product (Admin required)
@@ -989,11 +1036,14 @@ var WalletUtils = class _WalletUtils {
989
1036
  WalletUtils,
990
1037
  canAccessAdmin,
991
1038
  createPermissionChecker,
1039
+ createSecureMessageRequestSchema,
992
1040
  defaultPermissionChecker,
993
1041
  getRoleAwareErrorMessage,
994
1042
  getUserDisplay,
995
1043
  getUserRole,
996
1044
  hasPermission,
997
1045
  isAdminAccount,
1046
+ secureMessageMetadataSchema,
1047
+ secureMessageSchema,
998
1048
  verifyCryptoWebhookSignature
999
1049
  });
package/dist/index.mjs CHANGED
@@ -190,6 +190,11 @@ var init_permissions = __esm({
190
190
  init_permissions();
191
191
  import crypto from "crypto";
192
192
  import axios from "axios";
193
+ import {
194
+ createSecureMessageRequestSchema,
195
+ secureMessageSchema,
196
+ secureMessageMetadataSchema
197
+ } from "spaps-types";
193
198
  if (typeof globalThis.fetch === "undefined") {
194
199
  __require("cross-fetch/polyfill");
195
200
  }
@@ -200,11 +205,39 @@ var SPAPSClient = class {
200
205
  refreshToken;
201
206
  _isLocalMode = false;
202
207
  unwrapApiResponse(response, fallback) {
203
- const body = response?.data ?? response;
204
- if (body?.success === false) {
205
- throw new Error(body?.error?.message || fallback);
208
+ if (!response) {
209
+ throw new Error(fallback);
206
210
  }
207
- return body?.data ?? body;
211
+ const payload = this.isAxiosResponse(response) ? response.data : this.isResponseLikeWithData(response) ? response.data : response;
212
+ if (this.isApiResponse(payload)) {
213
+ if (payload.success === false) {
214
+ throw new Error(payload.error?.message || fallback);
215
+ }
216
+ if (payload.data !== void 0) {
217
+ return payload.data;
218
+ }
219
+ return void 0;
220
+ }
221
+ return payload;
222
+ }
223
+ isAxiosResponse(value) {
224
+ if (!value || typeof value !== "object") {
225
+ return false;
226
+ }
227
+ const record = value;
228
+ return "data" in record && "status" in record;
229
+ }
230
+ isResponseLikeWithData(value) {
231
+ if (!value || typeof value !== "object") return false;
232
+ const record = value;
233
+ return "data" in record && !("success" in record);
234
+ }
235
+ isApiResponse(value) {
236
+ if (!value || typeof value !== "object") {
237
+ return false;
238
+ }
239
+ const record = value;
240
+ return "success" in record && typeof record.success === "boolean";
208
241
  }
209
242
  // Admin namespace for cleaner API
210
243
  admin = {
@@ -216,6 +249,10 @@ var SPAPSClient = class {
216
249
  getProducts: () => this.getProducts(),
217
250
  triggerCryptoReconcile: (opts) => this.payments.crypto.reconcile(opts || {})
218
251
  };
252
+ secureMessages = {
253
+ create: (payload) => this.createSecureMessage(payload),
254
+ list: () => this.listSecureMessages()
255
+ };
219
256
  constructor(config = {}) {
220
257
  const apiUrl = config.apiUrl || process.env.SPAPS_API_URL || process.env.NEXT_PUBLIC_SPAPS_API_URL;
221
258
  if (!apiUrl || apiUrl.includes("localhost") || apiUrl.includes("127.0.0.1")) {
@@ -397,68 +434,66 @@ var SPAPSClient = class {
397
434
  */
398
435
  verifyMagicLink: async (payload) => {
399
436
  const res = await this.client.post("/api/auth/verify-magic-link", payload);
400
- const body = res.data;
401
- if (body?.success === false) throw new Error(body?.error?.message || "Failed to verify magic link");
402
- return body?.data || body || { success: true };
437
+ return this.unwrapApiResponse(res, "Failed to verify magic link");
403
438
  },
404
439
  solana: {
405
440
  linkWallet: async (payload) => {
406
441
  const res = await this.client.post("/api/auth/solana/link-wallet", payload);
407
- return res.data;
442
+ return this.unwrapApiResponse(res, "Failed to link Solana wallet");
408
443
  },
409
444
  verifySignature: async (payload) => {
410
445
  const res = await this.client.post("/api/auth/solana/verify-signature", payload);
411
- return res.data;
446
+ return this.unwrapApiResponse(res, "Failed to verify Solana signature");
412
447
  },
413
448
  generateMessage: async (wallet_address) => {
414
449
  const res = await this.client.get(`/api/auth/solana/generate-message/${wallet_address}`);
415
- return res.data;
450
+ return this.unwrapApiResponse(res, "Failed to generate Solana auth message");
416
451
  },
417
452
  getWallets: async () => {
418
453
  const res = await this.client.get("/api/auth/solana/wallets");
419
- return res.data;
454
+ return this.unwrapApiResponse(res, "Failed to fetch Solana wallets");
420
455
  },
421
456
  networkInfo: async () => {
422
457
  const res = await this.client.get("/api/auth/solana/network-info");
423
- return res.data;
458
+ return this.unwrapApiResponse(res, "Failed to fetch Solana network info");
424
459
  }
425
460
  },
426
461
  ethereum: {
427
462
  linkWallet: async (payload) => {
428
463
  const res = await this.client.post("/api/auth/ethereum/link-wallet", payload);
429
- return res.data;
464
+ return this.unwrapApiResponse(res, "Failed to link Ethereum wallet");
430
465
  },
431
466
  verifySignature: async (payload) => {
432
467
  const res = await this.client.post("/api/auth/ethereum/verify-signature", payload);
433
- return res.data;
468
+ return this.unwrapApiResponse(res, "Failed to verify Ethereum signature");
434
469
  },
435
470
  verifyTypedData: async (payload) => {
436
471
  const res = await this.client.post("/api/auth/ethereum/verify-typed-data", payload);
437
- return res.data;
472
+ return this.unwrapApiResponse(res, "Failed to verify EIP-712 typed data");
438
473
  },
439
474
  generateMessage: async (wallet_address) => {
440
475
  const res = await this.client.get(`/api/auth/ethereum/generate-message/${wallet_address}`);
441
- return res.data;
476
+ return this.unwrapApiResponse(res, "Failed to generate Ethereum auth message");
442
477
  },
443
478
  generateTypedData: async (wallet_address) => {
444
479
  const res = await this.client.get(`/api/auth/ethereum/generate-typed-data/${wallet_address}`);
445
- return res.data;
480
+ return this.unwrapApiResponse(res, "Failed to generate Ethereum typed data");
446
481
  },
447
482
  getWallets: async () => {
448
483
  const res = await this.client.get("/api/auth/ethereum/wallets");
449
- return res.data;
484
+ return this.unwrapApiResponse(res, "Failed to fetch Ethereum wallets");
450
485
  },
451
486
  networkInfo: async () => {
452
487
  const res = await this.client.get("/api/auth/ethereum/network-info");
453
- return res.data;
488
+ return this.unwrapApiResponse(res, "Failed to fetch Ethereum network info");
454
489
  },
455
490
  balance: async (wallet_address) => {
456
491
  const res = await this.client.get(`/api/auth/ethereum/balance/${wallet_address}`);
457
- return res.data;
492
+ return this.unwrapApiResponse(res, "Failed to fetch Ethereum balance");
458
493
  },
459
494
  contractCheck: async (wallet_address, contract_address) => {
460
495
  const res = await this.client.get(`/api/auth/ethereum/contract-check/${wallet_address}/${contract_address}`);
461
- return res.data;
496
+ return this.unwrapApiResponse(res, "Failed to check contract");
462
497
  }
463
498
  },
464
499
  refreshToken: async (refreshToken) => {
@@ -538,7 +573,7 @@ var SPAPSClient = class {
538
573
  const headers = {};
539
574
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
540
575
  const res = await this.client.post("/api/stripe/checkout-sessions", payload, { headers });
541
- return res.data;
576
+ return this.unwrapApiResponse(res, "Failed to create checkout session");
542
577
  },
543
578
  createPaymentCheckout: async (params) => {
544
579
  const payload = { mode: "payment", line_items: [{ price_id: params.price_id, quantity: params.quantity ?? 1 }], success_url: params.success_url, cancel_url: params.cancel_url };
@@ -551,18 +586,18 @@ var SPAPSClient = class {
551
586
  },
552
587
  getCheckoutSession: async (sessionId) => {
553
588
  const res = await this.client.get(`/api/stripe/checkout-sessions/${sessionId}`);
554
- return res.data;
589
+ return this.unwrapApiResponse(res, "Failed to get checkout session");
555
590
  },
556
591
  listCheckoutSessions: async (query = {}) => {
557
592
  const q = new URLSearchParams();
558
593
  if (query.limit) q.append("limit", String(query.limit));
559
594
  if (query.starting_after) q.append("starting_after", query.starting_after);
560
595
  const res = await this.client.get(`/api/stripe/checkout-sessions${q.toString() ? `?${q.toString()}` : ""}`);
561
- return res.data;
596
+ return this.unwrapApiResponse(res, "Failed to list checkout sessions");
562
597
  },
563
598
  expireCheckoutSession: async (sessionId) => {
564
599
  const res = await this.client.post(`/api/stripe/checkout-sessions/${sessionId}/expire`);
565
- return res.data;
600
+ return this.unwrapApiResponse(res, "Failed to expire checkout session");
566
601
  },
567
602
  listProducts: async (query = {}) => {
568
603
  const q = new URLSearchParams();
@@ -573,32 +608,32 @@ var SPAPSClient = class {
573
608
  const headers = {};
574
609
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
575
610
  const res = await this.client.get(`/api/stripe/products${q.toString() ? `?${q.toString()}` : ""}`, { headers });
576
- return res.data;
611
+ return this.unwrapApiResponse(res, "Failed to list products");
577
612
  },
578
613
  getProduct: async (productId) => {
579
614
  const headers = {};
580
615
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
581
616
  const res = await this.client.get(`/api/stripe/products/${productId}`, { headers });
582
- return res.data;
617
+ return this.unwrapApiResponse(res, "Failed to get product");
583
618
  },
584
619
  createCustomerPortalSession: async (payload) => {
585
620
  const headers = {};
586
621
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
587
622
  const res = await this.client.post("/api/stripe/portal-session", payload, { headers });
588
- return res.data;
623
+ return this.unwrapApiResponse(res, "Failed to create portal session");
589
624
  },
590
625
  // Guest checkout helpers
591
626
  createGuestCheckoutSession: async (payload) => {
592
627
  const headers = {};
593
628
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
594
629
  const res = await this.client.post("/api/stripe/guest-checkout-sessions", payload, { headers });
595
- return res.data;
630
+ return this.unwrapApiResponse(res, "Failed to create guest checkout session");
596
631
  },
597
632
  getGuestCheckoutSession: async (sessionId) => {
598
633
  const headers = {};
599
634
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
600
635
  const res = await this.client.get(`/api/stripe/guest-checkout-sessions/${sessionId}`, { headers });
601
- return res.data;
636
+ return this.unwrapApiResponse(res, "Failed to get guest checkout session");
602
637
  },
603
638
  listGuestCheckoutSessions: async (query = {}) => {
604
639
  const q = new URLSearchParams();
@@ -607,55 +642,55 @@ var SPAPSClient = class {
607
642
  const headers = {};
608
643
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
609
644
  const res = await this.client.get(`/api/stripe/guest-checkout-sessions${q.toString() ? `?${q.toString()}` : ""}`, { headers });
610
- return res.data;
645
+ return this.unwrapApiResponse(res, "Failed to list guest checkout sessions");
611
646
  },
612
647
  convertGuestCheckoutSession: async (payload) => {
613
648
  const headers = {};
614
649
  if (this.accessToken) headers["Authorization"] = `Bearer ${this.accessToken}`;
615
650
  const res = await this.client.post("/api/stripe/guest-checkout-sessions/convert", payload, { headers });
616
- return res.data;
651
+ return this.unwrapApiResponse(res, "Failed to convert guest checkout session");
617
652
  },
618
653
  convertGuestCheckout: async (payload) => this.payments.convertGuestCheckoutSession(payload),
619
654
  // Super-admin product helpers (admin token required)
620
655
  listAllProductsSuperAdmin: async () => {
621
656
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
622
657
  const res = await this.client.get("/api/stripe/products/super-admin/all", { headers: { Authorization: `Bearer ${this.accessToken}` } });
623
- return res.data;
658
+ return this.unwrapApiResponse(res, "Failed to list all products (super admin)");
624
659
  },
625
660
  updateProductSuperAdmin: async (productId, updates) => {
626
661
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
627
662
  const res = await this.client.put(`/api/stripe/products/super-admin/${productId}`, updates, { headers: { Authorization: `Bearer ${this.accessToken}` } });
628
- return res.data;
663
+ return this.unwrapApiResponse(res, "Failed to update product (super admin)");
629
664
  },
630
665
  deleteProductSuperAdmin: async (productId) => {
631
666
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
632
667
  const res = await this.client.delete(`/api/stripe/products/super-admin/${productId}`, { headers: { Authorization: `Bearer ${this.accessToken}` } });
633
- return res.data;
668
+ return this.unwrapApiResponse(res, "Failed to archive product (super admin)");
634
669
  },
635
670
  createProductWithPrice: async (payload) => {
636
671
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
637
672
  const res = await this.client.post("/api/stripe/products/with-price", payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
638
- return res.data;
673
+ return this.unwrapApiResponse(res, "Failed to create product with price");
639
674
  },
640
675
  createProductWithPriceSuperAdmin: async (productId, payload) => {
641
676
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
642
677
  const res = await this.client.post(`/api/stripe/products/super-admin/${productId}/with-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
643
- return res.data;
678
+ return this.unwrapApiResponse(res, "Failed to create product with price (super admin)");
644
679
  },
645
680
  setDefaultPrice: async (productId, payload) => {
646
681
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
647
682
  const res = await this.client.post(`/api/stripe/products/${productId}/default-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
648
- return res.data;
683
+ return this.unwrapApiResponse(res, "Failed to set default price");
649
684
  },
650
685
  setDefaultPriceSuperAdmin: async (productId, payload) => {
651
686
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
652
687
  const res = await this.client.put(`/api/stripe/products/super-admin/${productId}/default-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
653
- return res.data;
688
+ return this.unwrapApiResponse(res, "Failed to set default price (super admin)");
654
689
  },
655
690
  createDefaultNewPrice: async (productId, payload) => {
656
691
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
657
692
  const res = await this.client.post(`/api/stripe/products/${productId}/prices/default-new`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
658
- return res.data;
693
+ return this.unwrapApiResponse(res, "Failed to create default price");
659
694
  },
660
695
  superAdminListAllProducts: async () => this.payments.listAllProductsSuperAdmin(),
661
696
  superAdminUpdateProduct: async (productId, updates) => this.payments.updateProductSuperAdmin(productId, updates),
@@ -663,42 +698,42 @@ var SPAPSClient = class {
663
698
  superAdminCreateProductWithPrice: async (applicationId, payload) => {
664
699
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
665
700
  const res = await this.client.post(`/api/stripe/products/super-admin/${applicationId}/with-price`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
666
- return res.data;
701
+ return this.unwrapApiResponse(res, "Failed to create product with price for application (super admin)");
667
702
  },
668
703
  superAdminCreatePriceAndSetDefault: async (productId, payload) => {
669
704
  if (!this.accessToken) throw new Error("Authentication required. Please authenticate first.");
670
705
  const res = await this.client.post(`/api/stripe/products/super-admin/${productId}/prices/default-new`, payload, { headers: { Authorization: `Bearer ${this.accessToken}` } });
671
- return res.data;
706
+ return this.unwrapApiResponse(res, "Failed to create price and set default (super admin)");
672
707
  },
673
708
  superAdminSetDefaultPrice: async (productId, payload) => this.payments.setDefaultPriceSuperAdmin(productId, payload)
674
709
  };
675
710
  sessions = {
676
711
  getCurrent: async () => {
677
712
  const res = await this.client.get("/api/sessions/current", this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
678
- return res.data;
713
+ return this.unwrapApiResponse(res, "Failed to get current session");
679
714
  },
680
715
  list: async (params = {}) => {
681
716
  const q = new URLSearchParams();
682
717
  if (params.limit) q.append("limit", String(params.limit));
683
718
  if (params.starting_after) q.append("starting_after", params.starting_after);
684
719
  const res = await this.client.get(`/api/sessions${q.toString() ? `?${q.toString()}` : ""}`, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
685
- return res.data;
720
+ return this.unwrapApiResponse(res, "Failed to list sessions");
686
721
  },
687
722
  validate: async () => {
688
723
  const res = await this.client.post("/api/sessions/validate", {}, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
689
- return res.data || { valid: true };
724
+ return this.unwrapApiResponse(res, "Failed to validate session");
690
725
  },
691
726
  revoke: async (sessionId) => {
692
727
  const res = await this.client.delete(`/api/sessions/${sessionId}`, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
693
- return res.data || { revoked: true };
728
+ return this.unwrapApiResponse(res, "Failed to revoke session");
694
729
  },
695
730
  revokeAll: async () => {
696
731
  const res = await this.client.delete("/api/sessions/all", this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
697
- return res.data || { revoked: true };
732
+ return this.unwrapApiResponse(res, "Failed to revoke all sessions");
698
733
  },
699
734
  touch: async () => {
700
735
  const res = await this.client.post("/api/sessions/touch", {}, this.accessToken ? { headers: { Authorization: `Bearer ${this.accessToken}` } } : void 0);
701
- return res.data || { touched: true };
736
+ return this.unwrapApiResponse(res, "Failed to touch session");
702
737
  }
703
738
  };
704
739
  // Stripe Methods
@@ -725,6 +760,19 @@ var SPAPSClient = class {
725
760
  amount
726
761
  });
727
762
  }
763
+ // Secure Messaging Methods
764
+ async createSecureMessage(payload) {
765
+ const response = await this.client.post("/api/secure-messages", payload);
766
+ return this.unwrapApiResponse(response, "Failed to create secure message");
767
+ }
768
+ async listSecureMessages() {
769
+ const response = await this.client.get("/api/secure-messages");
770
+ const payload = this.unwrapApiResponse(response, "Failed to list secure messages");
771
+ if (payload && Array.isArray(payload.messages)) {
772
+ return payload.messages;
773
+ }
774
+ return payload;
775
+ }
728
776
  // Admin Methods (Require admin privileges)
729
777
  /**
730
778
  * Create a new Stripe product (Admin required)
@@ -963,6 +1011,7 @@ export {
963
1011
  WalletUtils,
964
1012
  canAccessAdmin,
965
1013
  createPermissionChecker,
1014
+ createSecureMessageRequestSchema,
966
1015
  index_default as default,
967
1016
  defaultPermissionChecker,
968
1017
  getRoleAwareErrorMessage,
@@ -970,5 +1019,7 @@ export {
970
1019
  getUserRole,
971
1020
  hasPermission,
972
1021
  isAdminAccount,
1022
+ secureMessageMetadataSchema,
1023
+ secureMessageSchema,
973
1024
  verifyCryptoWebhookSignature
974
1025
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spaps-sdk",
3
- "version": "1.1.7",
3
+ "version": "1.1.8",
4
4
  "description": "Sweet Potato Authentication & Payment Service SDK - Zero-config client with built-in permission checking and role-based access control",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -44,7 +44,7 @@
44
44
  "email": "buildooor@gmail.com"
45
45
  },
46
46
  "dependencies": {
47
- "spaps-types": "^1.0.12",
47
+ "spaps-types": "^1.0.14",
48
48
  "axios": "^1.6.0",
49
49
  "cross-fetch": "^4.0.0"
50
50
  },
@@ -72,4 +72,4 @@
72
72
  "engines": {
73
73
  "node": ">=14.0.0"
74
74
  }
75
- }
75
+ }