@sparkvault/sdk-js 2.2.2 → 2.2.4

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.
@@ -32,6 +32,38 @@ class ValidationError extends SparkVaultError {
32
32
  Object.setPrototypeOf(this, ValidationError.prototype);
33
33
  }
34
34
  }
35
+ /**
36
+ * Plan required gate (402 PLAN_REQUIRED) — the account has no active
37
+ * subscription and attempted a billable/create action. Surface a subscribe CTA
38
+ * to admins, or "ask your account admin" to members.
39
+ */
40
+ class PlanRequiredError extends SparkVaultError {
41
+ constructor(message, details) {
42
+ super(message, 'PLAN_REQUIRED', 402, details);
43
+ this.name = 'PlanRequiredError';
44
+ Object.setPrototypeOf(this, PlanRequiredError.prototype);
45
+ }
46
+ }
47
+ /**
48
+ * Quota exceeded gate (402 QUOTA_EXCEEDED) — a pooled-capacity or seat limit is
49
+ * exhausted. `resource` identifies which pool so callers can branch on the CTA
50
+ * (add a capacity block for storage/bandwidth, free a seat for seats).
51
+ */
52
+ class QuotaExceededError extends SparkVaultError {
53
+ constructor(message, details) {
54
+ super(message, 'QUOTA_EXCEEDED', 402, details);
55
+ this.name = 'QuotaExceededError';
56
+ const resource = details?.resource;
57
+ this.resource =
58
+ resource === 'storage' ||
59
+ resource === 'bandwidth' ||
60
+ resource === 'seats' ||
61
+ resource === 'identity'
62
+ ? resource
63
+ : undefined;
64
+ Object.setPrototypeOf(this, QuotaExceededError.prototype);
65
+ }
66
+ }
35
67
  class NetworkError extends SparkVaultError {
36
68
  constructor(message, details) {
37
69
  super(message, 'network_error', undefined, details);
@@ -205,6 +237,7 @@ class HttpClient {
205
237
  }
206
238
  return {
207
239
  data: this.unwrapApiResponse(parsed),
240
+ meta: this.extractResponseMeta(parsed),
208
241
  status: response.status,
209
242
  headers: response.headers,
210
243
  };
@@ -265,6 +298,11 @@ class HttpClient {
265
298
  return new ValidationError(message, details);
266
299
  case 401:
267
300
  return new AuthenticationError(message, details);
301
+ case 402:
302
+ if (code === 'QUOTA_EXCEEDED')
303
+ return new QuotaExceededError(message, details);
304
+ // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
305
+ return new PlanRequiredError(message, details);
268
306
  case 403:
269
307
  return new AuthorizationError(message, details);
270
308
  default:
@@ -280,6 +318,19 @@ class HttpClient {
280
318
  }
281
319
  return data;
282
320
  }
321
+ /**
322
+ * Pull the `meta` envelope (carrying `pools` capacity snapshots) off a
323
+ * standard `{ data, meta }` response. Returns undefined for bare responses.
324
+ */
325
+ extractResponseMeta(data) {
326
+ if (typeof data === 'object' && data !== null) {
327
+ const record = data;
328
+ if (typeof record.meta === 'object' && record.meta !== null) {
329
+ return record.meta;
330
+ }
331
+ }
332
+ return undefined;
333
+ }
283
334
  get(path, options) {
284
335
  return this.request(path, { ...options, method: 'GET' });
285
336
  }
@@ -1039,6 +1090,28 @@ class IdentityApi extends SparkVaultApi {
1039
1090
  ...this.buildAuthContextParams(authContext),
1040
1091
  });
1041
1092
  }
1093
+ /**
1094
+ * Claim the SparkLink verification result by kindling — the WebSocket-loss
1095
+ * fallback. The SDK calls this when its socket was suspended with the tab and
1096
+ * it refocuses. Returns the verified result, or null while still pending (not
1097
+ * yet clicked) or already consumed. The read burns the server-side spark, so
1098
+ * the result can be claimed exactly once.
1099
+ */
1100
+ async consumeSparkLinkResult(kindling) {
1101
+ const data = await this.request('GET', `/sparklink/result?kindling=${encodeURIComponent(kindling)}`);
1102
+ if (!data || typeof data !== 'object' || typeof data.token !== 'string') {
1103
+ return null;
1104
+ }
1105
+ return {
1106
+ token: data.token,
1107
+ identity: data.identity,
1108
+ identityType: data.identityType || 'email',
1109
+ svid: typeof data.svid === 'string' ? data.svid : undefined,
1110
+ sessionId: typeof data.session_id === 'string' ? data.session_id : undefined,
1111
+ refreshToken: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
1112
+ redirect: typeof data.redirect === 'string' ? data.redirect : undefined,
1113
+ };
1114
+ }
1042
1115
  }
1043
1116
  class IdentityApiError extends SparkVaultError {
1044
1117
  constructor(message, code, statusCode, details) {
@@ -1791,6 +1864,7 @@ class SparkLinkHandler {
1791
1864
  success: true,
1792
1865
  sparkId: result.sparkId,
1793
1866
  expiresAt: result.expiresAt,
1867
+ kindling: result.kindling,
1794
1868
  };
1795
1869
  }
1796
1870
  catch (error) {
@@ -5529,6 +5603,13 @@ class IdentityRenderer {
5529
5603
  this.focusTimeoutId = null;
5530
5604
  // SparkLink WebSocket
5531
5605
  this.sparkLinkWs = null;
5606
+ // SparkLink WebSocket-loss fallback: the login kindling lets the SDK reclaim
5607
+ // the verified result if the socket was suspended with the tab (mobile). The
5608
+ // visibility handler fires the single re-check on refocus.
5609
+ this.sparkLinkKindling = null;
5610
+ this.sparkLinkVisibilityHandler = null;
5611
+ this.sparkLinkClaiming = false;
5612
+ this.sparkLinkRetryTimer = null;
5532
5613
  this.container = container;
5533
5614
  this.api = api;
5534
5615
  this.options = options;
@@ -5879,6 +5960,11 @@ class IdentityRenderer {
5879
5960
  * actual list of alternatives instead of bouncing back to passkey.
5880
5961
  */
5881
5962
  async showMethodSelect(options = {}) {
5963
+ // Leaving the SparkLink waiting view (e.g. "Choose another method") must
5964
+ // tear down its WebSocket + refocus listeners and clear the kindling, or a
5965
+ // later tab refocus would fire a stale claim for an abandoned flow.
5966
+ // Idempotent — a no-op when SparkLink was never armed.
5967
+ this.cleanupSparkLink();
5882
5968
  const autoRoute = options.autoRoute !== false;
5883
5969
  if (!this.sdkConfig)
5884
5970
  return;
@@ -6044,6 +6130,11 @@ class IdentityRenderer {
6044
6130
  });
6045
6131
  return;
6046
6132
  }
6133
+ // Arm the WebSocket-loss fallback: keep the kindling and re-check for
6134
+ // the result whenever the tab is brought back to the foreground with
6135
+ // a dead socket (the mobile email round-trip).
6136
+ this.sparkLinkKindling = result.kindling ?? null;
6137
+ this.armSparkLinkRefocusClaim();
6047
6138
  this.setState({
6048
6139
  view: 'sparklink-waiting',
6049
6140
  email: this.recipient,
@@ -6561,7 +6652,14 @@ class IdentityRenderer {
6561
6652
  * delegate navigation entirely to the SDK.
6562
6653
  */
6563
6654
  async handleSparkLinkVerified(result) {
6655
+ // Burn the server-side fallback spark so a completed login never leaves a
6656
+ // second claimable auth path floating around. Capture the kindling before
6657
+ // cleanup clears it; fire-and-forget (the WS path may already have it).
6658
+ const kindling = this.sparkLinkKindling;
6564
6659
  this.cleanupSparkLink();
6660
+ if (kindling) {
6661
+ void this.api.consumeSparkLinkResult(kindling).catch(() => { });
6662
+ }
6565
6663
  // Passkey upsell only when there's no redirect target — once we have
6566
6664
  // a destination we go there immediately, no upsell.
6567
6665
  if (!result.redirect && await this.shouldShowPasskeyPrompt()) {
@@ -6572,11 +6670,11 @@ class IdentityRenderer {
6572
6670
  });
6573
6671
  return;
6574
6672
  }
6575
- this.close();
6576
- // Hand the full result (including redirect) to the host first so the
6577
- // page-level handler can do app-specific work (logging, navigation,
6578
- // etc.) before we steal the browsing context with a navigation.
6673
+ // Hand the full result (including redirect) to the host BEFORE tearing down
6674
+ // the modal, so the host's onSuccess can act (logging, navigation) without
6675
+ // racing the teardown of the browsing context.
6579
6676
  this.safeOnSuccess(result);
6677
+ this.close();
6580
6678
  // SDK-side fallback navigation. If the host already navigated this is
6581
6679
  // a no-op (the document is already unloading); if not, this rescues
6582
6680
  // simple-mode flows whose host forgot to act on result.redirect.
@@ -6584,6 +6682,67 @@ class IdentityRenderer {
6584
6682
  navigateWith(this.options, result.redirect);
6585
6683
  }
6586
6684
  }
6685
+ /**
6686
+ * Arm the WebSocket-loss fallback for the waiting screen.
6687
+ *
6688
+ * While waiting for the emailed link, the socket can be dropped when the tab
6689
+ * is suspended (mobile: the user leaves to the mail app). On refocus, if the
6690
+ * socket is no longer open, reclaim the verified result once by kindling. A
6691
+ * single ~2s retry covers returning before the server finished writing it.
6692
+ * Deliberately NOT a polling loop — it fires only on refocus, and only when
6693
+ * the socket is actually gone.
6694
+ */
6695
+ armSparkLinkRefocusClaim() {
6696
+ if (this.sparkLinkVisibilityHandler || !this.sparkLinkKindling)
6697
+ return;
6698
+ if (typeof document === 'undefined')
6699
+ return;
6700
+ const handler = () => {
6701
+ if (typeof document !== 'undefined' && document.visibilityState !== 'visible')
6702
+ return;
6703
+ // Healthy socket → the push path owns completion; nothing to reclaim.
6704
+ if (this.sparkLinkWs && this.sparkLinkWs.readyState === WebSocket.OPEN)
6705
+ return;
6706
+ void this.claimSparkLinkResult(true);
6707
+ };
6708
+ this.sparkLinkVisibilityHandler = handler;
6709
+ document.addEventListener('visibilitychange', handler);
6710
+ if (typeof window !== 'undefined') {
6711
+ window.addEventListener('pageshow', handler);
6712
+ }
6713
+ }
6714
+ /**
6715
+ * Reclaim the verified result by kindling. Single attempt; if still pending
6716
+ * and allowRetry, schedule exactly one ~2s retry, then stop (the next refocus
6717
+ * or Resend can try again).
6718
+ */
6719
+ async claimSparkLinkResult(allowRetry) {
6720
+ const kindling = this.sparkLinkKindling;
6721
+ if (!kindling || this.sparkLinkClaiming)
6722
+ return;
6723
+ this.sparkLinkClaiming = true;
6724
+ let result = null;
6725
+ try {
6726
+ result = await this.api.consumeSparkLinkResult(kindling);
6727
+ }
6728
+ catch {
6729
+ result = null;
6730
+ }
6731
+ this.sparkLinkClaiming = false;
6732
+ if (result) {
6733
+ await this.handleSparkLinkVerified(result);
6734
+ return;
6735
+ }
6736
+ // Pending — the click may still be processing server-side. One short retry,
6737
+ // then stop. No ongoing polling. Tracked so cleanup can cancel it.
6738
+ if (allowRetry && this.sparkLinkKindling === kindling) {
6739
+ this.sparkLinkRetryTimer = setTimeout(() => {
6740
+ this.sparkLinkRetryTimer = null;
6741
+ if (this.sparkLinkKindling === kindling)
6742
+ void this.claimSparkLinkResult(false);
6743
+ }, 2000);
6744
+ }
6745
+ }
6587
6746
  /**
6588
6747
  * Clean up SparkLink WebSocket connection.
6589
6748
  */
@@ -6595,6 +6754,20 @@ class IdentityRenderer {
6595
6754
  this.sparkLinkWs.close();
6596
6755
  this.sparkLinkWs = null;
6597
6756
  }
6757
+ if (this.sparkLinkVisibilityHandler) {
6758
+ if (typeof document !== 'undefined') {
6759
+ document.removeEventListener('visibilitychange', this.sparkLinkVisibilityHandler);
6760
+ }
6761
+ if (typeof window !== 'undefined') {
6762
+ window.removeEventListener('pageshow', this.sparkLinkVisibilityHandler);
6763
+ }
6764
+ this.sparkLinkVisibilityHandler = null;
6765
+ }
6766
+ if (this.sparkLinkRetryTimer !== null) {
6767
+ clearTimeout(this.sparkLinkRetryTimer);
6768
+ this.sparkLinkRetryTimer = null;
6769
+ }
6770
+ this.sparkLinkKindling = null;
6598
6771
  }
6599
6772
  /**
6600
6773
  * Handle resending SparkLink.
@@ -6621,6 +6794,10 @@ class IdentityRenderer {
6621
6794
  }
6622
6795
  const result = await this.sparkLinkHandler.send(wsResult.connectionId);
6623
6796
  if (result.success) {
6797
+ // Re-arm the fallback against the resend's fresh kindling (openSparkLink-
6798
+ // WebSocket cleared the previous one).
6799
+ this.sparkLinkKindling = result.kindling ?? null;
6800
+ this.armSparkLinkRefocusClaim();
6624
6801
  this.setState({
6625
6802
  view: 'sparklink-waiting',
6626
6803
  email: this.recipient,
@@ -11171,5 +11348,5 @@ if (typeof window !== 'undefined') {
11171
11348
  window.SparkVault = instance ?? SparkVault;
11172
11349
  }
11173
11350
 
11174
- export { AuthenticationError, AuthorizationError, NetworkError, PopupBlockedError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
11351
+ export { AuthenticationError, AuthorizationError, NetworkError, PlanRequiredError, PopupBlockedError, QuotaExceededError, SparkVault, SparkVaultError, TimeoutError, UserCancelledError, ValidationError, SparkVault as default, logger, setDebugMode };
11175
11352
  //# sourceMappingURL=sparkvault.esm.js.map