@sparkvault/sdk-js 8.13.1 → 8.15.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.
@@ -59,6 +59,19 @@ class QuotaExceededError extends SparkVaultError {
59
59
  Object.setPrototypeOf(this, QuotaExceededError.prototype);
60
60
  }
61
61
  }
62
+ /**
63
+ * Notify subscription gate (403 NOTIFY_SUBSCRIPTION_REQUIRED) — the account has
64
+ * no active Notify subscription and attempted a send. Distinct from a generic
65
+ * authorization failure: the credential is fine and re-authenticating changes
66
+ * nothing, so surface a subscribe CTA rather than a sign-in prompt.
67
+ */
68
+ class NotifySubscriptionRequiredError extends SparkVaultError {
69
+ constructor(message, details) {
70
+ super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details);
71
+ this.name = 'NotifySubscriptionRequiredError';
72
+ Object.setPrototypeOf(this, NotifySubscriptionRequiredError.prototype);
73
+ }
74
+ }
62
75
  class NetworkError extends SparkVaultError {
63
76
  constructor(message, details) {
64
77
  super(message, 'network_error', undefined, details);
@@ -321,6 +334,11 @@ class HttpClient {
321
334
  // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
322
335
  return new PlanRequiredError(message, details);
323
336
  case 403:
337
+ // A Notify send refused for want of a subscription is a billing gate, not
338
+ // a credential problem — give it its own catchable type.
339
+ if (code === 'NOTIFY_SUBSCRIPTION_REQUIRED') {
340
+ return new NotifySubscriptionRequiredError(message, details);
341
+ }
324
342
  return new AuthorizationError(message, details);
325
343
  default:
326
344
  return new SparkVaultError(message, code, status, details);
@@ -844,6 +862,12 @@ function buildSigninUrl(config, options, extras) {
844
862
  params.set('mode', 'simple');
845
863
  params.set('session', authContext.simpleMode.sessionId);
846
864
  }
865
+ // `prompt` is validated here, the single serialization point: only the exact
866
+ // literal reaches the sign-in page; anything else is silently dropped, so a
867
+ // plain-JS caller passing junk degrades to the default behavior.
868
+ if (options.prompt === 'select_account') {
869
+ params.set('prompt', 'select_account');
870
+ }
847
871
  if (extras) {
848
872
  params.set('redirect_uri', extras.redirectUri);
849
873
  params.set('state', extras.state);
@@ -8544,17 +8568,67 @@ const PORTAL_SECTIONS = ['home', 'identity', 'security', 'sessions', 'sites'];
8544
8568
  // listener but not sessionStorage) is what lets the next load self-heal.
8545
8569
  const PENDING_KEY = 'sv_signin_pending';
8546
8570
  const PENDING_TTL_MS = 10 * 60 * 1000;
8547
- /** True when the pending marker is present and still within its TTL. */
8548
- function hasFreshPendingMarker() {
8571
+ // One-shot: the identifier the recovery bounce is re-minting for. Written only
8572
+ // by the recovery bounce; the return leg consumes it to verify the redeemed
8573
+ // result is for that same account (see consumeHandoffFragment).
8574
+ const RECOVERY_HINT_KEY = 'sv_recovery_hint';
8575
+ /**
8576
+ * Normalize an identifier for equality, mirroring the server: trim, and
8577
+ * lowercase emails (a value containing '@'). Phones compare trimmed-exact.
8578
+ */
8579
+ function normalizeIdentity(value) {
8580
+ const trimmed = value.trim();
8581
+ return trimmed.includes('@') ? trimmed.toLowerCase() : trimmed;
8582
+ }
8583
+ /**
8584
+ * Read and parse the pending marker — JSON `{ at, hint }`, where `hint` is the
8585
+ * email or phone the sign-in was started with (null when the flow collects the
8586
+ * identifier itself). A bare-timestamp value is accepted as `{ at, hint: null }`:
8587
+ * markers live at most 10 minutes in sessionStorage, so any such value
8588
+ * disappears within one deploy window of this parser going live — the fallback
8589
+ * is bounded and never grows. Anything unreadable yields null.
8590
+ */
8591
+ function readPendingMarker() {
8549
8592
  let raw = null;
8550
8593
  try {
8551
8594
  raw = sessionStorage.getItem(PENDING_KEY);
8552
8595
  }
8553
8596
  catch {
8554
- return false;
8597
+ return null;
8598
+ }
8599
+ if (!raw) {
8600
+ return null;
8601
+ }
8602
+ let at = NaN;
8603
+ let hint = null;
8604
+ try {
8605
+ const parsed = JSON.parse(raw);
8606
+ if (typeof parsed === 'object' && parsed !== null) {
8607
+ const marker = parsed;
8608
+ if (typeof marker.at === 'number') {
8609
+ at = marker.at;
8610
+ }
8611
+ if (typeof marker.hint === 'string' && marker.hint) {
8612
+ hint = marker.hint;
8613
+ }
8614
+ }
8615
+ else if (typeof parsed === 'number') {
8616
+ // A bare timestamp parses as a JSON number.
8617
+ at = parsed;
8618
+ }
8555
8619
  }
8556
- const at = raw ? Number(raw) : NaN;
8557
- return Number.isFinite(at) && Date.now() - at < PENDING_TTL_MS;
8620
+ catch {
8621
+ at = Number(raw);
8622
+ }
8623
+ return Number.isFinite(at) ? { at, hint } : null;
8624
+ }
8625
+ /** True while a marker is within the self-heal TTL. */
8626
+ function isFreshPendingMarker(marker) {
8627
+ return marker !== null && Date.now() - marker.at < PENDING_TTL_MS;
8628
+ }
8629
+ /** True when the pending marker is present and still within its TTL. */
8630
+ function hasFreshPendingMarker() {
8631
+ return isFreshPendingMarker(readPendingMarker());
8558
8632
  }
8559
8633
  /**
8560
8634
  * Whether `handleRedirectResult()` has anything to do on this load — a returned
@@ -8824,7 +8898,8 @@ class IdentityModule {
8824
8898
  // the backgrounded opener tab, killing the postMessage listener),
8825
8899
  // handleRedirectResult() can silently self-heal on the next load from
8826
8900
  // the SSO session the popup login established.
8827
- this.markSignInPending();
8901
+ const pendingHint = mergedOptions.email || mergedOptions.phone || null;
8902
+ this.markSignInPending(pendingHint);
8828
8903
  this.launcher = new DialogLauncher(this.config, this.api, mergedOptions, {
8829
8904
  onSuccess: (result) => { this.clearSignInPending(); hostCallbacks.onSuccess(result); },
8830
8905
  onError: (error) => { this.clearSignInPending(); hostCallbacks.onError(error); },
@@ -8833,7 +8908,7 @@ class IdentityModule {
8833
8908
  // no-result end retires the marker (no spurious bounce on a reload
8834
8909
  // while the retry alert is up); "Try again" re-arms it.
8835
8910
  onPopupClosedUnresolved: () => this.clearSignInPending(),
8836
- onPopupReopened: () => this.markSignInPending(),
8911
+ onPopupReopened: () => this.markSignInPending(pendingHint),
8837
8912
  // COOP-severed popup: postMessage can never deliver, so switch this tab
8838
8913
  // to the redirect flow (returns via handleRedirectResult). The pending
8839
8914
  // marker stays armed — the returned #sv_code fragment retires it.
@@ -8871,6 +8946,7 @@ class IdentityModule {
8871
8946
  email: options.email,
8872
8947
  phone: options.phone,
8873
8948
  authContext: options.authContext,
8949
+ prompt: options.prompt,
8874
8950
  onSuccess: options.onSuccess,
8875
8951
  onError: options.onError,
8876
8952
  onCancel: options.onCancel,
@@ -8986,8 +9062,9 @@ class IdentityModule {
8986
9062
  }
8987
9063
  // No returned result. If a sign-in was in flight and its result never
8988
9064
  // arrived, self-heal once from the SSO session (mobile opener-tab discard).
8989
- if (this.consumeSignInPending()) {
8990
- await this.startRecoveryBounce();
9065
+ const pending = this.consumeSignInPending();
9066
+ if (pending.fresh) {
9067
+ await this.startRecoveryBounce(pending.hint);
8991
9068
  }
8992
9069
  return null;
8993
9070
  }
@@ -9004,9 +9081,11 @@ class IdentityModule {
9004
9081
  // (and a StrictMode double-invocation finds an empty hash and no-ops).
9005
9082
  let expectedState = null;
9006
9083
  let codeVerifier = null;
9084
+ let expectedRecoveryIdentity = null;
9007
9085
  try {
9008
9086
  expectedState = sessionStorage.getItem('sv_oauth_state');
9009
9087
  codeVerifier = sessionStorage.getItem('sv_pkce_verifier');
9088
+ expectedRecoveryIdentity = sessionStorage.getItem(RECOVERY_HINT_KEY);
9010
9089
  this.clearOneShotAuthState();
9011
9090
  }
9012
9091
  catch {
@@ -9036,6 +9115,18 @@ class IdentityModule {
9036
9115
  sessionId: raw.session_id ?? undefined,
9037
9116
  refreshToken: raw.refresh_token ?? undefined,
9038
9117
  };
9118
+ // A recovery bounce carries the identifier the interrupted sign-in was
9119
+ // addressing, but /sso treats a hint matching no hub session like no hint
9120
+ // at all (anti-oracle) — so the bounce can come back holding a DIFFERENT
9121
+ // single-eligible account. The client is the one place that knows which
9122
+ // account the person was signing in to: a mismatched result is discarded,
9123
+ // never handed to the host (a wrong-account handoff). Silent — no
9124
+ // onError — falling through to interactive sign-in, matching the recovery
9125
+ // flow's non-oracle posture.
9126
+ if (expectedRecoveryIdentity &&
9127
+ normalizeIdentity(expectedRecoveryIdentity) !== normalizeIdentity(result.identity)) {
9128
+ return null;
9129
+ }
9039
9130
  options.onSuccess?.(result);
9040
9131
  return result;
9041
9132
  }
@@ -9054,11 +9145,41 @@ class IdentityModule {
9054
9145
  * so a hostile/degraded environment simply never recovers rather than
9055
9146
  * erroring.
9056
9147
  */
9057
- async startRecoveryBounce() {
9058
- const nav = await this.prepareHandoffNavigation(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
9148
+ async startRecoveryBounce(loginHint) {
9149
+ const sso = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);
9150
+ // With several hub sessions, login_hint tells /sso which account the
9151
+ // interrupted sign-in was addressing, so recovery never re-mints another.
9152
+ // Also stash it one-shot: a hint matching no hub session deliberately
9153
+ // behaves server-side like no hint at all (anti-oracle), so the return leg
9154
+ // must verify the redeemed identity is the one this sign-in was for.
9155
+ try {
9156
+ if (loginHint) {
9157
+ sessionStorage.setItem(RECOVERY_HINT_KEY, loginHint);
9158
+ }
9159
+ else {
9160
+ sessionStorage.removeItem(RECOVERY_HINT_KEY);
9161
+ }
9162
+ }
9163
+ catch {
9164
+ // No storage → prepareHandoffNavigation bails below; nothing to verify.
9165
+ }
9166
+ if (loginHint) {
9167
+ sso.searchParams.set('login_hint', loginHint);
9168
+ }
9169
+ const nav = await this.prepareHandoffNavigation(sso.toString());
9059
9170
  if (nav) {
9060
9171
  window.location.assign(nav);
9061
9172
  }
9173
+ else {
9174
+ // The bounce never left (no storage or WebCrypto) — retire the stash so
9175
+ // it cannot linger into an unrelated later return leg.
9176
+ try {
9177
+ sessionStorage.removeItem(RECOVERY_HINT_KEY);
9178
+ }
9179
+ catch {
9180
+ // Storage disabled: nothing was persisted, nothing to clear.
9181
+ }
9182
+ }
9062
9183
  }
9063
9184
  /**
9064
9185
  * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
@@ -9118,9 +9239,16 @@ class IdentityModule {
9118
9239
  url.searchParams.set('code_challenge', codeChallenge);
9119
9240
  return url.toString();
9120
9241
  }
9121
- markSignInPending() {
9242
+ /**
9243
+ * Arm the self-heal marker for an in-flight sign-in. `hint` is the identifier
9244
+ * (email or phone) the sign-in was started with, when the caller supplied
9245
+ * one — the recovery bounce forwards it as the /sso `login_hint`, so with
9246
+ * several hub sessions recovery re-mints the account this sign-in was for,
9247
+ * never a different one.
9248
+ */
9249
+ markSignInPending(hint) {
9122
9250
  try {
9123
- sessionStorage.setItem(PENDING_KEY, String(Date.now()));
9251
+ sessionStorage.setItem(PENDING_KEY, JSON.stringify({ at: Date.now(), hint }));
9124
9252
  }
9125
9253
  catch {
9126
9254
  // No storage → no self-heal; the popup still delivers when it can.
@@ -9134,11 +9262,16 @@ class IdentityModule {
9134
9262
  // Nothing to clear.
9135
9263
  }
9136
9264
  }
9137
- /** True once (then cleared) if a recent sign-in is still awaiting its result. */
9265
+ /**
9266
+ * Consume the pending marker: `fresh` is true once (then cleared) if a recent
9267
+ * sign-in is still awaiting its result; `hint` is the identifier that sign-in
9268
+ * carried, for the recovery bounce's `login_hint`.
9269
+ */
9138
9270
  consumeSignInPending() {
9139
- const fresh = hasFreshPendingMarker();
9271
+ const marker = readPendingMarker();
9272
+ const fresh = isFreshPendingMarker(marker);
9140
9273
  this.clearSignInPending();
9141
- return fresh;
9274
+ return { fresh, hint: fresh ? marker.hint : null };
9142
9275
  }
9143
9276
  /** Remove the result fragment from the URL bar (and history entry). */
9144
9277
  clearUrlFragment() {
@@ -9146,11 +9279,12 @@ class IdentityModule {
9146
9279
  window.history.replaceState(window.history.state, document.title, `${window.location.pathname}${window.location.search}`);
9147
9280
  }
9148
9281
  }
9149
- /** Drop the one-shot PKCE state/verifier a redirect bounce staged. */
9282
+ /** Drop the one-shot PKCE state/verifier (+ recovery hint) a bounce staged. */
9150
9283
  clearOneShotAuthState() {
9151
9284
  try {
9152
9285
  sessionStorage.removeItem('sv_oauth_state');
9153
9286
  sessionStorage.removeItem('sv_pkce_verifier');
9287
+ sessionStorage.removeItem(RECOVERY_HINT_KEY);
9154
9288
  }
9155
9289
  catch {
9156
9290
  // Storage disabled: nothing was persisted, nothing to clear.
@@ -9282,6 +9416,401 @@ class IdentityModule {
9282
9416
  }
9283
9417
  }
9284
9418
 
9419
+ /**
9420
+ * Notify Product Module — the TENANT (sender) surface.
9421
+ *
9422
+ * The counterpart to `sv.notify`: where that module is session-scoped and reads
9423
+ * only the signed-in person's OWN inbox, this one is the account-scoped product
9424
+ * surface a tenant's BACKEND drives — send, sender-side inbox reads and state,
9425
+ * send status, receipts, and the account's Notify config. Every method maps to
9426
+ * `/v1/products/notify/*` and is authorized by the caller's account, so the
9427
+ * recipient is supplied explicitly rather than derived from a session.
9428
+ *
9429
+ * Intended for server-side use with an `apiKey` (sent as `X-API-Key`); a Core JWT
9430
+ * works identically. Note the API prefers a Bearer JWT when both credentials are
9431
+ * configured, so a server integration should set `apiKey` alone.
9432
+ *
9433
+ * Notify never touches crypto here: `send` seals content and mints one single-use
9434
+ * SparkLink per recipient server-side, and the client only ever carries pointers
9435
+ * and metadata.
9436
+ */
9437
+ /** Root of every tenant-facing Notify route. */
9438
+ const BASE_PATH = '/v1/products/notify';
9439
+ /**
9440
+ * The caller-supplied idempotency key's accepted shape. Mirrors the server's
9441
+ * validation exactly so a malformed key fails locally instead of on the wire.
9442
+ */
9443
+ const SEND_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/;
9444
+ const MARK_STATES$1 = ['seen', 'read', 'archived'];
9445
+ /**
9446
+ * Bulk drains ride the sparse unseen/unread GSIs. `archived` has no index, so it
9447
+ * is per-row only.
9448
+ */
9449
+ const BULK_MARK_STATES$1 = ['seen', 'read'];
9450
+ /**
9451
+ * The five secure-by-default preset bundles, mirroring the server's table.
9452
+ *
9453
+ * There is no preset endpoint — presets are a merge over the one send contract,
9454
+ * so they are applied client-side and produce an ordinary `send` request. Caller
9455
+ * arguments always win over a preset's defaults; `channels` left unset lets the
9456
+ * account config resolve the ladder per category.
9457
+ *
9458
+ * `alert` is the only plaintext preset: a non-confidential ping is read at a
9459
+ * glance rather than behind a tap-to-view link. The other four seal.
9460
+ */
9461
+ const NOTIFY_PRESETS = Object.freeze({
9462
+ alert: {
9463
+ category: 'alert',
9464
+ delivery: 'plaintext',
9465
+ policy: { verificationLevel: 'none', interaction: 'view' },
9466
+ },
9467
+ secureMessage: {
9468
+ category: 'secure',
9469
+ channels: ['push', 'web_push', 'email'],
9470
+ policy: { verificationLevel: 'identifier', interaction: 'view' },
9471
+ },
9472
+ conversation: {
9473
+ category: 'conversation',
9474
+ channels: ['in_app', 'push', 'web_push', 'email'],
9475
+ policy: { verificationLevel: 'identifier', interaction: 'reply' },
9476
+ },
9477
+ approval: {
9478
+ category: 'approval',
9479
+ channels: ['in_app', 'push', 'web_push', 'email'],
9480
+ policy: { verificationLevel: 'passkey', interaction: 'approve' },
9481
+ },
9482
+ signatureRequest: {
9483
+ category: 'signature',
9484
+ channels: ['in_app', 'push', 'web_push', 'email'],
9485
+ policy: { verificationLevel: 'passkey', interaction: 'sign' },
9486
+ },
9487
+ });
9488
+ /**
9489
+ * Merge a preset's bundle UNDER the caller's arguments, yielding ordinary send
9490
+ * options. Exported so a caller can inspect (or further adjust) what a preset
9491
+ * would send before sending it.
9492
+ */
9493
+ function buildNotifyPresetSend(preset, options) {
9494
+ const bundle = NOTIFY_PRESETS[preset];
9495
+ if (!bundle) {
9496
+ throw new ValidationError(`Unknown notify preset "${preset}" (valid: ${Object.keys(NOTIFY_PRESETS).join(', ')})`, { field: 'preset', received: preset });
9497
+ }
9498
+ const merged = {
9499
+ ...options,
9500
+ category: options.category || bundle.category,
9501
+ // A caller-supplied delivery wins (a sealed override of an alert is allowed);
9502
+ // otherwise the preset's mode, or the sealed default when it declares none.
9503
+ delivery: options.delivery ?? bundle.delivery,
9504
+ policy: { ...bundle.policy, ...(options.policy ?? {}) },
9505
+ };
9506
+ // Only set channels when the preset declares them and the caller did not
9507
+ // override — leaving it unset lets the account config resolve them per category.
9508
+ const channels = options.channels || bundle.channels;
9509
+ if (channels)
9510
+ merged.channels = channels;
9511
+ return merged;
9512
+ }
9513
+ class NotifyProductModule {
9514
+ constructor(http) {
9515
+ this.http = http;
9516
+ }
9517
+ // ── Send ────────────────────────────────────────────────────────────────────
9518
+ /**
9519
+ * Send a notification: seal the content, mint one single-use SparkLink per
9520
+ * recipient, and enqueue delivery across the resolved channel ladder.
9521
+ *
9522
+ * `sendId` is the idempotency key. Replaying an existing one returns the stored
9523
+ * send unchanged — never re-sealed, never re-delivered — flagged `idempotent`.
9524
+ *
9525
+ * @example
9526
+ * const send = await sv.products.notify.send({
9527
+ * sendId: `invoice:${invoice.id}`,
9528
+ * recipients: [{ id: user.svid, email: user.email }],
9529
+ * content: { payload: 'Your invoice is ready.' },
9530
+ * policy: { verificationLevel: 'identifier', interaction: 'view' },
9531
+ * title: 'Invoice ready',
9532
+ * category: 'transactional',
9533
+ * });
9534
+ */
9535
+ async send(options) {
9536
+ if (options?.sendId !== undefined) {
9537
+ if (typeof options.sendId !== 'string' || !SEND_ID_PATTERN.test(options.sendId)) {
9538
+ throw new ValidationError('sendId must be 1-128 characters of letters, digits, and _ . : -', { field: 'sendId', received: options.sendId });
9539
+ }
9540
+ }
9541
+ if (!Array.isArray(options?.recipients) || options.recipients.length === 0) {
9542
+ throw new ValidationError('recipients is required and must be non-empty', {
9543
+ field: 'recipients',
9544
+ });
9545
+ }
9546
+ if (Boolean(options.content) === Boolean(options.ingot)) {
9547
+ throw new ValidationError('Provide exactly one content source: content OR ingot');
9548
+ }
9549
+ const response = await this.http.post(`${BASE_PATH}/send`, toSendBody(options));
9550
+ return response.data;
9551
+ }
9552
+ /**
9553
+ * Frictionless informational ping — no verification, view-only, delivered
9554
+ * INLINE (plaintext) so it is read at a glance. Channels resolve from the
9555
+ * account config; plaintext requires an inline-capable channel.
9556
+ *
9557
+ * @example
9558
+ * await sv.products.notify.sendAlert({
9559
+ * recipients: [{ id: user.svid }],
9560
+ * content: { payload: 'Your export finished.' },
9561
+ * title: 'Export complete',
9562
+ * });
9563
+ */
9564
+ async sendAlert(options) {
9565
+ return this.send(buildNotifyPresetSend('alert', options));
9566
+ }
9567
+ /** Confidential content revealed after the recipient proves their identifier. */
9568
+ async sendSecureMessage(options) {
9569
+ return this.send(buildNotifyPresetSend('secureMessage', options));
9570
+ }
9571
+ /** Two-way thread: identifier-verified reveal plus an encrypted reply. */
9572
+ async sendConversation(options) {
9573
+ return this.send(buildNotifyPresetSend('conversation', options));
9574
+ }
9575
+ /** High-stakes approve/deny — passkey-verified, with `action_hash` binding. */
9576
+ async sendApproval(options) {
9577
+ return this.send(buildNotifyPresetSend('approval', options));
9578
+ }
9579
+ /** Signature-on-delivery — passkey-verified, with `action_hash` binding. */
9580
+ async sendSignatureRequest(options) {
9581
+ return this.send(buildNotifyPresetSend('signatureRequest', options));
9582
+ }
9583
+ // ── Inbox (sender-side) ─────────────────────────────────────────────────────
9584
+ /**
9585
+ * Read one recipient's metadata-only feed, newest first. Rows are pointers: a
9586
+ * sealed row carries only `sparklink_code`, never the content.
9587
+ *
9588
+ * A page can come back SHORT of `limit` yet still carry a non-null cursor —
9589
+ * follow the cursor; never treat a short page as the end.
9590
+ *
9591
+ * @example
9592
+ * const { notifications, cursor } = await sv.products.notify.getInbox({
9593
+ * recipientId: user.svid,
9594
+ * state: 'unread',
9595
+ * });
9596
+ */
9597
+ async getInbox(options) {
9598
+ requireRecipientId(options?.recipientId);
9599
+ const query = buildQuery$3({
9600
+ recipient_id: options.recipientId,
9601
+ state: options.state,
9602
+ limit: options.limit,
9603
+ cursor: options.cursor,
9604
+ });
9605
+ const response = await this.http.get(`${BASE_PATH}/inbox${query}`);
9606
+ return response.data;
9607
+ }
9608
+ /**
9609
+ * Apply a terminal display state to one row (idempotent). `createdAt` MUST be
9610
+ * the row's own `created_at`, round-tripped from the feed or the webhook/push
9611
+ * payload — the id alone cannot address the row.
9612
+ *
9613
+ * @example
9614
+ * await sv.products.notify.markInboxState(row.notification_id, {
9615
+ * recipientId: user.svid,
9616
+ * createdAt: row.created_at,
9617
+ * state: 'read',
9618
+ * });
9619
+ */
9620
+ async markInboxState(notificationId, options) {
9621
+ if (!notificationId || typeof notificationId !== 'string') {
9622
+ throw new ValidationError('notificationId is required', { field: 'notificationId' });
9623
+ }
9624
+ requireRecipientId(options?.recipientId);
9625
+ if (!Number.isInteger(options?.createdAt)) {
9626
+ throw new ValidationError("createdAt (the row's created_at) is required", {
9627
+ field: 'createdAt',
9628
+ received: options?.createdAt,
9629
+ });
9630
+ }
9631
+ if (!MARK_STATES$1.includes(options.state)) {
9632
+ throw new ValidationError(`state must be one of ${MARK_STATES$1.join(', ')}`, {
9633
+ field: 'state',
9634
+ received: options.state,
9635
+ });
9636
+ }
9637
+ const response = await this.http.post(`${BASE_PATH}/inbox/${encodeURIComponent(notificationId)}/state`, { recipient_id: options.recipientId, created_at: options.createdAt, state: options.state });
9638
+ return response.data;
9639
+ }
9640
+ /**
9641
+ * Bulk-mark one bounded page of a recipient's inbox `seen` or `read`. Loop on
9642
+ * the returned cursor until it is null. `archived` is per-row only.
9643
+ *
9644
+ * @example
9645
+ * let cursor: string | undefined;
9646
+ * do {
9647
+ * const page = await sv.products.notify.markInboxAll({
9648
+ * recipientId: user.svid, state: 'read', cursor,
9649
+ * });
9650
+ * cursor = page.cursor ?? undefined;
9651
+ * } while (cursor);
9652
+ */
9653
+ async markInboxAll(options) {
9654
+ requireRecipientId(options?.recipientId);
9655
+ if (!BULK_MARK_STATES$1.includes(options.state)) {
9656
+ throw new ValidationError(`state must be one of ${BULK_MARK_STATES$1.join(', ')} (archive per-row instead)`, { field: 'state', received: options.state });
9657
+ }
9658
+ const response = await this.http.post(`${BASE_PATH}/inbox/state`, {
9659
+ recipient_id: options.recipientId,
9660
+ state: options.state,
9661
+ cursor: options.cursor,
9662
+ });
9663
+ return response.data;
9664
+ }
9665
+ // ── Status & receipts ───────────────────────────────────────────────────────
9666
+ /**
9667
+ * The sender's per-recipient delivery rollup for one send: who it reached and
9668
+ * how far each recipient got. Metadata only — never the pointer or contacts.
9669
+ *
9670
+ * @example
9671
+ * const { counts } = await sv.products.notify.getSendStatus(send.send_id);
9672
+ */
9673
+ async getSendStatus(sendId) {
9674
+ requireSendId(sendId);
9675
+ const response = await this.http.get(`${BASE_PATH}/sends/${encodeURIComponent(sendId)}/status`);
9676
+ return response.data;
9677
+ }
9678
+ /**
9679
+ * The account's verified-interaction receipts (portable, JWKS-verifiable
9680
+ * proofs), newest first. Follow `cursor` to page.
9681
+ *
9682
+ * A page can come back SHORT of `limit` — even EMPTY — yet still carry a
9683
+ * non-null cursor: the receipt-subtype and `interaction` filters are applied
9684
+ * after the key query, so a page of non-matching rows yields no receipts and a
9685
+ * live cursor. Follow the cursor; never treat a short or empty page as the end.
9686
+ *
9687
+ * @example
9688
+ * const { receipts, cursor } = await sv.products.notify.listReceipts({ interaction: 'approve' });
9689
+ */
9690
+ async listReceipts(options = {}) {
9691
+ const query = buildQuery$3({
9692
+ limit: options.limit,
9693
+ cursor: options.cursor,
9694
+ interaction: options.interaction,
9695
+ });
9696
+ const response = await this.http.get(`${BASE_PATH}/receipts${query}`);
9697
+ return response.data;
9698
+ }
9699
+ /**
9700
+ * Every receipt for one send, each attached to the recipient who produced it.
9701
+ * The correlation scan is bounded: when `truncated` is true, some older
9702
+ * receipts fall outside the scanned window — pass the returned `cursor` back in
9703
+ * to resume the scan exactly where it stopped.
9704
+ *
9705
+ * @example
9706
+ * const all: NotifySendReceipt[] = [];
9707
+ * let cursor: string | undefined;
9708
+ * do {
9709
+ * const page = await sv.products.notify.getSendReceipts(send.send_id, { cursor });
9710
+ * all.push(...page.receipts);
9711
+ * cursor = page.truncated ? page.cursor ?? undefined : undefined;
9712
+ * } while (cursor);
9713
+ */
9714
+ async getSendReceipts(sendId, options = {}) {
9715
+ requireSendId(sendId);
9716
+ const query = buildQuery$3({ cursor: options.cursor });
9717
+ const response = await this.http.get(`${BASE_PATH}/sends/${encodeURIComponent(sendId)}/receipts${query}`);
9718
+ return response.data;
9719
+ }
9720
+ // ── Config ──────────────────────────────────────────────────────────────────
9721
+ /**
9722
+ * The account's effective Notify config (secure defaults deep-merged with its
9723
+ * overrides) plus the raw override delta, so an editor can show what is
9724
+ * customized versus default.
9725
+ *
9726
+ * @example
9727
+ * const { effective, overrides } = await sv.products.notify.getConfig();
9728
+ */
9729
+ async getConfig() {
9730
+ const response = await this.http.get(`${BASE_PATH}/config`);
9731
+ return response.data;
9732
+ }
9733
+ /**
9734
+ * Merge a partial patch onto the account's config overrides. Owner-gated
9735
+ * (`channel_credentials`) and unknown keys are rejected before any write.
9736
+ *
9737
+ * Delete a category by storing an explicit `null` TOMBSTONE — that is what keeps
9738
+ * a seeded default from re-appearing on the next merge. The reserved `security`
9739
+ * category can neither be removed nor made optional.
9740
+ *
9741
+ * @example
9742
+ * await sv.products.notify.updateConfig({
9743
+ * categories: {
9744
+ * weekly_newsletter: { label: 'Weekly newsletter', required: false },
9745
+ * marketing: null, // tombstone — remove the seeded default
9746
+ * },
9747
+ * });
9748
+ */
9749
+ async updateConfig(patch) {
9750
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
9751
+ throw new ValidationError('config patch must be an object');
9752
+ }
9753
+ const response = await this.http.put(`${BASE_PATH}/config`, patch);
9754
+ return response.data;
9755
+ }
9756
+ }
9757
+ /**
9758
+ * Map the camelCase option bag onto the send body. Undefined fields drop out at
9759
+ * JSON serialization, so an omitted option is absent on the wire rather than null.
9760
+ */
9761
+ function toSendBody(options) {
9762
+ return {
9763
+ send_id: options.sendId,
9764
+ recipients: options.recipients,
9765
+ content: options.content
9766
+ ? {
9767
+ payload: options.content.payload,
9768
+ content_type: options.content.contentType,
9769
+ filename: options.content.filename,
9770
+ ttl_minutes: options.content.ttlMinutes,
9771
+ }
9772
+ : undefined,
9773
+ ingot: options.ingot
9774
+ ? { ingot_id: options.ingot.ingotId, vault_id: options.ingot.vaultId }
9775
+ : undefined,
9776
+ delivery: options.delivery,
9777
+ policy: options.policy
9778
+ ? {
9779
+ verification_level: options.policy.verificationLevel,
9780
+ interaction: options.policy.interaction,
9781
+ reveal_freshness_minutes: options.policy.revealFreshnessMinutes,
9782
+ }
9783
+ : undefined,
9784
+ channels: options.channels,
9785
+ escalation: options.escalation,
9786
+ title: options.title,
9787
+ category: options.category,
9788
+ type: options.type,
9789
+ instructions: options.instructions,
9790
+ history_ttl_days: options.historyTtlDays,
9791
+ };
9792
+ }
9793
+ function requireRecipientId(recipientId) {
9794
+ if (!recipientId || typeof recipientId !== 'string') {
9795
+ throw new ValidationError('recipientId is required', { field: 'recipientId' });
9796
+ }
9797
+ }
9798
+ function requireSendId(sendId) {
9799
+ if (!sendId || typeof sendId !== 'string') {
9800
+ throw new ValidationError('sendId is required', { field: 'sendId' });
9801
+ }
9802
+ }
9803
+ function buildQuery$3(params) {
9804
+ const search = new URLSearchParams();
9805
+ for (const [key, value] of Object.entries(params)) {
9806
+ if (value === undefined || value === '')
9807
+ continue;
9808
+ search.append(key, String(value));
9809
+ }
9810
+ const query = search.toString();
9811
+ return query ? `?${query}` : '';
9812
+ }
9813
+
9285
9814
  /**
9286
9815
  * Products Module
9287
9816
  *
@@ -9290,8 +9819,13 @@ class IdentityModule {
9290
9819
  * Currently exposes `identity`; future products attach here alongside it.
9291
9820
  */
9292
9821
  class ProductsModule {
9293
- constructor(config) {
9822
+ /**
9823
+ * `http` defaults to a client over the same resolved config so constructing
9824
+ * this module standalone stays a one-argument call.
9825
+ */
9826
+ constructor(config, http = new HttpClient(config)) {
9294
9827
  this.identity = new IdentityModule(config);
9828
+ this.notify = new NotifyProductModule(http);
9295
9829
  }
9296
9830
  }
9297
9831
 
@@ -13692,6 +14226,13 @@ class EntropyModule {
13692
14226
  * device push registration is intentionally omitted (Expo-only on mobile).
13693
14227
  */
13694
14228
  const MARK_STATES = ['seen', 'read', 'archived'];
14229
+ const BULK_MARK_STATES = ['seen', 'read'];
14230
+ /**
14231
+ * Hard bound on `markAllRead()`'s drain loop: 100 server pages of 100 rows. A
14232
+ * cursor that never resolves to null can therefore never spin forever, and an
14233
+ * inbox deeper than the bound finishes on a second call (the drain is idempotent).
14234
+ */
14235
+ const MARK_ALL_MAX_PAGES = 100;
13695
14236
  /**
13696
14237
  * Decode a base64url VAPID key into the Uint8Array `pushManager.subscribe`
13697
14238
  * requires for `applicationServerKey`. Standalone (no atob dependency on a
@@ -13781,6 +14322,65 @@ class NotifyModule {
13781
14322
  const response = await this.http.post(`/v1/me/notifications/${encodeURIComponent(notificationId)}/state`, { created_at: options.createdAt, state: options.state });
13782
14323
  return response.data;
13783
14324
  }
14325
+ /**
14326
+ * Bulk-mark ONE bounded page of the caller's inbox and return the server's
14327
+ * payload verbatim. `cursor` comes back non-null while rows remain — thread it
14328
+ * into the next call. `archived` is per-row only (no GSI to page over), so the
14329
+ * bulk states are `seen` and `read`.
14330
+ *
14331
+ * Prefer `markAllRead()` unless the caller needs to own the paging.
14332
+ *
14333
+ * @example
14334
+ * let page = await sv.notify.markAllState({ state: 'seen' });
14335
+ * while (page.cursor) page = await sv.notify.markAllState({ state: 'seen', cursor: page.cursor });
14336
+ */
14337
+ async markAllState(options) {
14338
+ if (!BULK_MARK_STATES.includes(options?.state)) {
14339
+ throw new ValidationError(`state must be one of ${BULK_MARK_STATES.join(', ')}`, {
14340
+ field: 'state',
14341
+ received: options?.state,
14342
+ });
14343
+ }
14344
+ if (options.cursor !== undefined && typeof options.cursor !== 'string') {
14345
+ throw new ValidationError('cursor must be the string cursor from a prior response', {
14346
+ field: 'cursor',
14347
+ received: options.cursor,
14348
+ });
14349
+ }
14350
+ const body = { state: options.state };
14351
+ if (options.cursor)
14352
+ body.cursor = options.cursor;
14353
+ const response = await this.http.post('/v1/me/notifications/state', body);
14354
+ return response.data;
14355
+ }
14356
+ /**
14357
+ * Drain the caller's whole inbox to read: loop `markAllState` on the returned
14358
+ * cursor until it comes back null, and return the total marked. Marking read
14359
+ * clears the unseen marker too, so the badge zeroes with it. Idempotent.
14360
+ *
14361
+ * `complete` is false when the loop stopped at the page bound with rows still
14362
+ * unmarked — an inbox deeper than the bound finishes on a second call. Without
14363
+ * it a truncated drain looks exactly like a finished one.
14364
+ *
14365
+ * An error mid-drain propagates — the pages already marked stay marked, and a
14366
+ * re-run picks up the remainder.
14367
+ *
14368
+ * @example
14369
+ * let { updated, complete } = await sv.notify.markAllRead();
14370
+ * while (!complete) ({ complete } = await sv.notify.markAllRead());
14371
+ */
14372
+ async markAllRead() {
14373
+ let cursor;
14374
+ let updated = 0;
14375
+ for (let page = 0; page < MARK_ALL_MAX_PAGES; page += 1) {
14376
+ const result = await this.markAllState(cursor ? { state: 'read', cursor } : { state: 'read' });
14377
+ updated += result?.updated ?? 0;
14378
+ if (!result?.cursor)
14379
+ return { updated, complete: true };
14380
+ cursor = result.cursor;
14381
+ }
14382
+ return { updated, complete: false };
14383
+ }
13784
14384
  // ── Browser Web Push ──────────────────────────────────────────────────────
13785
14385
  /**
13786
14386
  * Whether this environment can do Web Push (service worker + Push API +
@@ -14063,7 +14663,7 @@ class SparkVault {
14063
14663
  validateConfig(config);
14064
14664
  this.config = resolveConfig(config);
14065
14665
  const http = new HttpClient(this.config);
14066
- this.products = new ProductsModule(this.config);
14666
+ this.products = new ProductsModule(this.config, http);
14067
14667
  this.vaults = new VaultsModule(this.config, http);
14068
14668
  this.ingots = new IngotsModule(this.config, http);
14069
14669
  this.folders = new FoldersModule(http);
@@ -14109,5 +14709,5 @@ if (typeof window !== 'undefined') {
14109
14709
  window.SparkVault = instance ?? SparkVault;
14110
14710
  }
14111
14711
 
14112
- export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IngotsModule, NetworkError, NotifyModule, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, SparkVault as default, logger, setDebugMode };
14712
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IngotsModule, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, logger, setDebugMode };
14113
14713
  //# sourceMappingURL=sparkvault.esm.js.map