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