@stackbe/sdk 0.3.0 → 0.4.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/README.md CHANGED
@@ -392,6 +392,54 @@ const stackbe = new StackBE({
392
392
  appId: 'app_...', // Required: Your App ID
393
393
  baseUrl: 'https://api.stackbe.io', // Optional: API base URL
394
394
  timeout: 30000, // Optional: Request timeout in ms
395
+
396
+ // Session caching (reduces API calls)
397
+ sessionCacheTTL: 120, // Optional: Cache sessions for 2 minutes
398
+
399
+ // Environment-aware redirects
400
+ devCallbackUrl: 'http://localhost:3000/auth/callback', // Optional: Auto-use in dev
401
+ });
402
+ ```
403
+
404
+ ### Session Caching
405
+
406
+ Enable session caching to reduce API calls on every request:
407
+
408
+ ```typescript
409
+ const stackbe = new StackBE({
410
+ apiKey,
411
+ appId,
412
+ sessionCacheTTL: 120, // Cache for 2 minutes
413
+ });
414
+
415
+ // Cached calls won't hit the API
416
+ const session1 = await stackbe.auth.getSession(token); // API call
417
+ const session2 = await stackbe.auth.getSession(token); // From cache
418
+
419
+ // Manually invalidate cache
420
+ stackbe.auth.invalidateSession(token);
421
+ stackbe.auth.clearCache(); // Clear all
422
+ ```
423
+
424
+ ### Environment-Aware Redirects
425
+
426
+ Auto-detect development environment for magic link redirects:
427
+
428
+ ```typescript
429
+ const stackbe = new StackBE({
430
+ apiKey,
431
+ appId,
432
+ devCallbackUrl: 'http://localhost:3000/auth/callback',
433
+ });
434
+
435
+ // In development (NODE_ENV !== 'production'), uses devCallbackUrl automatically
436
+ await stackbe.auth.sendMagicLink('user@example.com');
437
+ // Redirects to: http://localhost:3000/auth/callback
438
+
439
+ // In production, uses your configured auth callback URL
440
+ // Or pass explicit redirectUrl to override
441
+ await stackbe.auth.sendMagicLink('user@example.com', {
442
+ redirectUrl: 'https://myapp.com/custom-callback',
395
443
  });
396
444
  ```
397
445
 
package/dist/index.d.mts CHANGED
@@ -24,6 +24,30 @@ interface StackBEConfig {
24
24
  baseUrl?: string;
25
25
  /** Request timeout in milliseconds (default: 30000) */
26
26
  timeout?: number;
27
+ /**
28
+ * Session cache TTL in seconds (default: 0 = disabled).
29
+ * When set, getSession() results are cached to reduce API calls.
30
+ * @example
31
+ * ```typescript
32
+ * new StackBE({ apiKey, appId, sessionCacheTTL: 120 }) // Cache for 2 minutes
33
+ * ```
34
+ */
35
+ sessionCacheTTL?: number;
36
+ /**
37
+ * Development callback URL for magic link redirects.
38
+ * When set, this URL is used automatically when:
39
+ * - NODE_ENV !== 'production', or
40
+ * - useDev: true is passed to sendMagicLink()
41
+ * @example
42
+ * ```typescript
43
+ * new StackBE({
44
+ * apiKey,
45
+ * appId,
46
+ * devCallbackUrl: 'http://localhost:3000/auth/callback'
47
+ * })
48
+ * ```
49
+ */
50
+ devCallbackUrl?: string;
27
51
  }
28
52
  interface TrackUsageOptions {
29
53
  /** Quantity to track (default: 1) */
@@ -691,13 +715,37 @@ declare class SubscriptionsClient {
691
715
  isActive(customerId: string): Promise<boolean>;
692
716
  }
693
717
 
718
+ interface AuthClientOptions {
719
+ /** Session cache TTL in seconds (0 = disabled) */
720
+ sessionCacheTTL?: number;
721
+ /** Development callback URL for magic links */
722
+ devCallbackUrl?: string;
723
+ }
694
724
  declare class AuthClient {
695
725
  private http;
696
726
  private appId;
697
- constructor(http: HttpClient, appId: string);
727
+ private sessionCache;
728
+ private sessionCacheTTL;
729
+ private devCallbackUrl?;
730
+ constructor(http: HttpClient, appId: string, options?: AuthClientOptions);
731
+ /**
732
+ * Check if we're in a development environment.
733
+ */
734
+ private isDev;
735
+ /**
736
+ * Clear the session cache (useful for testing or logout).
737
+ */
738
+ clearCache(): void;
739
+ /**
740
+ * Remove a specific session from the cache.
741
+ */
742
+ invalidateSession(sessionToken: string): void;
698
743
  /**
699
744
  * Send a magic link email to a customer for passwordless authentication.
700
745
  *
746
+ * If `devCallbackUrl` is configured and we're in a dev environment (NODE_ENV !== 'production'),
747
+ * the dev callback URL will be used automatically.
748
+ *
701
749
  * @example
702
750
  * ```typescript
703
751
  * // Send magic link
@@ -708,7 +756,7 @@ declare class AuthClient {
708
756
  * redirectUrl: 'https://myapp.com/dashboard',
709
757
  * });
710
758
  *
711
- * // For localhost development
759
+ * // For localhost development (auto-detected if devCallbackUrl is configured)
712
760
  * await stackbe.auth.sendMagicLink('user@example.com', {
713
761
  * useDev: true,
714
762
  * });
@@ -748,6 +796,9 @@ declare class AuthClient {
748
796
  * Get the current session for an authenticated customer.
749
797
  * Use this to validate session tokens and get customer data.
750
798
  *
799
+ * If `sessionCacheTTL` is configured, results are cached to reduce API calls.
800
+ * Use `invalidateSession()` or `clearCache()` to manually clear cached sessions.
801
+ *
751
802
  * Returns session info including tenant and organization context extracted from the JWT.
752
803
  *
753
804
  * @example
package/dist/index.d.ts CHANGED
@@ -24,6 +24,30 @@ interface StackBEConfig {
24
24
  baseUrl?: string;
25
25
  /** Request timeout in milliseconds (default: 30000) */
26
26
  timeout?: number;
27
+ /**
28
+ * Session cache TTL in seconds (default: 0 = disabled).
29
+ * When set, getSession() results are cached to reduce API calls.
30
+ * @example
31
+ * ```typescript
32
+ * new StackBE({ apiKey, appId, sessionCacheTTL: 120 }) // Cache for 2 minutes
33
+ * ```
34
+ */
35
+ sessionCacheTTL?: number;
36
+ /**
37
+ * Development callback URL for magic link redirects.
38
+ * When set, this URL is used automatically when:
39
+ * - NODE_ENV !== 'production', or
40
+ * - useDev: true is passed to sendMagicLink()
41
+ * @example
42
+ * ```typescript
43
+ * new StackBE({
44
+ * apiKey,
45
+ * appId,
46
+ * devCallbackUrl: 'http://localhost:3000/auth/callback'
47
+ * })
48
+ * ```
49
+ */
50
+ devCallbackUrl?: string;
27
51
  }
28
52
  interface TrackUsageOptions {
29
53
  /** Quantity to track (default: 1) */
@@ -691,13 +715,37 @@ declare class SubscriptionsClient {
691
715
  isActive(customerId: string): Promise<boolean>;
692
716
  }
693
717
 
718
+ interface AuthClientOptions {
719
+ /** Session cache TTL in seconds (0 = disabled) */
720
+ sessionCacheTTL?: number;
721
+ /** Development callback URL for magic links */
722
+ devCallbackUrl?: string;
723
+ }
694
724
  declare class AuthClient {
695
725
  private http;
696
726
  private appId;
697
- constructor(http: HttpClient, appId: string);
727
+ private sessionCache;
728
+ private sessionCacheTTL;
729
+ private devCallbackUrl?;
730
+ constructor(http: HttpClient, appId: string, options?: AuthClientOptions);
731
+ /**
732
+ * Check if we're in a development environment.
733
+ */
734
+ private isDev;
735
+ /**
736
+ * Clear the session cache (useful for testing or logout).
737
+ */
738
+ clearCache(): void;
739
+ /**
740
+ * Remove a specific session from the cache.
741
+ */
742
+ invalidateSession(sessionToken: string): void;
698
743
  /**
699
744
  * Send a magic link email to a customer for passwordless authentication.
700
745
  *
746
+ * If `devCallbackUrl` is configured and we're in a dev environment (NODE_ENV !== 'production'),
747
+ * the dev callback URL will be used automatically.
748
+ *
701
749
  * @example
702
750
  * ```typescript
703
751
  * // Send magic link
@@ -708,7 +756,7 @@ declare class AuthClient {
708
756
  * redirectUrl: 'https://myapp.com/dashboard',
709
757
  * });
710
758
  *
711
- * // For localhost development
759
+ * // For localhost development (auto-detected if devCallbackUrl is configured)
712
760
  * await stackbe.auth.sendMagicLink('user@example.com', {
713
761
  * useDev: true,
714
762
  * });
@@ -748,6 +796,9 @@ declare class AuthClient {
748
796
  * Get the current session for an authenticated customer.
749
797
  * Use this to validate session tokens and get customer data.
750
798
  *
799
+ * If `sessionCacheTTL` is configured, results are cached to reduce API calls.
800
+ * Use `invalidateSession()` or `clearCache()` to manually clear cached sessions.
801
+ *
751
802
  * Returns session info including tenant and organization context extracted from the JWT.
752
803
  *
753
804
  * @example
package/dist/index.js CHANGED
@@ -697,13 +697,40 @@ function decodeJwt(token) {
697
697
  }
698
698
  }
699
699
  var AuthClient = class {
700
- constructor(http, appId) {
700
+ constructor(http, appId, options = {}) {
701
701
  this.http = http;
702
702
  this.appId = appId;
703
+ this.sessionCache = /* @__PURE__ */ new Map();
704
+ this.sessionCacheTTL = (options.sessionCacheTTL ?? 0) * 1e3;
705
+ this.devCallbackUrl = options.devCallbackUrl;
706
+ }
707
+ /**
708
+ * Check if we're in a development environment.
709
+ */
710
+ isDev() {
711
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
712
+ return true;
713
+ }
714
+ return false;
715
+ }
716
+ /**
717
+ * Clear the session cache (useful for testing or logout).
718
+ */
719
+ clearCache() {
720
+ this.sessionCache.clear();
721
+ }
722
+ /**
723
+ * Remove a specific session from the cache.
724
+ */
725
+ invalidateSession(sessionToken) {
726
+ this.sessionCache.delete(sessionToken);
703
727
  }
704
728
  /**
705
729
  * Send a magic link email to a customer for passwordless authentication.
706
730
  *
731
+ * If `devCallbackUrl` is configured and we're in a dev environment (NODE_ENV !== 'production'),
732
+ * the dev callback URL will be used automatically.
733
+ *
707
734
  * @example
708
735
  * ```typescript
709
736
  * // Send magic link
@@ -714,19 +741,26 @@ var AuthClient = class {
714
741
  * redirectUrl: 'https://myapp.com/dashboard',
715
742
  * });
716
743
  *
717
- * // For localhost development
744
+ * // For localhost development (auto-detected if devCallbackUrl is configured)
718
745
  * await stackbe.auth.sendMagicLink('user@example.com', {
719
746
  * useDev: true,
720
747
  * });
721
748
  * ```
722
749
  */
723
750
  async sendMagicLink(email, options = {}) {
751
+ let useDev = options.useDev;
752
+ let redirectUrl = options.redirectUrl;
753
+ if (!redirectUrl && this.devCallbackUrl) {
754
+ if (useDev || this.isDev()) {
755
+ redirectUrl = this.devCallbackUrl;
756
+ }
757
+ }
724
758
  return this.http.post(
725
759
  `/v1/apps/${this.appId}/auth/magic-link`,
726
760
  {
727
761
  email,
728
- redirectUrl: options.redirectUrl,
729
- useDev: options.useDev
762
+ redirectUrl,
763
+ useDev
730
764
  }
731
765
  );
732
766
  }
@@ -806,6 +840,9 @@ var AuthClient = class {
806
840
  * Get the current session for an authenticated customer.
807
841
  * Use this to validate session tokens and get customer data.
808
842
  *
843
+ * If `sessionCacheTTL` is configured, results are cached to reduce API calls.
844
+ * Use `invalidateSession()` or `clearCache()` to manually clear cached sessions.
845
+ *
809
846
  * Returns session info including tenant and organization context extracted from the JWT.
810
847
  *
811
848
  * @example
@@ -825,6 +862,15 @@ var AuthClient = class {
825
862
  * ```
826
863
  */
827
864
  async getSession(sessionToken) {
865
+ if (this.sessionCacheTTL > 0) {
866
+ const cached = this.sessionCache.get(sessionToken);
867
+ if (cached && cached.expiresAt > Date.now()) {
868
+ return cached.session;
869
+ }
870
+ if (cached) {
871
+ this.sessionCache.delete(sessionToken);
872
+ }
873
+ }
828
874
  try {
829
875
  const response = await fetch(
830
876
  `${this.http.baseUrl}/v1/apps/${this.appId}/auth/session`,
@@ -837,6 +883,7 @@ var AuthClient = class {
837
883
  );
838
884
  if (!response.ok) {
839
885
  if (response.status === 401) {
886
+ this.sessionCache.delete(sessionToken);
840
887
  return null;
841
888
  }
842
889
  throw new StackBEError("Failed to get session", response.status, "SESSION_INVALID");
@@ -851,7 +898,7 @@ var AuthClient = class {
851
898
  organizationId = payload.organizationId;
852
899
  orgRole = payload.orgRole;
853
900
  }
854
- return {
901
+ const session = {
855
902
  valid: data.valid ?? true,
856
903
  customerId: data.customerId,
857
904
  email: data.email,
@@ -863,6 +910,13 @@ var AuthClient = class {
863
910
  subscription: data.subscription,
864
911
  entitlements: data.entitlements
865
912
  };
913
+ if (this.sessionCacheTTL > 0) {
914
+ this.sessionCache.set(sessionToken, {
915
+ session,
916
+ expiresAt: Date.now() + this.sessionCacheTTL
917
+ });
918
+ }
919
+ return session;
866
920
  } catch (error) {
867
921
  if (error instanceof StackBEError) {
868
922
  throw error;
@@ -978,7 +1032,10 @@ var StackBE = class {
978
1032
  this.customers = new CustomersClient(this.http);
979
1033
  this.checkout = new CheckoutClient(this.http, config.appId);
980
1034
  this.subscriptions = new SubscriptionsClient(this.http);
981
- this.auth = new AuthClient(this.http, config.appId);
1035
+ this.auth = new AuthClient(this.http, config.appId, {
1036
+ sessionCacheTTL: config.sessionCacheTTL,
1037
+ devCallbackUrl: config.devCallbackUrl
1038
+ });
982
1039
  }
983
1040
  /**
984
1041
  * Create a middleware for Express that tracks usage automatically.
package/dist/index.mjs CHANGED
@@ -664,13 +664,40 @@ function decodeJwt(token) {
664
664
  }
665
665
  }
666
666
  var AuthClient = class {
667
- constructor(http, appId) {
667
+ constructor(http, appId, options = {}) {
668
668
  this.http = http;
669
669
  this.appId = appId;
670
+ this.sessionCache = /* @__PURE__ */ new Map();
671
+ this.sessionCacheTTL = (options.sessionCacheTTL ?? 0) * 1e3;
672
+ this.devCallbackUrl = options.devCallbackUrl;
673
+ }
674
+ /**
675
+ * Check if we're in a development environment.
676
+ */
677
+ isDev() {
678
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
679
+ return true;
680
+ }
681
+ return false;
682
+ }
683
+ /**
684
+ * Clear the session cache (useful for testing or logout).
685
+ */
686
+ clearCache() {
687
+ this.sessionCache.clear();
688
+ }
689
+ /**
690
+ * Remove a specific session from the cache.
691
+ */
692
+ invalidateSession(sessionToken) {
693
+ this.sessionCache.delete(sessionToken);
670
694
  }
671
695
  /**
672
696
  * Send a magic link email to a customer for passwordless authentication.
673
697
  *
698
+ * If `devCallbackUrl` is configured and we're in a dev environment (NODE_ENV !== 'production'),
699
+ * the dev callback URL will be used automatically.
700
+ *
674
701
  * @example
675
702
  * ```typescript
676
703
  * // Send magic link
@@ -681,19 +708,26 @@ var AuthClient = class {
681
708
  * redirectUrl: 'https://myapp.com/dashboard',
682
709
  * });
683
710
  *
684
- * // For localhost development
711
+ * // For localhost development (auto-detected if devCallbackUrl is configured)
685
712
  * await stackbe.auth.sendMagicLink('user@example.com', {
686
713
  * useDev: true,
687
714
  * });
688
715
  * ```
689
716
  */
690
717
  async sendMagicLink(email, options = {}) {
718
+ let useDev = options.useDev;
719
+ let redirectUrl = options.redirectUrl;
720
+ if (!redirectUrl && this.devCallbackUrl) {
721
+ if (useDev || this.isDev()) {
722
+ redirectUrl = this.devCallbackUrl;
723
+ }
724
+ }
691
725
  return this.http.post(
692
726
  `/v1/apps/${this.appId}/auth/magic-link`,
693
727
  {
694
728
  email,
695
- redirectUrl: options.redirectUrl,
696
- useDev: options.useDev
729
+ redirectUrl,
730
+ useDev
697
731
  }
698
732
  );
699
733
  }
@@ -773,6 +807,9 @@ var AuthClient = class {
773
807
  * Get the current session for an authenticated customer.
774
808
  * Use this to validate session tokens and get customer data.
775
809
  *
810
+ * If `sessionCacheTTL` is configured, results are cached to reduce API calls.
811
+ * Use `invalidateSession()` or `clearCache()` to manually clear cached sessions.
812
+ *
776
813
  * Returns session info including tenant and organization context extracted from the JWT.
777
814
  *
778
815
  * @example
@@ -792,6 +829,15 @@ var AuthClient = class {
792
829
  * ```
793
830
  */
794
831
  async getSession(sessionToken) {
832
+ if (this.sessionCacheTTL > 0) {
833
+ const cached = this.sessionCache.get(sessionToken);
834
+ if (cached && cached.expiresAt > Date.now()) {
835
+ return cached.session;
836
+ }
837
+ if (cached) {
838
+ this.sessionCache.delete(sessionToken);
839
+ }
840
+ }
795
841
  try {
796
842
  const response = await fetch(
797
843
  `${this.http.baseUrl}/v1/apps/${this.appId}/auth/session`,
@@ -804,6 +850,7 @@ var AuthClient = class {
804
850
  );
805
851
  if (!response.ok) {
806
852
  if (response.status === 401) {
853
+ this.sessionCache.delete(sessionToken);
807
854
  return null;
808
855
  }
809
856
  throw new StackBEError("Failed to get session", response.status, "SESSION_INVALID");
@@ -818,7 +865,7 @@ var AuthClient = class {
818
865
  organizationId = payload.organizationId;
819
866
  orgRole = payload.orgRole;
820
867
  }
821
- return {
868
+ const session = {
822
869
  valid: data.valid ?? true,
823
870
  customerId: data.customerId,
824
871
  email: data.email,
@@ -830,6 +877,13 @@ var AuthClient = class {
830
877
  subscription: data.subscription,
831
878
  entitlements: data.entitlements
832
879
  };
880
+ if (this.sessionCacheTTL > 0) {
881
+ this.sessionCache.set(sessionToken, {
882
+ session,
883
+ expiresAt: Date.now() + this.sessionCacheTTL
884
+ });
885
+ }
886
+ return session;
833
887
  } catch (error) {
834
888
  if (error instanceof StackBEError) {
835
889
  throw error;
@@ -945,7 +999,10 @@ var StackBE = class {
945
999
  this.customers = new CustomersClient(this.http);
946
1000
  this.checkout = new CheckoutClient(this.http, config.appId);
947
1001
  this.subscriptions = new SubscriptionsClient(this.http);
948
- this.auth = new AuthClient(this.http, config.appId);
1002
+ this.auth = new AuthClient(this.http, config.appId, {
1003
+ sessionCacheTTL: config.sessionCacheTTL,
1004
+ devCallbackUrl: config.devCallbackUrl
1005
+ });
949
1006
  }
950
1007
  /**
951
1008
  * Create a middleware for Express that tracks usage automatically.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackbe/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Official JavaScript/TypeScript SDK for StackBE - the billing backend for your side project",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",