@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.
@@ -1,5 +1,5 @@
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
  */
@@ -7,7 +7,7 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
- const SDK_VERSION = '1.3.3';
10
+ const SDK_VERSION = '1.4.0';
11
11
  const DEFAULT_API_ENDPOINT = 'https://api-eu1.joryio.com/api';
12
12
  function normalizeApiEndpoint(raw) {
13
13
  const trimmed = (raw || '').trim();
@@ -92,6 +92,7 @@ function resolveConfig(config) {
92
92
  trackPageProperties: config.trackPageProperties !== false,
93
93
  trackDeviceProperties: config.trackDeviceProperties !== false,
94
94
  inApp: inAppOptions,
95
+ webPush: config.webPush === true ? true : config.webPush === false ? false : undefined,
95
96
  persistQueue: config.persistQueue !== false,
96
97
  maxRetries: typeof config.maxRetries === 'number' && config.maxRetries >= 0 ? Math.floor(config.maxRetries) : DEFAULT_MAX_RETRIES,
97
98
  retryBackoffMs: config.retryBackoffMs || DEFAULT_RETRY_BACKOFF_MS,
@@ -103,6 +104,8 @@ function resolveConfig(config) {
103
104
  : undefined,
104
105
  enableSdkAuthentication: config.enableSdkAuthentication === true,
105
106
  sdkAuthenticationToken: config.sdkAuthenticationToken,
107
+ storefrontIdentityToken: typeof config.storefrontIdentityToken === 'string' && config.storefrontIdentityToken ? config.storefrontIdentityToken : undefined,
108
+ storefrontIdentityTokenProvider: typeof config.storefrontIdentityTokenProvider === 'function' ? config.storefrontIdentityTokenProvider : undefined,
106
109
  enableDebug: config.enableDebug || false,
107
110
  logLevel: config.logLevel || (config.enableDebug ? 'debug' : 'error'),
108
111
  loggingEnabled: config.enableDebug === true || !!config.logLevel,
@@ -730,11 +733,11 @@ class IdentityManager {
730
733
  this.logger.info(`User identified: ${userId} (was: ${previousUserId || 'anonymous'})`);
731
734
  }
732
735
  }
733
- reset() {
736
+ reset(anonymousId) {
734
737
  this.logger.debug(`Resetting identity (was: ${this.userId || 'anonymous'})`);
735
738
  this.userId = null;
736
739
  this.attributes = {};
737
- this.anonymousId = generateUUID();
740
+ this.anonymousId = anonymousId || generateUUID();
738
741
  this.storage.remove(USER_ID_KEY);
739
742
  this.storage.remove(USER_ATTRIBUTES_KEY);
740
743
  this.storage.set(ANONYMOUS_ID_KEY, this.anonymousId);
@@ -955,6 +958,36 @@ function identifiedUserOf(body) {
955
958
  }
956
959
  return null;
957
960
  }
961
+ const STOREFRONT_IDENTITY_ISSUER = 'joryio-storefront';
962
+ const STOREFRONT_IDENTITY_ERROR = 'storefront_identity_error';
963
+ const STOREFRONT_TOKEN_MIN_LIFE_MS = 30000;
964
+ function storefrontTokenClaims(token) {
965
+ const c = jwtClaims(token);
966
+ if (!c || c.iss !== STOREFRONT_IDENTITY_ISSUER)
967
+ return null;
968
+ if (typeof c.vid !== 'string' || !c.vid || typeof c.exp !== 'number')
969
+ return null;
970
+ return { vid: c.vid, exp: c.exp };
971
+ }
972
+ function anonymousIdOfBody(body) {
973
+ if (!body || typeof body !== 'object')
974
+ return null;
975
+ if (identifiedUserOf(body))
976
+ return null;
977
+ const ids = new Set();
978
+ const add = (v) => {
979
+ if (typeof v === 'string' && v)
980
+ ids.add(v);
981
+ };
982
+ add(body.anonymousId);
983
+ if (body.identify)
984
+ add(body.identify.anonymousId);
985
+ for (const list of [body.events, body.impressions]) {
986
+ if (Array.isArray(list))
987
+ list.forEach((e) => e && add(e.anonymousId));
988
+ }
989
+ return ids.size === 1 ? ids.values().next().value : null;
990
+ }
958
991
  const DEFAULT_CIRCUIT_BREAKER_CONFIG = {
959
992
  failureThreshold: 5,
960
993
  cooldownMs: 30000,
@@ -971,12 +1004,96 @@ class NetworkClient {
971
1004
  this.sdkAuthTokenUser = null;
972
1005
  this.keepaliveBytesInFlight = 0;
973
1006
  this.currentUserId = null;
1007
+ this.storefrontTokenProvider = null;
1008
+ this.storefrontRefresh = null;
1009
+ this.anonymousIdSource = null;
974
1010
  this.suspended = false;
975
1011
  this.sdkKey = sdkKey;
976
1012
  this.logger = logger;
977
1013
  this.retryConfig = retryConfig;
978
1014
  this.circuitBreakerConfig = Object.assign(Object.assign({}, DEFAULT_CIRCUIT_BREAKER_CONFIG), circuitBreakerConfig);
979
1015
  }
1016
+ setAnonymousIdSource(source) {
1017
+ this.anonymousIdSource = source;
1018
+ }
1019
+ setStorefrontIdentityToken(token) {
1020
+ const next = typeof token === 'string' && token ? token : undefined;
1021
+ if (next && !storefrontTokenClaims(next)) {
1022
+ this.logger.warn('setStorefrontIdentityToken: not a storefront identity token - ignored');
1023
+ return;
1024
+ }
1025
+ this.storefrontToken = next;
1026
+ }
1027
+ setStorefrontIdentityTokenProvider(provider) {
1028
+ this.storefrontTokenProvider = provider;
1029
+ }
1030
+ clearStorefrontIdentityToken() {
1031
+ this.storefrontToken = undefined;
1032
+ this.storefrontRefresh = null;
1033
+ }
1034
+ isStorefrontIdentityError(status, data) {
1035
+ return status === 401 && !!data && typeof data === 'object' && data.error === STOREFRONT_IDENTITY_ERROR;
1036
+ }
1037
+ storefrontTokenFor(subjectUserId, bodyAnonymousId) {
1038
+ const token = this.storefrontToken;
1039
+ if (!token)
1040
+ return undefined;
1041
+ const user = subjectUserId === undefined ? this.currentUserId : subjectUserId;
1042
+ if (user)
1043
+ return undefined;
1044
+ const claims = storefrontTokenClaims(token);
1045
+ const current = this.anonymousIdSource ? this.anonymousIdSource() : null;
1046
+ if (!claims || !current || claims.vid !== current)
1047
+ return undefined;
1048
+ if (bodyAnonymousId === null)
1049
+ return undefined;
1050
+ if (bodyAnonymousId !== undefined && bodyAnonymousId !== claims.vid)
1051
+ return undefined;
1052
+ if (claims.exp * 1000 - Date.now() < STOREFRONT_TOKEN_MIN_LIFE_MS) {
1053
+ void this.refreshStorefrontToken();
1054
+ return undefined;
1055
+ }
1056
+ return token;
1057
+ }
1058
+ refreshStorefrontToken() {
1059
+ if (!this.storefrontTokenProvider)
1060
+ return Promise.resolve(undefined);
1061
+ if (this.storefrontRefresh)
1062
+ return this.storefrontRefresh;
1063
+ const previous = this.storefrontToken;
1064
+ const provider = this.storefrontTokenProvider;
1065
+ this.storefrontRefresh = (async () => {
1066
+ try {
1067
+ const fresh = await Promise.resolve(provider());
1068
+ if (typeof fresh === 'string' && fresh && storefrontTokenClaims(fresh)) {
1069
+ this.storefrontToken = fresh;
1070
+ return fresh !== previous ? fresh : undefined;
1071
+ }
1072
+ }
1073
+ catch (err) {
1074
+ this.logger.warn('The storefront identity token provider failed:', err);
1075
+ }
1076
+ return undefined;
1077
+ })().finally(() => {
1078
+ this.storefrontRefresh = null;
1079
+ });
1080
+ return this.storefrontRefresh;
1081
+ }
1082
+ async handleStorefrontIdentityError(data) {
1083
+ const reason = data && typeof data === 'object' ? data.reason : undefined;
1084
+ this.logger.warn(`Storefront identity token refused (${reason || 'invalid'})`);
1085
+ if (reason === 'expired') {
1086
+ const before = this.storefrontToken;
1087
+ const fresh = await this.refreshStorefrontToken();
1088
+ if (fresh)
1089
+ return true;
1090
+ if (this.storefrontToken === before)
1091
+ this.storefrontToken = undefined;
1092
+ return true;
1093
+ }
1094
+ this.storefrontToken = undefined;
1095
+ return true;
1096
+ }
980
1097
  setSdkAuthenticationEnabled(enabled) {
981
1098
  this.sdkAuthEnabled = enabled;
982
1099
  }
@@ -1187,8 +1304,9 @@ class NetworkClient {
1187
1304
  }
1188
1305
  return true;
1189
1306
  }
1190
- getSdkAuthHeaders(subjectUserId) {
1191
- const token = this.sdkAuthTokenFor(subjectUserId);
1307
+ getSdkAuthHeaders(subjectUserId, anonymousId) {
1308
+ var _a;
1309
+ const token = (_a = this.sdkAuthTokenFor(subjectUserId)) !== null && _a !== void 0 ? _a : this.storefrontTokenFor(subjectUserId, anonymousId);
1192
1310
  return token ? { [SDK_AUTH_HEADER]: token } : {};
1193
1311
  }
1194
1312
  keepaliveBudget() {
@@ -1250,16 +1368,24 @@ class NetworkClient {
1250
1368
  return { ok: false, status: 400, error: 'The request body cannot be serialized' };
1251
1369
  }
1252
1370
  const forCurrentUser = request.subjectUserId === undefined || (request.subjectUserId || null) === this.currentUserId;
1371
+ const bodyAnonymousId = request.body ? anonymousIdOfBody(request.body) : undefined;
1253
1372
  let lastError = null;
1254
1373
  let lastStatus = 0;
1255
1374
  let lastData;
1256
1375
  let retryAfterMs;
1257
1376
  let attempt = 0;
1258
1377
  let sdkAuthRefreshAttempted = false;
1378
+ let storefrontRetryAttempted = false;
1259
1379
  while (attempt <= this.retryConfig.maxRetries) {
1260
1380
  try {
1261
1381
  this.logger.debug(`Request attempt ${attempt + 1}/${this.retryConfig.maxRetries + 1}: ${method} ${url}`);
1262
- let { response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId);
1382
+ let { response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId);
1383
+ if (!storefrontRetryAttempted && this.isStorefrontIdentityError(response.status, responseData)) {
1384
+ storefrontRetryAttempted = true;
1385
+ if (await this.handleStorefrontIdentityError(responseData)) {
1386
+ ({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId));
1387
+ }
1388
+ }
1263
1389
  if (!sdkAuthRefreshAttempted &&
1264
1390
  this.sdkAuthEnabled &&
1265
1391
  forCurrentUser &&
@@ -1273,7 +1399,7 @@ class NetworkClient {
1273
1399
  });
1274
1400
  if (fresh) {
1275
1401
  this.logger.debug('SDK authentication token refreshed – retrying request once');
1276
- ({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId));
1402
+ ({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId));
1277
1403
  }
1278
1404
  }
1279
1405
  if (response.ok) {
@@ -1358,11 +1484,12 @@ class NetworkClient {
1358
1484
  openedAt: this.circuitOpenedAt,
1359
1485
  };
1360
1486
  }
1361
- async performFetch(url, method, callerHeaders, body, subjectUserId) {
1487
+ async performFetch(url, method, callerHeaders, body, subjectUserId, bodyAnonymousId) {
1488
+ var _a;
1362
1489
  const controller = new AbortController();
1363
1490
  const timeoutId = setTimeout(() => controller.abort(), this.retryConfig.timeoutMs || 10000);
1364
1491
  const headers = Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, callerHeaders);
1365
- const authToken = this.sdkAuthTokenFor(subjectUserId);
1492
+ const authToken = (_a = this.sdkAuthTokenFor(subjectUserId)) !== null && _a !== void 0 ? _a : this.storefrontTokenFor(subjectUserId, bodyAnonymousId);
1366
1493
  if (authToken) {
1367
1494
  headers[SDK_AUTH_HEADER] = authToken;
1368
1495
  }
@@ -1440,13 +1567,14 @@ class NetworkClient {
1440
1567
  return this.postKeepalive(`${apiEndpoint}/v1/track/batch`, body);
1441
1568
  }
1442
1569
  postKeepalive(url, body) {
1570
+ var _a;
1443
1571
  if ((this.suspended && !isWithdrawalRequest(url, body)) || !this.supportsKeepalive())
1444
1572
  return null;
1445
1573
  let json;
1446
1574
  try {
1447
1575
  json = JSON.stringify(body);
1448
1576
  }
1449
- catch (_a) {
1577
+ catch (_b) {
1450
1578
  return null;
1451
1579
  }
1452
1580
  const bytes = utf8Length(json) + 256;
@@ -1456,7 +1584,8 @@ class NetworkClient {
1456
1584
  'Content-Type': 'application/json',
1457
1585
  'X-SDK-Key': this.sdkKey,
1458
1586
  };
1459
- const authToken = this.sdkAuthTokenFor(identifiedUserOf(body));
1587
+ const subject = identifiedUserOf(body);
1588
+ const authToken = (_a = this.sdkAuthTokenFor(subject)) !== null && _a !== void 0 ? _a : this.storefrontTokenFor(subject, anonymousIdOfBody(body));
1460
1589
  if (authToken) {
1461
1590
  headers[SDK_AUTH_HEADER] = authToken;
1462
1591
  }
@@ -1503,6 +1632,22 @@ class NetworkClient {
1503
1632
  subjectUserId: userId,
1504
1633
  });
1505
1634
  }
1635
+ async sendIdentifyLink(apiEndpoint, payload) {
1636
+ return this.request({
1637
+ url: `${apiEndpoint}/v1/identify-link`,
1638
+ method: 'POST',
1639
+ body: { token: payload.token, anonymousId: payload.anonymousId },
1640
+ subjectUserId: null,
1641
+ });
1642
+ }
1643
+ hasStorefrontIdentity() {
1644
+ const token = this.storefrontToken;
1645
+ if (!token)
1646
+ return false;
1647
+ const claims = storefrontTokenClaims(token);
1648
+ const current = this.anonymousIdSource ? this.anonymousIdSource() : null;
1649
+ return !!claims && !!current && claims.vid === current;
1650
+ }
1506
1651
  async sendAddAlias(apiEndpoint, payload) {
1507
1652
  return this.request({
1508
1653
  url: `${apiEndpoint}/v1/alias/add`,
@@ -2753,6 +2898,7 @@ class InAppMessagingManager {
2753
2898
  return Object.assign(Object.assign({}, (userId ? { userId } : {})), { anonymousId: this.identity.getAnonymousId() });
2754
2899
  }
2755
2900
  async maybeHandleSdkAuthError(response, endpoint, subjectUserId) {
2901
+ var _a, _b, _c, _d;
2756
2902
  if (!this.auth || response.status !== 401) {
2757
2903
  return;
2758
2904
  }
@@ -2763,7 +2909,11 @@ class InAppMessagingManager {
2763
2909
  try {
2764
2910
  data = await response.clone().json();
2765
2911
  }
2766
- catch (_a) {
2912
+ catch (_e) {
2913
+ return;
2914
+ }
2915
+ if ((_b = (_a = this.auth).isStorefrontIdentityError) === null || _b === void 0 ? void 0 : _b.call(_a, response.status, data)) {
2916
+ await ((_d = (_c = this.auth).handleStorefrontIdentityError) === null || _d === void 0 ? void 0 : _d.call(_c, data).catch(() => false));
2767
2917
  return;
2768
2918
  }
2769
2919
  if (!this.auth.isSdkAuthError(response.status, data)) {
@@ -2804,7 +2954,7 @@ class InAppMessagingManager {
2804
2954
  try {
2805
2955
  const response = await fetch(`${this.apiEndpoint}/v1/in-app/sync`, {
2806
2956
  method: 'POST',
2807
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(subjectUser)) || {})),
2957
+ 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())) || {})),
2808
2958
  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() })),
2809
2959
  signal: controller.signal,
2810
2960
  });
@@ -2916,7 +3066,7 @@ class InAppMessagingManager {
2916
3066
  try {
2917
3067
  const res = await fetch(`${this.apiEndpoint}/v1/in-app/resolve`, {
2918
3068
  method: 'POST',
2919
- 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())) || {})),
3069
+ 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())) || {})),
2920
3070
  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' })),
2921
3071
  signal: controller.signal,
2922
3072
  });
@@ -3660,7 +3810,7 @@ class InAppMessagingManager {
3660
3810
  this.callHost('onConversion', () => { var _a, _b; return (_b = (_a = this.displayOptions).onConversion) === null || _b === void 0 ? void 0 : _b.call(_a, message, event); });
3661
3811
  }
3662
3812
  async submitForm(campaignId, values) {
3663
- var _a, _b;
3813
+ var _a, _b, _c;
3664
3814
  const message = this.displayedMessages.get(campaignId);
3665
3815
  if (!this.runtime.canSend())
3666
3816
  return { ok: false, message: 'This form cannot be sent right now.' };
@@ -3668,25 +3818,29 @@ class InAppMessagingManager {
3668
3818
  const timeoutId = setTimeout(() => controller.abort(), this.runtime.requestTimeoutMs);
3669
3819
  const subjectUser = this.identity.getUserId();
3670
3820
  try {
3671
- const response = await fetch(`${this.apiEndpoint}/v1/in-app/form-submit`, {
3672
- method: 'POST',
3673
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_a = this.auth) === null || _a === void 0 ? void 0 : _a.getSdkAuthHeaders(subjectUser)) || {})),
3674
- body: JSON.stringify({
3675
- campaignId,
3676
- variantId: (_b = message === null || message === void 0 ? void 0 : message.campaign) === null || _b === void 0 ? void 0 : _b.variantId,
3677
- userId: this.identity.getUserId() || undefined,
3678
- anonymousId: this.identity.getAnonymousId(),
3679
- values,
3680
- }),
3681
- signal: controller.signal,
3682
- });
3821
+ const send = () => {
3822
+ var _a, _b, _c;
3823
+ return fetch(`${this.apiEndpoint}/v1/in-app/form-submit`, {
3824
+ method: 'POST',
3825
+ 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())) || {})),
3826
+ 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 })),
3827
+ signal: controller.signal,
3828
+ });
3829
+ };
3830
+ let response = await send();
3831
+ if (response.status === 401 && ((_a = this.auth) === null || _a === void 0 ? void 0 : _a.isStorefrontIdentityError)) {
3832
+ const data = await response.clone().json().catch(() => null);
3833
+ if (this.auth.isStorefrontIdentityError(401, data) && (await ((_c = (_b = this.auth).handleStorefrontIdentityError) === null || _c === void 0 ? void 0 : _c.call(_b, data).catch(() => false)))) {
3834
+ response = await send();
3835
+ }
3836
+ }
3683
3837
  await this.maybeHandleSdkAuthError(response, `${this.apiEndpoint}/v1/in-app/form-submit`, subjectUser);
3684
3838
  const json = await response.json().catch(() => null);
3685
3839
  if (!json || typeof json !== 'object')
3686
3840
  return { ok: false, message: 'Something went wrong. Please try again.' };
3687
3841
  return json;
3688
3842
  }
3689
- catch (_c) {
3843
+ catch (_d) {
3690
3844
  return { ok: false, message: 'Something went wrong. Please try again.' };
3691
3845
  }
3692
3846
  finally {
@@ -3694,7 +3848,7 @@ class InAppMessagingManager {
3694
3848
  }
3695
3849
  }
3696
3850
  async trackImpression(campaignId, type, extra) {
3697
- var _a, _b, _c, _d;
3851
+ var _a, _b, _c, _d, _e;
3698
3852
  const campaign = this.campaigns.get(campaignId) || ((_a = this.displayedMessages.get(campaignId)) === null || _a === void 0 ? void 0 : _a.campaign);
3699
3853
  if (!campaign)
3700
3854
  return;
@@ -3730,12 +3884,12 @@ class InAppMessagingManager {
3730
3884
  try {
3731
3885
  const response = await fetch(`${this.apiEndpoint}/v1/in-app/track`, {
3732
3886
  method: 'POST',
3733
- headers: Object.assign({ 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey }, (((_b = this.auth) === null || _b === void 0 ? void 0 : _b.getSdkAuthHeaders(subjectUser)) || {})),
3887
+ 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)) || {})),
3734
3888
  body: JSON.stringify(data),
3735
3889
  signal: controller.signal,
3736
3890
  });
3737
3891
  if (!response.ok)
3738
- (_d = (_c = this.runtime).noteStatus) === null || _d === void 0 ? void 0 : _d.call(_c, response.status, null);
3892
+ (_e = (_d = this.runtime).noteStatus) === null || _e === void 0 ? void 0 : _e.call(_d, response.status, null);
3739
3893
  await this.maybeHandleSdkAuthError(response, `${this.apiEndpoint}/v1/in-app/track`, subjectUser);
3740
3894
  this.logger.debug(`Tracked ${type} for campaign ${campaignId}`);
3741
3895
  }
@@ -4456,6 +4610,7 @@ function writeAttemptsExhausted(attempts, notFoundAttempts) {
4456
4610
 
4457
4611
  const REGISTRATION_MARKER_KEY = 'push_registration';
4458
4612
  const UNREGISTERED_KEY = 'push_unregistered';
4613
+ const IN_USE_KEY = 'push_in_use';
4459
4614
  const PENDING_UNREGISTER_KEY = 'push_pending_unregister';
4460
4615
  const REREGISTER_EVERY_MS = 24 * 60 * 60 * 1000;
4461
4616
  const SW_STATE_CACHE = 'joryio-sdk-state';
@@ -4471,12 +4626,38 @@ class PushManager {
4471
4626
  this.lastPrepareError = null;
4472
4627
  this.unregisterInFlight = false;
4473
4628
  this.unregisterTimer = null;
4629
+ this.usedThisPage = false;
4474
4630
  this.canSend = options.canSend || (() => true);
4475
4631
  this.canWithdraw = options.canWithdraw || (() => true);
4476
4632
  this.withdrawalUserId = options.withdrawalUserId || (() => this.identity.getUserId());
4477
4633
  this.storage = options.storage || null;
4478
4634
  this.getDeviceId = options.getDeviceId || (() => undefined);
4479
4635
  this.onSubscribeSettled = options.onSubscribeSettled || null;
4636
+ this.onPrepared = options.onPrepared || null;
4637
+ }
4638
+ usedOnThisPage() {
4639
+ return this.usedThisPage;
4640
+ }
4641
+ usedEarlier() {
4642
+ if (!this.storage)
4643
+ return false;
4644
+ try {
4645
+ return (this.storage.get(IN_USE_KEY) === true ||
4646
+ this.storage.get(REGISTRATION_MARKER_KEY) != null ||
4647
+ this.storage.get(UNREGISTERED_KEY) === true);
4648
+ }
4649
+ catch (_a) {
4650
+ return false;
4651
+ }
4652
+ }
4653
+ markUsed() {
4654
+ var _a;
4655
+ this.usedThisPage = true;
4656
+ try {
4657
+ (_a = this.storage) === null || _a === void 0 ? void 0 : _a.set(IN_USE_KEY, true);
4658
+ }
4659
+ catch (_b) {
4660
+ }
4480
4661
  }
4481
4662
  isSupported() {
4482
4663
  return (typeof window !== 'undefined' &&
@@ -4568,6 +4749,7 @@ class PushManager {
4568
4749
  }
4569
4750
  }
4570
4751
  async prepare(options) {
4752
+ var _a;
4571
4753
  options = options || {};
4572
4754
  if (!this.isSupported()) {
4573
4755
  this.lastPrepareError = 'unsupported';
@@ -4588,6 +4770,13 @@ class PushManager {
4588
4770
  await navigator.serviceWorker.ready;
4589
4771
  this.prepared = { registration, publicKey };
4590
4772
  this.lastPrepareError = null;
4773
+ this.markUsed();
4774
+ try {
4775
+ (_a = this.onPrepared) === null || _a === void 0 ? void 0 : _a.call(this);
4776
+ }
4777
+ catch (error) {
4778
+ this.logger.warn('Push permission report failed:', error);
4779
+ }
4591
4780
  return true;
4592
4781
  }
4593
4782
  catch (err) {
@@ -4602,6 +4791,7 @@ class PushManager {
4602
4791
  return await this.subscribeOnce(options);
4603
4792
  }
4604
4793
  finally {
4794
+ this.markUsed();
4605
4795
  try {
4606
4796
  (_a = this.onSubscribeSettled) === null || _a === void 0 ? void 0 : _a.call(this);
4607
4797
  }
@@ -5463,6 +5653,72 @@ function withoutUnsendableValues(values, warn) {
5463
5653
  return out;
5464
5654
  }
5465
5655
 
5656
+ const RESET_TO_ANONYMOUS_ID_PATTERN = /^[A-Za-z0-9._:-]{8,255}$/;
5657
+ const RESET_TO_INTERNAL_ID_PATTERN = /^[0-9a-f]{24}$/;
5658
+ const SIGNED_IN_ANONYMOUS_IDS_KEY = 'signed_in_anonymous_ids';
5659
+ function rememberSignedInAnonymousId(list, id) {
5660
+ return [...list.filter((x) => x !== id), id].slice(-20);
5661
+ }
5662
+ function resetToRefusal(anonymousId, knownUserIds, signedInAnonymousId = null, rememberedSignedInAnonymousIds = []) {
5663
+ if (typeof anonymousId !== 'string' || !RESET_TO_ANONYMOUS_ID_PATTERN.test(anonymousId)) {
5664
+ return 'resetTo: the anonymous id must be 8 to 255 letters, digits, ".", "_", ":" or "-"';
5665
+ }
5666
+ if (RESET_TO_INTERNAL_ID_PATTERN.test(anonymousId)) {
5667
+ return 'resetTo: the anonymous id has the shape of a Joryio profile id';
5668
+ }
5669
+ if (knownUserIds.some((u) => typeof u === 'string' && u === anonymousId)) {
5670
+ return 'resetTo: the anonymous id is a user id';
5671
+ }
5672
+ if ((typeof signedInAnonymousId === 'string' && signedInAnonymousId === anonymousId) || rememberedSignedInAnonymousIds.includes(anonymousId)) {
5673
+ return 'resetTo: the anonymous id belongs to the signed-in user';
5674
+ }
5675
+ return null;
5676
+ }
5677
+
5678
+ const CLICK_IDENTITY_PARAM = 'jr_t';
5679
+ const CLICK_IDENTITY_TOKEN_RE = /^[A-Za-z0-9_-]{16,512}$/;
5680
+ function readClickIdentityToken(url) {
5681
+ if (typeof url !== 'string' || !url.includes(`${CLICK_IDENTITY_PARAM}=`))
5682
+ return null;
5683
+ try {
5684
+ const base = typeof window !== 'undefined' && window.location ? window.location.href : 'https://x.invalid/';
5685
+ const value = new URL(url, base).searchParams.get(CLICK_IDENTITY_PARAM);
5686
+ return value && CLICK_IDENTITY_TOKEN_RE.test(value) ? value : null;
5687
+ }
5688
+ catch (_a) {
5689
+ return null;
5690
+ }
5691
+ }
5692
+ function withoutClickIdentityToken(url) {
5693
+ try {
5694
+ const parsed = new URL(url);
5695
+ if (!parsed.searchParams.has(CLICK_IDENTITY_PARAM))
5696
+ return null;
5697
+ parsed.searchParams.delete(CLICK_IDENTITY_PARAM);
5698
+ return parsed.toString();
5699
+ }
5700
+ catch (_a) {
5701
+ return null;
5702
+ }
5703
+ }
5704
+ function consumeClickIdentityTokenFromLocation() {
5705
+ if (typeof window === 'undefined' || !window.location)
5706
+ return null;
5707
+ const href = window.location.href;
5708
+ const token = readClickIdentityToken(href);
5709
+ const stripped = withoutClickIdentityToken(href);
5710
+ if (stripped) {
5711
+ try {
5712
+ if (window.history && typeof window.history.replaceState === 'function') {
5713
+ window.history.replaceState(window.history.state, '', stripped);
5714
+ }
5715
+ }
5716
+ catch (_a) {
5717
+ }
5718
+ }
5719
+ return token;
5720
+ }
5721
+
5466
5722
  const OPT_OUT_KEY = 'tracking_opted_out';
5467
5723
  const CONSENT_KEY = 'tracking_consent';
5468
5724
  const CONSENT_GRANT_SIGNAL_KEY = 'tracking_consent_granted_at';
@@ -5571,6 +5827,8 @@ class JoryioSDK {
5571
5827
  this.lastDecisionStamp = 0;
5572
5828
  this.awaitingSessionOf = null;
5573
5829
  this.pruneTimer = null;
5830
+ this.pendingLinkToken = null;
5831
+ this.sentLinkTokens = new Set();
5574
5832
  this.dataGate = new Set();
5575
5833
  this.inflightSessionStartAtClear = null;
5576
5834
  if (JoryioSDK.instance) {
@@ -5604,6 +5862,9 @@ class JoryioSDK {
5604
5862
  if (this.userOptedOut)
5605
5863
  this.optedOutAt = this.storedStamp(OPT_OUT_AT_KEY);
5606
5864
  this.trackingConsent = this.initialConsent(this.config.trackingConsent);
5865
+ const linkToken = consumeClickIdentityTokenFromLocation();
5866
+ if (linkToken && !this.disabled)
5867
+ this.pendingLinkToken = linkToken;
5607
5868
  this.utm = new UTMManager(this.storage, this.logger, this.config.resetSessionOnNewCampaign);
5608
5869
  const shouldResetSession = this.config.resetSessionOnNewCampaign &&
5609
5870
  this.config.captureUTM &&
@@ -5650,6 +5911,13 @@ class JoryioSDK {
5650
5911
  this.network.setSdkAuthenticationToken(this.config.sdkAuthenticationToken);
5651
5912
  }
5652
5913
  }
5914
+ this.network.setAnonymousIdSource(() => this.identity.getAnonymousId());
5915
+ if (this.config.storefrontIdentityTokenProvider) {
5916
+ this.network.setStorefrontIdentityTokenProvider(this.config.storefrontIdentityTokenProvider);
5917
+ }
5918
+ if (this.config.storefrontIdentityToken) {
5919
+ this.network.setStorefrontIdentityToken(this.config.storefrontIdentityToken);
5920
+ }
5653
5921
  this.outbox = this.createOutbox();
5654
5922
  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 }), {
5655
5923
  logCustomEvent: (name, properties) => this.track(name, properties),
@@ -5683,6 +5951,7 @@ class JoryioSDK {
5683
5951
  storage: this.storage,
5684
5952
  getDeviceId: () => this.deviceId,
5685
5953
  onSubscribeSettled: () => this.reportPushPermissionIfChanged(),
5954
+ onPrepared: () => this.reportPushPermissionIfChanged(),
5686
5955
  });
5687
5956
  this.queue.setClearedInflightCallback((delivered) => {
5688
5957
  const sessionId = this.inflightSessionStartAtClear;
@@ -5787,6 +6056,7 @@ class JoryioSDK {
5787
6056
  this.syncWorkerReporting();
5788
6057
  if (!this.isOptedOut)
5789
6058
  this.releaseDeferredIdentify();
6059
+ this.flushLinkIdentity();
5790
6060
  this.syncOptOutMarker();
5791
6061
  this.scheduleRetiredTokenPrune();
5792
6062
  this.outbox.kick();
@@ -6256,6 +6526,7 @@ class JoryioSDK {
6256
6526
  this.outbox.kick();
6257
6527
  if (this.config.inApp.enabled)
6258
6528
  this.inapp.stop();
6529
+ this.pendingLinkToken = null;
6259
6530
  return;
6260
6531
  }
6261
6532
  if (wasOptedOut)
@@ -6280,6 +6551,52 @@ class JoryioSDK {
6280
6551
  });
6281
6552
  }
6282
6553
  this._push.syncExistingSubscription().catch(() => undefined);
6554
+ this.flushLinkIdentity();
6555
+ }
6556
+ flushLinkIdentity() {
6557
+ const token = this.pendingLinkToken;
6558
+ if (!token)
6559
+ return;
6560
+ if (this.disabled || this.isOptedOut) {
6561
+ this.pendingLinkToken = null;
6562
+ return;
6563
+ }
6564
+ if (!this.canSend())
6565
+ return;
6566
+ this.pendingLinkToken = null;
6567
+ if (this.sentLinkTokens.has(token))
6568
+ return;
6569
+ if (this.effectiveUserId()) {
6570
+ this.logger.debug('Link identity not sent: a user is identified on this browser');
6571
+ return;
6572
+ }
6573
+ if (this.network.hasStorefrontIdentity()) {
6574
+ this.logger.debug('Link identity not sent: a signed-in store customer is on this browser');
6575
+ return;
6576
+ }
6577
+ this.sentLinkTokens.add(token);
6578
+ this.network
6579
+ .sendIdentifyLink(this.config.apiEndpoint, { token, anonymousId: this.identity.getAnonymousId() })
6580
+ .catch((error) => this.logger.debug('Link identity request failed:', error));
6581
+ }
6582
+ identifyFromLink(url) {
6583
+ if (!this.isInitialized || this.disabled)
6584
+ return;
6585
+ const token = readClickIdentityToken(url);
6586
+ if (!token)
6587
+ return;
6588
+ try {
6589
+ if (typeof window !== 'undefined' && window.location && readClickIdentityToken(window.location.href) === token) {
6590
+ const stripped = withoutClickIdentityToken(window.location.href);
6591
+ if (stripped && window.history && typeof window.history.replaceState === 'function') {
6592
+ window.history.replaceState(window.history.state, '', stripped);
6593
+ }
6594
+ }
6595
+ }
6596
+ catch (_a) {
6597
+ }
6598
+ this.pendingLinkToken = token;
6599
+ this.flushLinkIdentity();
6283
6600
  }
6284
6601
  releaseHeldWrites() {
6285
6602
  if (!this.identity.pending.isEmpty()) {
@@ -6699,6 +7016,8 @@ class JoryioSDK {
6699
7016
  reportPushPermissionIfChanged() {
6700
7017
  if (!this.isInitialized || this.isOptedOut)
6701
7018
  return;
7019
+ if (!this.pushPermissionReported())
7020
+ return;
6702
7021
  try {
6703
7022
  const state = this._push.getPermissionState();
6704
7023
  const current = state === 'notDetermined' ? 'not_determined' : state;
@@ -6711,6 +7030,15 @@ class JoryioSDK {
6711
7030
  this.logger.warn('Could not report push permission:', error);
6712
7031
  }
6713
7032
  }
7033
+ pushPermissionReported() {
7034
+ if (this.config.webPush === true)
7035
+ return true;
7036
+ if (this._push.usedOnThisPage())
7037
+ return true;
7038
+ if (this.config.webPush === false)
7039
+ return false;
7040
+ return this._push.usedEarlier();
7041
+ }
6714
7042
  setAttribute(key, value) {
6715
7043
  if (typeof key !== 'string' || !key) {
6716
7044
  this.logger.error('setAttribute(key, value) needs a non-empty key');
@@ -6793,18 +7121,42 @@ class JoryioSDK {
6793
7121
  }
6794
7122
  }
6795
7123
  async reset() {
7124
+ return this.resetIdentity(undefined);
7125
+ }
7126
+ async resetTo(anonymousId) {
7127
+ if (!this.isInitialized) {
7128
+ this.logger.error('SDK not initialized');
7129
+ return false;
7130
+ }
7131
+ const userId = this.identity.getUserId();
7132
+ const refusal = resetToRefusal(anonymousId, [userId, this.withdrawalUserId], userId ? this.identity.getAnonymousId() : null, this.signedInAnonymousIds());
7133
+ if (refusal)
7134
+ this.logger.error(`${refusal}; a random anonymous id is used instead`);
7135
+ await this.resetIdentity(refusal ? undefined : anonymousId);
7136
+ return !refusal;
7137
+ }
7138
+ signedInAnonymousIds() {
7139
+ const stored = this.storage.get(SIGNED_IN_ANONYMOUS_IDS_KEY);
7140
+ return Array.isArray(stored) ? stored.filter((x) => typeof x === 'string') : [];
7141
+ }
7142
+ async resetIdentity(anonymousId) {
6796
7143
  if (!this.isInitialized) {
6797
7144
  this.logger.error('SDK not initialized');
6798
7145
  return;
6799
7146
  }
6800
7147
  this.logger.info('Resetting user identity');
7148
+ this.pendingLinkToken = null;
6801
7149
  if (this.config.inApp.enabled) {
6802
7150
  this.inapp.clearAll();
6803
7151
  }
6804
7152
  this.network.retireSdkAuthToken();
7153
+ this.network.clearStorefrontIdentityToken();
6805
7154
  this.forgetDeferredIdentify();
7155
+ if (this.identity.getUserId()) {
7156
+ this.storage.set(SIGNED_IN_ANONYMOUS_IDS_KEY, rememberSignedInAnonymousId(this.signedInAnonymousIds(), this.identity.getAnonymousId()));
7157
+ }
6806
7158
  this.pinAnonymousWrites();
6807
- this.identity.reset();
7159
+ this.identity.reset(anonymousId);
6808
7160
  this.network.setCurrentUserId(this.identity.getUserId());
6809
7161
  this.utm.reset();
6810
7162
  this.session.resetSession();
@@ -6822,6 +7174,7 @@ class JoryioSDK {
6822
7174
  return;
6823
7175
  }
6824
7176
  this.logger.info('Wiping local SDK data');
7177
+ this.pendingLinkToken = null;
6825
7178
  const pushWiped = this._push.forget().catch(() => undefined);
6826
7179
  this.wipeLocalState();
6827
7180
  this.session.ensureSession();
@@ -6835,6 +7188,7 @@ class JoryioSDK {
6835
7188
  this.clearPendingAttributeWrites();
6836
7189
  this.outbox.discardNonWithdrawals();
6837
7190
  this.storage.remove(REPORTED_PUSH_PERMISSION_KEY);
7191
+ this.storage.remove(SIGNED_IN_ANONYMOUS_IDS_KEY);
6838
7192
  this.storage.set(SESSION_START_SENT_KEY, '');
6839
7193
  this.queue.clear();
6840
7194
  if (this.config.inApp.enabled) {
@@ -6860,6 +7214,7 @@ class JoryioSDK {
6860
7214
  collectUserIds(this.storage.get(key), keepTokens);
6861
7215
  this.network.retireSdkAuthToken();
6862
7216
  this.network.dropStandbySdkAuthTokens(keepTokens);
7217
+ this.network.clearStorefrontIdentityToken();
6863
7218
  this.forgetDeferredIdentify();
6864
7219
  this.pinAnonymousWrites();
6865
7220
  this.identity.reset();
@@ -7158,6 +7513,22 @@ class JoryioSDK {
7158
7513
  }
7159
7514
  this.network.setSdkAuthenticationToken(token);
7160
7515
  }
7516
+ setStorefrontIdentityToken(token) {
7517
+ var _a;
7518
+ if (!this.isInitialized) {
7519
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('SDK not initialized');
7520
+ return;
7521
+ }
7522
+ this.network.setStorefrontIdentityToken(token);
7523
+ }
7524
+ setStorefrontIdentityTokenProvider(provider) {
7525
+ var _a;
7526
+ if (!this.isInitialized) {
7527
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('SDK not initialized');
7528
+ return;
7529
+ }
7530
+ this.network.setStorefrontIdentityTokenProvider(provider);
7531
+ }
7161
7532
  setSdkAuthenticationErrorCallback(cb) {
7162
7533
  var _a;
7163
7534
  if (!this.isInitialized) {