@joryio/web-sdk 1.3.3-beta.2 → 1.4.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/joryio.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Joryio Web SDK v1.3.3-beta.2
2
+ * Joryio Web SDK v1.4.0-beta.1
3
3
  * (c) 2026 Joryio. All rights reserved.
4
4
  * @license Commercial - see https://github.com/joryio/joryio-web-sdk/blob/main/LICENSE
5
5
  */
6
- const SDK_VERSION = '1.3.3';
6
+ const SDK_VERSION = '1.4.0';
7
7
  const DEFAULT_API_ENDPOINT = 'https://api-eu1.joryio.com/api';
8
8
  function normalizeApiEndpoint(raw) {
9
9
  const trimmed = (raw || '').trim();
@@ -88,6 +88,7 @@ function resolveConfig(config) {
88
88
  trackPageProperties: config.trackPageProperties !== false,
89
89
  trackDeviceProperties: config.trackDeviceProperties !== false,
90
90
  inApp: inAppOptions,
91
+ webPush: config.webPush === true ? true : config.webPush === false ? false : undefined,
91
92
  persistQueue: config.persistQueue !== false,
92
93
  maxRetries: typeof config.maxRetries === 'number' && config.maxRetries >= 0 ? Math.floor(config.maxRetries) : DEFAULT_MAX_RETRIES,
93
94
  retryBackoffMs: config.retryBackoffMs || DEFAULT_RETRY_BACKOFF_MS,
@@ -99,6 +100,8 @@ function resolveConfig(config) {
99
100
  : undefined,
100
101
  enableSdkAuthentication: config.enableSdkAuthentication === true,
101
102
  sdkAuthenticationToken: config.sdkAuthenticationToken,
103
+ storefrontIdentityToken: typeof config.storefrontIdentityToken === 'string' && config.storefrontIdentityToken ? config.storefrontIdentityToken : undefined,
104
+ storefrontIdentityTokenProvider: typeof config.storefrontIdentityTokenProvider === 'function' ? config.storefrontIdentityTokenProvider : undefined,
102
105
  enableDebug: config.enableDebug || false,
103
106
  logLevel: config.logLevel || (config.enableDebug ? 'debug' : 'error'),
104
107
  loggingEnabled: config.enableDebug === true || !!config.logLevel,
@@ -726,11 +729,11 @@ class IdentityManager {
726
729
  this.logger.info(`User identified: ${userId} (was: ${previousUserId || 'anonymous'})`);
727
730
  }
728
731
  }
729
- reset() {
732
+ reset(anonymousId) {
730
733
  this.logger.debug(`Resetting identity (was: ${this.userId || 'anonymous'})`);
731
734
  this.userId = null;
732
735
  this.attributes = {};
733
- this.anonymousId = generateUUID();
736
+ this.anonymousId = anonymousId || generateUUID();
734
737
  this.storage.remove(USER_ID_KEY);
735
738
  this.storage.remove(USER_ATTRIBUTES_KEY);
736
739
  this.storage.set(ANONYMOUS_ID_KEY, this.anonymousId);
@@ -951,6 +954,36 @@ function identifiedUserOf(body) {
951
954
  }
952
955
  return null;
953
956
  }
957
+ const STOREFRONT_IDENTITY_ISSUER = 'joryio-storefront';
958
+ const STOREFRONT_IDENTITY_ERROR = 'storefront_identity_error';
959
+ const STOREFRONT_TOKEN_MIN_LIFE_MS = 30000;
960
+ function storefrontTokenClaims(token) {
961
+ const c = jwtClaims(token);
962
+ if (!c || c.iss !== STOREFRONT_IDENTITY_ISSUER)
963
+ return null;
964
+ if (typeof c.vid !== 'string' || !c.vid || typeof c.exp !== 'number')
965
+ return null;
966
+ return { vid: c.vid, exp: c.exp };
967
+ }
968
+ function anonymousIdOfBody(body) {
969
+ if (!body || typeof body !== 'object')
970
+ return null;
971
+ if (identifiedUserOf(body))
972
+ return null;
973
+ const ids = new Set();
974
+ const add = (v) => {
975
+ if (typeof v === 'string' && v)
976
+ ids.add(v);
977
+ };
978
+ add(body.anonymousId);
979
+ if (body.identify)
980
+ add(body.identify.anonymousId);
981
+ for (const list of [body.events, body.impressions]) {
982
+ if (Array.isArray(list))
983
+ list.forEach((e) => e && add(e.anonymousId));
984
+ }
985
+ return ids.size === 1 ? ids.values().next().value : null;
986
+ }
954
987
  const DEFAULT_CIRCUIT_BREAKER_CONFIG = {
955
988
  failureThreshold: 5,
956
989
  cooldownMs: 30000,
@@ -967,12 +1000,96 @@ class NetworkClient {
967
1000
  this.sdkAuthTokenUser = null;
968
1001
  this.keepaliveBytesInFlight = 0;
969
1002
  this.currentUserId = null;
1003
+ this.storefrontTokenProvider = null;
1004
+ this.storefrontRefresh = null;
1005
+ this.anonymousIdSource = null;
970
1006
  this.suspended = false;
971
1007
  this.sdkKey = sdkKey;
972
1008
  this.logger = logger;
973
1009
  this.retryConfig = retryConfig;
974
1010
  this.circuitBreakerConfig = Object.assign(Object.assign({}, DEFAULT_CIRCUIT_BREAKER_CONFIG), circuitBreakerConfig);
975
1011
  }
1012
+ setAnonymousIdSource(source) {
1013
+ this.anonymousIdSource = source;
1014
+ }
1015
+ setStorefrontIdentityToken(token) {
1016
+ const next = typeof token === 'string' && token ? token : undefined;
1017
+ if (next && !storefrontTokenClaims(next)) {
1018
+ this.logger.warn('setStorefrontIdentityToken: not a storefront identity token - ignored');
1019
+ return;
1020
+ }
1021
+ this.storefrontToken = next;
1022
+ }
1023
+ setStorefrontIdentityTokenProvider(provider) {
1024
+ this.storefrontTokenProvider = provider;
1025
+ }
1026
+ clearStorefrontIdentityToken() {
1027
+ this.storefrontToken = undefined;
1028
+ this.storefrontRefresh = null;
1029
+ }
1030
+ isStorefrontIdentityError(status, data) {
1031
+ return status === 401 && !!data && typeof data === 'object' && data.error === STOREFRONT_IDENTITY_ERROR;
1032
+ }
1033
+ storefrontTokenFor(subjectUserId, bodyAnonymousId) {
1034
+ const token = this.storefrontToken;
1035
+ if (!token)
1036
+ return undefined;
1037
+ const user = subjectUserId === undefined ? this.currentUserId : subjectUserId;
1038
+ if (user)
1039
+ return undefined;
1040
+ const claims = storefrontTokenClaims(token);
1041
+ const current = this.anonymousIdSource ? this.anonymousIdSource() : null;
1042
+ if (!claims || !current || claims.vid !== current)
1043
+ return undefined;
1044
+ if (bodyAnonymousId === null)
1045
+ return undefined;
1046
+ if (bodyAnonymousId !== undefined && bodyAnonymousId !== claims.vid)
1047
+ return undefined;
1048
+ if (claims.exp * 1000 - Date.now() < STOREFRONT_TOKEN_MIN_LIFE_MS) {
1049
+ void this.refreshStorefrontToken();
1050
+ return undefined;
1051
+ }
1052
+ return token;
1053
+ }
1054
+ refreshStorefrontToken() {
1055
+ if (!this.storefrontTokenProvider)
1056
+ return Promise.resolve(undefined);
1057
+ if (this.storefrontRefresh)
1058
+ return this.storefrontRefresh;
1059
+ const previous = this.storefrontToken;
1060
+ const provider = this.storefrontTokenProvider;
1061
+ this.storefrontRefresh = (async () => {
1062
+ try {
1063
+ const fresh = await Promise.resolve(provider());
1064
+ if (typeof fresh === 'string' && fresh && storefrontTokenClaims(fresh)) {
1065
+ this.storefrontToken = fresh;
1066
+ return fresh !== previous ? fresh : undefined;
1067
+ }
1068
+ }
1069
+ catch (err) {
1070
+ this.logger.warn('The storefront identity token provider failed:', err);
1071
+ }
1072
+ return undefined;
1073
+ })().finally(() => {
1074
+ this.storefrontRefresh = null;
1075
+ });
1076
+ return this.storefrontRefresh;
1077
+ }
1078
+ async handleStorefrontIdentityError(data) {
1079
+ const reason = data && typeof data === 'object' ? data.reason : undefined;
1080
+ this.logger.warn(`Storefront identity token refused (${reason || 'invalid'})`);
1081
+ if (reason === 'expired') {
1082
+ const before = this.storefrontToken;
1083
+ const fresh = await this.refreshStorefrontToken();
1084
+ if (fresh)
1085
+ return true;
1086
+ if (this.storefrontToken === before)
1087
+ this.storefrontToken = undefined;
1088
+ return true;
1089
+ }
1090
+ this.storefrontToken = undefined;
1091
+ return true;
1092
+ }
976
1093
  setSdkAuthenticationEnabled(enabled) {
977
1094
  this.sdkAuthEnabled = enabled;
978
1095
  }
@@ -1183,8 +1300,9 @@ class NetworkClient {
1183
1300
  }
1184
1301
  return true;
1185
1302
  }
1186
- getSdkAuthHeaders(subjectUserId) {
1187
- const token = this.sdkAuthTokenFor(subjectUserId);
1303
+ getSdkAuthHeaders(subjectUserId, anonymousId) {
1304
+ var _a;
1305
+ const token = (_a = this.sdkAuthTokenFor(subjectUserId)) !== null && _a !== void 0 ? _a : this.storefrontTokenFor(subjectUserId, anonymousId);
1188
1306
  return token ? { [SDK_AUTH_HEADER]: token } : {};
1189
1307
  }
1190
1308
  keepaliveBudget() {
@@ -1246,16 +1364,24 @@ class NetworkClient {
1246
1364
  return { ok: false, status: 400, error: 'The request body cannot be serialized' };
1247
1365
  }
1248
1366
  const forCurrentUser = request.subjectUserId === undefined || (request.subjectUserId || null) === this.currentUserId;
1367
+ const bodyAnonymousId = request.body ? anonymousIdOfBody(request.body) : undefined;
1249
1368
  let lastError = null;
1250
1369
  let lastStatus = 0;
1251
1370
  let lastData;
1252
1371
  let retryAfterMs;
1253
1372
  let attempt = 0;
1254
1373
  let sdkAuthRefreshAttempted = false;
1374
+ let storefrontRetryAttempted = false;
1255
1375
  while (attempt <= this.retryConfig.maxRetries) {
1256
1376
  try {
1257
1377
  this.logger.debug(`Request attempt ${attempt + 1}/${this.retryConfig.maxRetries + 1}: ${method} ${url}`);
1258
- let { response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId);
1378
+ let { response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId);
1379
+ if (!storefrontRetryAttempted && this.isStorefrontIdentityError(response.status, responseData)) {
1380
+ storefrontRetryAttempted = true;
1381
+ if (await this.handleStorefrontIdentityError(responseData)) {
1382
+ ({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId));
1383
+ }
1384
+ }
1259
1385
  if (!sdkAuthRefreshAttempted &&
1260
1386
  this.sdkAuthEnabled &&
1261
1387
  forCurrentUser &&
@@ -1269,7 +1395,7 @@ class NetworkClient {
1269
1395
  });
1270
1396
  if (fresh) {
1271
1397
  this.logger.debug('SDK authentication token refreshed – retrying request once');
1272
- ({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId));
1398
+ ({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId));
1273
1399
  }
1274
1400
  }
1275
1401
  if (response.ok) {
@@ -1354,11 +1480,12 @@ class NetworkClient {
1354
1480
  openedAt: this.circuitOpenedAt,
1355
1481
  };
1356
1482
  }
1357
- async performFetch(url, method, callerHeaders, body, subjectUserId) {
1483
+ async performFetch(url, method, callerHeaders, body, subjectUserId, bodyAnonymousId) {
1484
+ var _a;
1358
1485
  const controller = new AbortController();
1359
1486
  const timeoutId = setTimeout(() => controller.abort(), this.retryConfig.timeoutMs || 10000);
1360
1487
  const headers = Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, callerHeaders);
1361
- const authToken = this.sdkAuthTokenFor(subjectUserId);
1488
+ const authToken = (_a = this.sdkAuthTokenFor(subjectUserId)) !== null && _a !== void 0 ? _a : this.storefrontTokenFor(subjectUserId, bodyAnonymousId);
1362
1489
  if (authToken) {
1363
1490
  headers[SDK_AUTH_HEADER] = authToken;
1364
1491
  }
@@ -1436,13 +1563,14 @@ class NetworkClient {
1436
1563
  return this.postKeepalive(`${apiEndpoint}/v1/track/batch`, body);
1437
1564
  }
1438
1565
  postKeepalive(url, body) {
1566
+ var _a;
1439
1567
  if ((this.suspended && !isWithdrawalRequest(url, body)) || !this.supportsKeepalive())
1440
1568
  return null;
1441
1569
  let json;
1442
1570
  try {
1443
1571
  json = JSON.stringify(body);
1444
1572
  }
1445
- catch (_a) {
1573
+ catch (_b) {
1446
1574
  return null;
1447
1575
  }
1448
1576
  const bytes = utf8Length(json) + 256;
@@ -1452,7 +1580,8 @@ class NetworkClient {
1452
1580
  'Content-Type': 'application/json',
1453
1581
  'X-SDK-Key': this.sdkKey,
1454
1582
  };
1455
- const authToken = this.sdkAuthTokenFor(identifiedUserOf(body));
1583
+ const subject = identifiedUserOf(body);
1584
+ const authToken = (_a = this.sdkAuthTokenFor(subject)) !== null && _a !== void 0 ? _a : this.storefrontTokenFor(subject, anonymousIdOfBody(body));
1456
1585
  if (authToken) {
1457
1586
  headers[SDK_AUTH_HEADER] = authToken;
1458
1587
  }
@@ -1499,6 +1628,22 @@ class NetworkClient {
1499
1628
  subjectUserId: userId,
1500
1629
  });
1501
1630
  }
1631
+ async sendIdentifyLink(apiEndpoint, payload) {
1632
+ return this.request({
1633
+ url: `${apiEndpoint}/v1/identify-link`,
1634
+ method: 'POST',
1635
+ body: { token: payload.token, anonymousId: payload.anonymousId },
1636
+ subjectUserId: null,
1637
+ });
1638
+ }
1639
+ hasStorefrontIdentity() {
1640
+ const token = this.storefrontToken;
1641
+ if (!token)
1642
+ return false;
1643
+ const claims = storefrontTokenClaims(token);
1644
+ const current = this.anonymousIdSource ? this.anonymousIdSource() : null;
1645
+ return !!claims && !!current && claims.vid === current;
1646
+ }
1502
1647
  async sendAddAlias(apiEndpoint, payload) {
1503
1648
  return this.request({
1504
1649
  url: `${apiEndpoint}/v1/alias/add`,
@@ -2749,6 +2894,7 @@ class InAppMessagingManager {
2749
2894
  return Object.assign(Object.assign({}, (userId ? { userId } : {})), { anonymousId: this.identity.getAnonymousId() });
2750
2895
  }
2751
2896
  async maybeHandleSdkAuthError(response, endpoint, subjectUserId) {
2897
+ var _a, _b, _c, _d;
2752
2898
  if (!this.auth || response.status !== 401) {
2753
2899
  return;
2754
2900
  }
@@ -2759,7 +2905,11 @@ class InAppMessagingManager {
2759
2905
  try {
2760
2906
  data = await response.clone().json();
2761
2907
  }
2762
- catch (_a) {
2908
+ catch (_e) {
2909
+ return;
2910
+ }
2911
+ if ((_b = (_a = this.auth).isStorefrontIdentityError) === null || _b === void 0 ? void 0 : _b.call(_a, response.status, data)) {
2912
+ await ((_d = (_c = this.auth).handleStorefrontIdentityError) === null || _d === void 0 ? void 0 : _d.call(_c, data).catch(() => false));
2763
2913
  return;
2764
2914
  }
2765
2915
  if (!this.auth.isSdkAuthError(response.status, data)) {
@@ -2800,7 +2950,7 @@ class InAppMessagingManager {
2800
2950
  try {
2801
2951
  const response = await fetch(`${this.apiEndpoint}/v1/in-app/sync`, {
2802
2952
  method: 'POST',
2803
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(subjectUser)) || {})),
2953
+ headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(subjectUser, subjectUser ? null : this.identity.getAnonymousId())) || {})),
2804
2954
  body: JSON.stringify(Object.assign(Object.assign({}, this.subject()), { sessionId, userAttributes: attributeChanges || userAttributes, pendingAttributes: this.identity.pending.pending(this.identity.getAnonymousId()), deviceType: 'web', locale: navigator.language, capabilities: this.capabilities() })),
2805
2955
  signal: controller.signal,
2806
2956
  });
@@ -2912,7 +3062,7 @@ class InAppMessagingManager {
2912
3062
  try {
2913
3063
  const res = await fetch(`${this.apiEndpoint}/v1/in-app/resolve`, {
2914
3064
  method: 'POST',
2915
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(this.identity.getUserId())) || {})),
3065
+ headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(this.identity.getUserId(), this.identity.getUserId() ? null : this.identity.getAnonymousId())) || {})),
2916
3066
  body: JSON.stringify(Object.assign(Object.assign({}, this.subject()), { campaignId: campaign.id, sessionId: this.session.getSessionId(), userAttributes: this.identity.getAttributes(), pendingAttributes: this.identity.pending.pending(this.identity.getAnonymousId()), deviceType: 'web' })),
2917
3067
  signal: controller.signal,
2918
3068
  });
@@ -3656,7 +3806,7 @@ class InAppMessagingManager {
3656
3806
  this.callHost('onConversion', () => { var _a, _b; return (_b = (_a = this.displayOptions).onConversion) === null || _b === void 0 ? void 0 : _b.call(_a, message, event); });
3657
3807
  }
3658
3808
  async submitForm(campaignId, values) {
3659
- var _a, _b;
3809
+ var _a, _b, _c;
3660
3810
  const message = this.displayedMessages.get(campaignId);
3661
3811
  if (!this.runtime.canSend())
3662
3812
  return { ok: false, message: 'This form cannot be sent right now.' };
@@ -3664,25 +3814,29 @@ class InAppMessagingManager {
3664
3814
  const timeoutId = setTimeout(() => controller.abort(), this.runtime.requestTimeoutMs);
3665
3815
  const subjectUser = this.identity.getUserId();
3666
3816
  try {
3667
- const response = await fetch(`${this.apiEndpoint}/v1/in-app/form-submit`, {
3668
- method: 'POST',
3669
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(subjectUser)) || {})),
3670
- body: JSON.stringify({
3671
- campaignId,
3672
- variantId: (_b = message === null || message === void 0 ? void 0 : message.campaign) === null || _b === void 0 ? void 0 : _b.variantId,
3673
- userId: this.identity.getUserId() || undefined,
3674
- anonymousId: this.identity.getAnonymousId(),
3675
- values,
3676
- }),
3677
- signal: controller.signal,
3678
- });
3817
+ const send = () => {
3818
+ var _a, _b, _c;
3819
+ return fetch(`${this.apiEndpoint}/v1/in-app/form-submit`, {
3820
+ method: 'POST',
3821
+ headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(subjectUser, subjectUser ? null : this.identity.getAnonymousId())) || {})),
3822
+ body: JSON.stringify(Object.assign(Object.assign({ campaignId, variantId: (_b = message === null || message === void 0 ? void 0 : message.campaign) === null || _b === void 0 ? void 0 : _b.variantId, userId: this.identity.getUserId() || undefined, anonymousId: this.identity.getAnonymousId() }, (((_c = message === null || message === void 0 ? void 0 : message.campaign) === null || _c === void 0 ? void 0 : _c.formToken) ? { formToken: message.campaign.formToken } : {})), { values })),
3823
+ signal: controller.signal,
3824
+ });
3825
+ };
3826
+ let response = await send();
3827
+ if (response.status === 401 && ((_a = this.auth) === null || _a === void 0 ? void 0 : _a.isStorefrontIdentityError)) {
3828
+ const data = await response.clone().json().catch(() => null);
3829
+ if (this.auth.isStorefrontIdentityError(401, data) && (await ((_c = (_b = this.auth).handleStorefrontIdentityError) === null || _c === void 0 ? void 0 : _c.call(_b, data).catch(() => false)))) {
3830
+ response = await send();
3831
+ }
3832
+ }
3679
3833
  await this.maybeHandleSdkAuthError(response, `${this.apiEndpoint}/v1/in-app/form-submit`, subjectUser);
3680
3834
  const json = await response.json().catch(() => null);
3681
3835
  if (!json || typeof json !== 'object')
3682
3836
  return { ok: false, message: 'Something went wrong. Please try again.' };
3683
3837
  return json;
3684
3838
  }
3685
- catch (_c) {
3839
+ catch (_d) {
3686
3840
  return { ok: false, message: 'Something went wrong. Please try again.' };
3687
3841
  }
3688
3842
  finally {
@@ -3690,7 +3844,7 @@ class InAppMessagingManager {
3690
3844
  }
3691
3845
  }
3692
3846
  async trackImpression(campaignId, type, extra) {
3693
- var _a, _b, _c, _d;
3847
+ var _a, _b, _c, _d, _e;
3694
3848
  const campaign = this.campaigns.get(campaignId) || ((_a = this.displayedMessages.get(campaignId)) === null || _a === void 0 ? void 0 : _a.campaign);
3695
3849
  if (!campaign)
3696
3850
  return;
@@ -3726,12 +3880,12 @@ class InAppMessagingManager {
3726
3880
  try {
3727
3881
  const response = await fetch(`${this.apiEndpoint}/v1/in-app/track`, {
3728
3882
  method: 'POST',
3729
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_b = this.auth) === null || _b === void 0 ? void 0 : _b.getSdkAuthHeaders(subjectUser)) || {})),
3883
+ headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_b = this.auth) === null || _b === void 0 ? void 0 : _b.getSdkAuthHeaders(subjectUser, subjectUser ? null : (_c = data.anonymousId) !== null && _c !== void 0 ? _c : null)) || {})),
3730
3884
  body: JSON.stringify(data),
3731
3885
  signal: controller.signal,
3732
3886
  });
3733
3887
  if (!response.ok)
3734
- (_d = (_c = this.runtime).noteStatus) === null || _d === void 0 ? void 0 : _d.call(_c, response.status, null);
3888
+ (_e = (_d = this.runtime).noteStatus) === null || _e === void 0 ? void 0 : _e.call(_d, response.status, null);
3735
3889
  await this.maybeHandleSdkAuthError(response, `${this.apiEndpoint}/v1/in-app/track`, subjectUser);
3736
3890
  this.logger.debug(`Tracked ${type} for campaign ${campaignId}`);
3737
3891
  }
@@ -4452,6 +4606,7 @@ function writeAttemptsExhausted(attempts, notFoundAttempts) {
4452
4606
 
4453
4607
  const REGISTRATION_MARKER_KEY = 'push_registration';
4454
4608
  const UNREGISTERED_KEY = 'push_unregistered';
4609
+ const IN_USE_KEY = 'push_in_use';
4455
4610
  const PENDING_UNREGISTER_KEY = 'push_pending_unregister';
4456
4611
  const REREGISTER_EVERY_MS = 24 * 60 * 60 * 1000;
4457
4612
  const SW_STATE_CACHE = 'joryio-sdk-state';
@@ -4467,12 +4622,38 @@ class PushManager {
4467
4622
  this.lastPrepareError = null;
4468
4623
  this.unregisterInFlight = false;
4469
4624
  this.unregisterTimer = null;
4625
+ this.usedThisPage = false;
4470
4626
  this.canSend = options.canSend || (() => true);
4471
4627
  this.canWithdraw = options.canWithdraw || (() => true);
4472
4628
  this.withdrawalUserId = options.withdrawalUserId || (() => this.identity.getUserId());
4473
4629
  this.storage = options.storage || null;
4474
4630
  this.getDeviceId = options.getDeviceId || (() => undefined);
4475
4631
  this.onSubscribeSettled = options.onSubscribeSettled || null;
4632
+ this.onPrepared = options.onPrepared || null;
4633
+ }
4634
+ usedOnThisPage() {
4635
+ return this.usedThisPage;
4636
+ }
4637
+ usedEarlier() {
4638
+ if (!this.storage)
4639
+ return false;
4640
+ try {
4641
+ return (this.storage.get(IN_USE_KEY) === true ||
4642
+ this.storage.get(REGISTRATION_MARKER_KEY) != null ||
4643
+ this.storage.get(UNREGISTERED_KEY) === true);
4644
+ }
4645
+ catch (_a) {
4646
+ return false;
4647
+ }
4648
+ }
4649
+ markUsed() {
4650
+ var _a;
4651
+ this.usedThisPage = true;
4652
+ try {
4653
+ (_a = this.storage) === null || _a === void 0 ? void 0 : _a.set(IN_USE_KEY, true);
4654
+ }
4655
+ catch (_b) {
4656
+ }
4476
4657
  }
4477
4658
  isSupported() {
4478
4659
  return (typeof window !== 'undefined' &&
@@ -4564,6 +4745,7 @@ class PushManager {
4564
4745
  }
4565
4746
  }
4566
4747
  async prepare(options) {
4748
+ var _a;
4567
4749
  options = options || {};
4568
4750
  if (!this.isSupported()) {
4569
4751
  this.lastPrepareError = 'unsupported';
@@ -4584,6 +4766,13 @@ class PushManager {
4584
4766
  await navigator.serviceWorker.ready;
4585
4767
  this.prepared = { registration, publicKey };
4586
4768
  this.lastPrepareError = null;
4769
+ this.markUsed();
4770
+ try {
4771
+ (_a = this.onPrepared) === null || _a === void 0 ? void 0 : _a.call(this);
4772
+ }
4773
+ catch (error) {
4774
+ this.logger.warn('Push permission report failed:', error);
4775
+ }
4587
4776
  return true;
4588
4777
  }
4589
4778
  catch (err) {
@@ -4598,6 +4787,7 @@ class PushManager {
4598
4787
  return await this.subscribeOnce(options);
4599
4788
  }
4600
4789
  finally {
4790
+ this.markUsed();
4601
4791
  try {
4602
4792
  (_a = this.onSubscribeSettled) === null || _a === void 0 ? void 0 : _a.call(this);
4603
4793
  }
@@ -5459,6 +5649,72 @@ function withoutUnsendableValues(values, warn) {
5459
5649
  return out;
5460
5650
  }
5461
5651
 
5652
+ const RESET_TO_ANONYMOUS_ID_PATTERN = /^[A-Za-z0-9._:-]{8,255}$/;
5653
+ const RESET_TO_INTERNAL_ID_PATTERN = /^[0-9a-f]{24}$/;
5654
+ const SIGNED_IN_ANONYMOUS_IDS_KEY = 'signed_in_anonymous_ids';
5655
+ function rememberSignedInAnonymousId(list, id) {
5656
+ return [...list.filter((x) => x !== id), id].slice(-20);
5657
+ }
5658
+ function resetToRefusal(anonymousId, knownUserIds, signedInAnonymousId = null, rememberedSignedInAnonymousIds = []) {
5659
+ if (typeof anonymousId !== 'string' || !RESET_TO_ANONYMOUS_ID_PATTERN.test(anonymousId)) {
5660
+ return 'resetTo: the anonymous id must be 8 to 255 letters, digits, ".", "_", ":" or "-"';
5661
+ }
5662
+ if (RESET_TO_INTERNAL_ID_PATTERN.test(anonymousId)) {
5663
+ return 'resetTo: the anonymous id has the shape of a Joryio profile id';
5664
+ }
5665
+ if (knownUserIds.some((u) => typeof u === 'string' && u === anonymousId)) {
5666
+ return 'resetTo: the anonymous id is a user id';
5667
+ }
5668
+ if ((typeof signedInAnonymousId === 'string' && signedInAnonymousId === anonymousId) || rememberedSignedInAnonymousIds.includes(anonymousId)) {
5669
+ return 'resetTo: the anonymous id belongs to the signed-in user';
5670
+ }
5671
+ return null;
5672
+ }
5673
+
5674
+ const CLICK_IDENTITY_PARAM = 'jr_t';
5675
+ const CLICK_IDENTITY_TOKEN_RE = /^[A-Za-z0-9_-]{16,512}$/;
5676
+ function readClickIdentityToken(url) {
5677
+ if (typeof url !== 'string' || !url.includes(`${CLICK_IDENTITY_PARAM}=`))
5678
+ return null;
5679
+ try {
5680
+ const base = typeof window !== 'undefined' && window.location ? window.location.href : 'https://x.invalid/';
5681
+ const value = new URL(url, base).searchParams.get(CLICK_IDENTITY_PARAM);
5682
+ return value && CLICK_IDENTITY_TOKEN_RE.test(value) ? value : null;
5683
+ }
5684
+ catch (_a) {
5685
+ return null;
5686
+ }
5687
+ }
5688
+ function withoutClickIdentityToken(url) {
5689
+ try {
5690
+ const parsed = new URL(url);
5691
+ if (!parsed.searchParams.has(CLICK_IDENTITY_PARAM))
5692
+ return null;
5693
+ parsed.searchParams.delete(CLICK_IDENTITY_PARAM);
5694
+ return parsed.toString();
5695
+ }
5696
+ catch (_a) {
5697
+ return null;
5698
+ }
5699
+ }
5700
+ function consumeClickIdentityTokenFromLocation() {
5701
+ if (typeof window === 'undefined' || !window.location)
5702
+ return null;
5703
+ const href = window.location.href;
5704
+ const token = readClickIdentityToken(href);
5705
+ const stripped = withoutClickIdentityToken(href);
5706
+ if (stripped) {
5707
+ try {
5708
+ if (window.history && typeof window.history.replaceState === 'function') {
5709
+ window.history.replaceState(window.history.state, '', stripped);
5710
+ }
5711
+ }
5712
+ catch (_a) {
5713
+ }
5714
+ }
5715
+ return token;
5716
+ }
5717
+
5462
5718
  const OPT_OUT_KEY = 'tracking_opted_out';
5463
5719
  const CONSENT_KEY = 'tracking_consent';
5464
5720
  const CONSENT_GRANT_SIGNAL_KEY = 'tracking_consent_granted_at';
@@ -5567,6 +5823,8 @@ class JoryioSDK {
5567
5823
  this.lastDecisionStamp = 0;
5568
5824
  this.awaitingSessionOf = null;
5569
5825
  this.pruneTimer = null;
5826
+ this.pendingLinkToken = null;
5827
+ this.sentLinkTokens = new Set();
5570
5828
  this.dataGate = new Set();
5571
5829
  this.inflightSessionStartAtClear = null;
5572
5830
  if (JoryioSDK.instance) {
@@ -5600,6 +5858,9 @@ class JoryioSDK {
5600
5858
  if (this.userOptedOut)
5601
5859
  this.optedOutAt = this.storedStamp(OPT_OUT_AT_KEY);
5602
5860
  this.trackingConsent = this.initialConsent(this.config.trackingConsent);
5861
+ const linkToken = consumeClickIdentityTokenFromLocation();
5862
+ if (linkToken && !this.disabled)
5863
+ this.pendingLinkToken = linkToken;
5603
5864
  this.utm = new UTMManager(this.storage, this.logger, this.config.resetSessionOnNewCampaign);
5604
5865
  const shouldResetSession = this.config.resetSessionOnNewCampaign &&
5605
5866
  this.config.captureUTM &&
@@ -5646,6 +5907,13 @@ class JoryioSDK {
5646
5907
  this.network.setSdkAuthenticationToken(this.config.sdkAuthenticationToken);
5647
5908
  }
5648
5909
  }
5910
+ this.network.setAnonymousIdSource(() => this.identity.getAnonymousId());
5911
+ if (this.config.storefrontIdentityTokenProvider) {
5912
+ this.network.setStorefrontIdentityTokenProvider(this.config.storefrontIdentityTokenProvider);
5913
+ }
5914
+ if (this.config.storefrontIdentityToken) {
5915
+ this.network.setStorefrontIdentityToken(this.config.storefrontIdentityToken);
5916
+ }
5649
5917
  this.outbox = this.createOutbox();
5650
5918
  this.inapp = new InAppMessagingManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, this.storage, Object.assign(Object.assign({ closeButton: true, backdropClose: true }, this.config.inApp.displayOptions), { onDisplay: this.config.inApp.onMessageDisplay, onClick: this.config.inApp.onMessageClick, onDismiss: this.config.inApp.onMessageDismiss }), {
5651
5919
  logCustomEvent: (name, properties) => this.track(name, properties),
@@ -5679,6 +5947,7 @@ class JoryioSDK {
5679
5947
  storage: this.storage,
5680
5948
  getDeviceId: () => this.deviceId,
5681
5949
  onSubscribeSettled: () => this.reportPushPermissionIfChanged(),
5950
+ onPrepared: () => this.reportPushPermissionIfChanged(),
5682
5951
  });
5683
5952
  this.queue.setClearedInflightCallback((delivered) => {
5684
5953
  const sessionId = this.inflightSessionStartAtClear;
@@ -5783,6 +6052,7 @@ class JoryioSDK {
5783
6052
  this.syncWorkerReporting();
5784
6053
  if (!this.isOptedOut)
5785
6054
  this.releaseDeferredIdentify();
6055
+ this.flushLinkIdentity();
5786
6056
  this.syncOptOutMarker();
5787
6057
  this.scheduleRetiredTokenPrune();
5788
6058
  this.outbox.kick();
@@ -6252,6 +6522,7 @@ class JoryioSDK {
6252
6522
  this.outbox.kick();
6253
6523
  if (this.config.inApp.enabled)
6254
6524
  this.inapp.stop();
6525
+ this.pendingLinkToken = null;
6255
6526
  return;
6256
6527
  }
6257
6528
  if (wasOptedOut)
@@ -6276,6 +6547,52 @@ class JoryioSDK {
6276
6547
  });
6277
6548
  }
6278
6549
  this._push.syncExistingSubscription().catch(() => undefined);
6550
+ this.flushLinkIdentity();
6551
+ }
6552
+ flushLinkIdentity() {
6553
+ const token = this.pendingLinkToken;
6554
+ if (!token)
6555
+ return;
6556
+ if (this.disabled || this.isOptedOut) {
6557
+ this.pendingLinkToken = null;
6558
+ return;
6559
+ }
6560
+ if (!this.canSend())
6561
+ return;
6562
+ this.pendingLinkToken = null;
6563
+ if (this.sentLinkTokens.has(token))
6564
+ return;
6565
+ if (this.effectiveUserId()) {
6566
+ this.logger.debug('Link identity not sent: a user is identified on this browser');
6567
+ return;
6568
+ }
6569
+ if (this.network.hasStorefrontIdentity()) {
6570
+ this.logger.debug('Link identity not sent: a signed-in store customer is on this browser');
6571
+ return;
6572
+ }
6573
+ this.sentLinkTokens.add(token);
6574
+ this.network
6575
+ .sendIdentifyLink(this.config.apiEndpoint, { token, anonymousId: this.identity.getAnonymousId() })
6576
+ .catch((error) => this.logger.debug('Link identity request failed:', error));
6577
+ }
6578
+ identifyFromLink(url) {
6579
+ if (!this.isInitialized || this.disabled)
6580
+ return;
6581
+ const token = readClickIdentityToken(url);
6582
+ if (!token)
6583
+ return;
6584
+ try {
6585
+ if (typeof window !== 'undefined' && window.location && readClickIdentityToken(window.location.href) === token) {
6586
+ const stripped = withoutClickIdentityToken(window.location.href);
6587
+ if (stripped && window.history && typeof window.history.replaceState === 'function') {
6588
+ window.history.replaceState(window.history.state, '', stripped);
6589
+ }
6590
+ }
6591
+ }
6592
+ catch (_a) {
6593
+ }
6594
+ this.pendingLinkToken = token;
6595
+ this.flushLinkIdentity();
6279
6596
  }
6280
6597
  releaseHeldWrites() {
6281
6598
  if (!this.identity.pending.isEmpty()) {
@@ -6695,6 +7012,8 @@ class JoryioSDK {
6695
7012
  reportPushPermissionIfChanged() {
6696
7013
  if (!this.isInitialized || this.isOptedOut)
6697
7014
  return;
7015
+ if (!this.pushPermissionReported())
7016
+ return;
6698
7017
  try {
6699
7018
  const state = this._push.getPermissionState();
6700
7019
  const current = state === 'notDetermined' ? 'not_determined' : state;
@@ -6707,6 +7026,15 @@ class JoryioSDK {
6707
7026
  this.logger.warn('Could not report push permission:', error);
6708
7027
  }
6709
7028
  }
7029
+ pushPermissionReported() {
7030
+ if (this.config.webPush === true)
7031
+ return true;
7032
+ if (this._push.usedOnThisPage())
7033
+ return true;
7034
+ if (this.config.webPush === false)
7035
+ return false;
7036
+ return this._push.usedEarlier();
7037
+ }
6710
7038
  setAttribute(key, value) {
6711
7039
  if (typeof key !== 'string' || !key) {
6712
7040
  this.logger.error('setAttribute(key, value) needs a non-empty key');
@@ -6789,18 +7117,42 @@ class JoryioSDK {
6789
7117
  }
6790
7118
  }
6791
7119
  async reset() {
7120
+ return this.resetIdentity(undefined);
7121
+ }
7122
+ async resetTo(anonymousId) {
7123
+ if (!this.isInitialized) {
7124
+ this.logger.error('SDK not initialized');
7125
+ return false;
7126
+ }
7127
+ const userId = this.identity.getUserId();
7128
+ const refusal = resetToRefusal(anonymousId, [userId, this.withdrawalUserId], userId ? this.identity.getAnonymousId() : null, this.signedInAnonymousIds());
7129
+ if (refusal)
7130
+ this.logger.error(`${refusal}; a random anonymous id is used instead`);
7131
+ await this.resetIdentity(refusal ? undefined : anonymousId);
7132
+ return !refusal;
7133
+ }
7134
+ signedInAnonymousIds() {
7135
+ const stored = this.storage.get(SIGNED_IN_ANONYMOUS_IDS_KEY);
7136
+ return Array.isArray(stored) ? stored.filter((x) => typeof x === 'string') : [];
7137
+ }
7138
+ async resetIdentity(anonymousId) {
6792
7139
  if (!this.isInitialized) {
6793
7140
  this.logger.error('SDK not initialized');
6794
7141
  return;
6795
7142
  }
6796
7143
  this.logger.info('Resetting user identity');
7144
+ this.pendingLinkToken = null;
6797
7145
  if (this.config.inApp.enabled) {
6798
7146
  this.inapp.clearAll();
6799
7147
  }
6800
7148
  this.network.retireSdkAuthToken();
7149
+ this.network.clearStorefrontIdentityToken();
6801
7150
  this.forgetDeferredIdentify();
7151
+ if (this.identity.getUserId()) {
7152
+ this.storage.set(SIGNED_IN_ANONYMOUS_IDS_KEY, rememberSignedInAnonymousId(this.signedInAnonymousIds(), this.identity.getAnonymousId()));
7153
+ }
6802
7154
  this.pinAnonymousWrites();
6803
- this.identity.reset();
7155
+ this.identity.reset(anonymousId);
6804
7156
  this.network.setCurrentUserId(this.identity.getUserId());
6805
7157
  this.utm.reset();
6806
7158
  this.session.resetSession();
@@ -6818,6 +7170,7 @@ class JoryioSDK {
6818
7170
  return;
6819
7171
  }
6820
7172
  this.logger.info('Wiping local SDK data');
7173
+ this.pendingLinkToken = null;
6821
7174
  const pushWiped = this._push.forget().catch(() => undefined);
6822
7175
  this.wipeLocalState();
6823
7176
  this.session.ensureSession();
@@ -6831,6 +7184,7 @@ class JoryioSDK {
6831
7184
  this.clearPendingAttributeWrites();
6832
7185
  this.outbox.discardNonWithdrawals();
6833
7186
  this.storage.remove(REPORTED_PUSH_PERMISSION_KEY);
7187
+ this.storage.remove(SIGNED_IN_ANONYMOUS_IDS_KEY);
6834
7188
  this.storage.set(SESSION_START_SENT_KEY, '');
6835
7189
  this.queue.clear();
6836
7190
  if (this.config.inApp.enabled) {
@@ -6856,6 +7210,7 @@ class JoryioSDK {
6856
7210
  collectUserIds(this.storage.get(key), keepTokens);
6857
7211
  this.network.retireSdkAuthToken();
6858
7212
  this.network.dropStandbySdkAuthTokens(keepTokens);
7213
+ this.network.clearStorefrontIdentityToken();
6859
7214
  this.forgetDeferredIdentify();
6860
7215
  this.pinAnonymousWrites();
6861
7216
  this.identity.reset();
@@ -7154,6 +7509,22 @@ class JoryioSDK {
7154
7509
  }
7155
7510
  this.network.setSdkAuthenticationToken(token);
7156
7511
  }
7512
+ setStorefrontIdentityToken(token) {
7513
+ var _a;
7514
+ if (!this.isInitialized) {
7515
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('SDK not initialized');
7516
+ return;
7517
+ }
7518
+ this.network.setStorefrontIdentityToken(token);
7519
+ }
7520
+ setStorefrontIdentityTokenProvider(provider) {
7521
+ var _a;
7522
+ if (!this.isInitialized) {
7523
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('SDK not initialized');
7524
+ return;
7525
+ }
7526
+ this.network.setStorefrontIdentityTokenProvider(provider);
7527
+ }
7157
7528
  setSdkAuthenticationErrorCallback(cb) {
7158
7529
  var _a;
7159
7530
  if (!this.isInitialized) {