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

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/src/core/push.ts CHANGED
@@ -30,6 +30,13 @@ const REGISTRATION_MARKER_KEY = 'push_registration';
30
30
  * permission still granted and silently subscribed the browser again.
31
31
  */
32
32
  const UNREGISTERED_KEY = 'push_unregistered';
33
+ /**
34
+ * Set when this browser first uses Joryio web push (subscribe() called, or
35
+ * prepare() succeeded). With `webPush` unset in the init config, it is what
36
+ * makes the SDK report `push_permission` on later page loads - including a
37
+ * revocation made in the browser's settings.
38
+ */
39
+ const IN_USE_KEY = 'push_in_use';
33
40
  /**
34
41
  * Server-side unregisters not acknowledged yet. A WITHDRAWAL (contract item
35
42
  * 36): sent even while opted out, with consent denied or pending, and after
@@ -82,6 +89,11 @@ export interface PushManagerOptions {
82
89
  * page load.
83
90
  */
84
91
  onSubscribeSettled?: () => void;
92
+ /**
93
+ * Called when prepare() succeeds: the workspace has web push on and the
94
+ * service worker is registered, so this site uses web push.
95
+ */
96
+ onPrepared?: () => void;
85
97
  }
86
98
 
87
99
  export interface PushSubscribeOptions {
@@ -122,6 +134,8 @@ export class PushManager {
122
134
  private unregisterTimer: ReturnType<typeof setTimeout> | null = null;
123
135
  private readonly getDeviceId: () => string | undefined;
124
136
  private readonly onSubscribeSettled: (() => void) | null;
137
+ private readonly onPrepared: (() => void) | null;
138
+ private usedThisPage = false;
125
139
 
126
140
  constructor(
127
141
  private readonly logger: Logger,
@@ -136,6 +150,39 @@ export class PushManager {
136
150
  this.storage = options.storage || null;
137
151
  this.getDeviceId = options.getDeviceId || (() => undefined);
138
152
  this.onSubscribeSettled = options.onSubscribeSettled || null;
153
+ this.onPrepared = options.onPrepared || null;
154
+ }
155
+
156
+ /** subscribe() was called, or prepare() succeeded, on this page. */
157
+ usedOnThisPage(): boolean {
158
+ return this.usedThisPage;
159
+ }
160
+
161
+ /**
162
+ * This browser used Joryio web push on an earlier page view: the marker
163
+ * set by subscribe() / prepare(), or the state an earlier SDK version left
164
+ * (a registration, or an unsubscribe), which predates the marker.
165
+ */
166
+ usedEarlier(): boolean {
167
+ if (!this.storage) return false;
168
+ try {
169
+ return (
170
+ this.storage.get<boolean>(IN_USE_KEY) === true ||
171
+ this.storage.get(REGISTRATION_MARKER_KEY) != null ||
172
+ this.storage.get<boolean>(UNREGISTERED_KEY) === true
173
+ );
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ private markUsed(): void {
180
+ this.usedThisPage = true;
181
+ try {
182
+ this.storage?.set(IN_USE_KEY, true);
183
+ } catch {
184
+ // Storage refused: this page still knows (usedThisPage).
185
+ }
139
186
  }
140
187
 
141
188
  /**
@@ -290,6 +337,12 @@ export class PushManager {
290
337
  await navigator.serviceWorker.ready;
291
338
  this.prepared = { registration, publicKey };
292
339
  this.lastPrepareError = null;
340
+ this.markUsed();
341
+ try {
342
+ this.onPrepared?.();
343
+ } catch (error) {
344
+ this.logger.warn('Push permission report failed:', error);
345
+ }
293
346
  return true;
294
347
  } catch (err) {
295
348
  this.lastPrepareError = 'sw-failed';
@@ -311,6 +364,7 @@ export class PushManager {
311
364
  try {
312
365
  return await this.subscribeOnce(options);
313
366
  } finally {
367
+ this.markUsed();
314
368
  try {
315
369
  this.onSubscribeSettled?.();
316
370
  } catch (error) {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * resetTo(anonymousId): the rule a caller-supplied anonymous id must pass
3
+ * (BACKLOG D366). The SAME rule on all five SDKs, byte-identical - the
4
+ * backend parity suite greps the pattern and the length bounds.
5
+ *
6
+ * - 8 to 255 characters (the backend stores at most 255), letters, digits
7
+ * and `.` `_` `:` `-` only - a UUID, `jry_<uuid>`, `hp_<hex>` all pass;
8
+ * - not 24 lowercase hex characters: that is the shape of a Joryio internal
9
+ * profile id, which several server paths read as the profile itself;
10
+ * - not the user id the SDK holds now (signed in, or kept for withdrawals):
11
+ * a user id is never an anonymous id;
12
+ * - not the anonymous id the SDK holds while a user is signed in: that id is
13
+ * tied to the signed-in user's profile (identify merged it there), so the
14
+ * next person on a shared device would inherit their in-app messages,
15
+ * events, form attribution and push subscription.
16
+ *
17
+ * A refused id is logged and the call behaves exactly like reset(): a
18
+ * random anonymous id. resetTo() is a logout first - a bad id must never
19
+ * leave the previous person signed in on a shared device.
20
+ */
21
+ export const RESET_TO_ANONYMOUS_ID_PATTERN = /^[A-Za-z0-9._:-]{8,255}$/;
22
+ export const RESET_TO_INTERNAL_ID_PATTERN = /^[0-9a-f]{24}$/;
23
+
24
+ /**
25
+ * How many anonymous ids tied to a signed-in user (held when a reset() or
26
+ * resetTo() signed them out) this browser remembers, newest kept. The same
27
+ * cap on all five SDKs; wipeData() forgets them with all other data.
28
+ */
29
+ export const SIGNED_IN_ANONYMOUS_IDS_MAX = 20;
30
+ /** Storage key (under the SDK's own prefix). */
31
+ export const SIGNED_IN_ANONYMOUS_IDS_KEY = 'signed_in_anonymous_ids';
32
+
33
+ /** Append `id` (moved to the end if present), keeping the newest SIGNED_IN_ANONYMOUS_IDS_MAX. */
34
+ export function rememberSignedInAnonymousId(list: readonly string[], id: string): string[] {
35
+ return [...list.filter((x) => x !== id), id].slice(-SIGNED_IN_ANONYMOUS_IDS_MAX);
36
+ }
37
+
38
+ /** Null when `anonymousId` may be adopted, otherwise why not. */
39
+ export function resetToRefusal(
40
+ anonymousId: unknown,
41
+ knownUserIds: Array<string | null | undefined>,
42
+ signedInAnonymousId: string | null | undefined = null,
43
+ rememberedSignedInAnonymousIds: readonly string[] = [],
44
+ ): string | null {
45
+ if (typeof anonymousId !== 'string' || !RESET_TO_ANONYMOUS_ID_PATTERN.test(anonymousId)) {
46
+ return 'resetTo: the anonymous id must be 8 to 255 letters, digits, ".", "_", ":" or "-"';
47
+ }
48
+ if (RESET_TO_INTERNAL_ID_PATTERN.test(anonymousId)) {
49
+ return 'resetTo: the anonymous id has the shape of a Joryio profile id';
50
+ }
51
+ if (knownUserIds.some((u) => typeof u === 'string' && u === anonymousId)) {
52
+ return 'resetTo: the anonymous id is a user id';
53
+ }
54
+ // ...and so is one a signed-in user held before an earlier reset.
55
+ if ((typeof signedInAnonymousId === 'string' && signedInAnonymousId === anonymousId) || rememberedSignedInAnonymousIds.includes(anonymousId)) {
56
+ return 'resetTo: the anonymous id belongs to the signed-in user';
57
+ }
58
+ return null;
59
+ }
package/src/core/sdk.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  NetworkResponse,
14
14
  AttributeOps,
15
15
  SdkAuthFailureCallback,
16
+ StorefrontIdentityTokenProvider,
16
17
  utf8Length,
17
18
  } from './network';
18
19
  import { UTMManager } from './utm';
@@ -32,6 +33,8 @@ import {
32
33
  } from './write-retry';
33
34
  import { WriteOutbox, OutboxEntry, OUTBOX_KEY } from './outbox';
34
35
  import { valueProblem, withoutUnsendableValues } from './values';
36
+ import { resetToRefusal, rememberSignedInAnonymousId, SIGNED_IN_ANONYMOUS_IDS_KEY } from './reset-to';
37
+ import { consumeClickIdentityTokenFromLocation, readClickIdentityToken, withoutClickIdentityToken } from './click-identity';
35
38
 
36
39
  /**
37
40
  * The visitor's own opt-out, persisted so it survives a reload. It used to
@@ -289,6 +292,15 @@ export class JoryioSDK {
289
292
 
290
293
  private pruneTimer: ReturnType<typeof setTimeout> | null = null;
291
294
 
295
+ /**
296
+ * Click-link identity (D407): a tracked link's `jr_t`, held IN MEMORY ONLY
297
+ * until it may be sent (consent pending) - never persisted, dropped on an
298
+ * opt-out, a denial or a reset. See click-identity.ts.
299
+ */
300
+ private pendingLinkToken: string | null = null;
301
+ /** Tokens already handed to the server by this page (send once). */
302
+ private readonly sentLinkTokens = new Set<string>();
303
+
292
304
  /**
293
305
  * @param preInit - internal: privacy decisions queued before the SDK loaded
294
306
  * (see installSnippetQueue). Not part of the public API.
@@ -350,6 +362,13 @@ export class JoryioSDK {
350
362
  if (this.userOptedOut) this.optedOutAt = this.storedStamp(OPT_OUT_AT_KEY);
351
363
  this.trackingConsent = this.initialConsent(this.config.trackingConsent);
352
364
 
365
+ // Click-link identity (D407): take `jr_t` off the address bar FIRST - before
366
+ // the UTM manager records the landing page - so the token is never
367
+ // bookmarked, shared, or stored as a landing URL. Stripped whatever the
368
+ // privacy state (hygiene, not collection); used only when allowed.
369
+ const linkToken = consumeClickIdentityTokenFromLocation();
370
+ if (linkToken && !this.disabled) this.pendingLinkToken = linkToken;
371
+
353
372
  // Initialize UTM tracking (before session to check for campaign changes)
354
373
  this.utm = new UTMManager(
355
374
  this.storage,
@@ -436,6 +455,16 @@ export class JoryioSDK {
436
455
  }
437
456
  }
438
457
 
458
+ // Storefront identity token (D383): bound to the visitor id it was minted
459
+ // for, read live from identity so a reset() (new visitor) never sends it.
460
+ this.network.setAnonymousIdSource(() => this.identity.getAnonymousId());
461
+ if (this.config.storefrontIdentityTokenProvider) {
462
+ this.network.setStorefrontIdentityTokenProvider(this.config.storefrontIdentityTokenProvider);
463
+ }
464
+ if (this.config.storefrontIdentityToken) {
465
+ this.network.setStorefrontIdentityToken(this.config.storefrontIdentityToken);
466
+ }
467
+
439
468
  this.outbox = this.createOutbox();
440
469
 
441
470
  // Initialize in-app messaging. The bridge lets in-app message HTML call SDK
@@ -528,6 +557,8 @@ export class JoryioSDK {
528
557
  getDeviceId: () => this.deviceId,
529
558
  // The new permission is reported now, not on the next page load.
530
559
  onSubscribeSettled: () => this.reportPushPermissionIfChanged(),
560
+ // A primer is about to ask: the site uses web push, so report now.
561
+ onPrepared: () => this.reportPushPermissionIfChanged(),
531
562
  },
532
563
  );
533
564
 
@@ -614,7 +645,8 @@ export class JoryioSDK {
614
645
  if (!this.disabled) JoryioSDK.instance = this;
615
646
  this.logger.info('SDK initialized successfully');
616
647
 
617
- // Report permission state now the SDK is live. Only sends on a change.
648
+ // Report permission state now the SDK is live - only when this site uses
649
+ // web push (see pushPermissionReported), and only on a change.
618
650
  this.reportPushPermissionIfChanged();
619
651
 
620
652
  // Enqueue Session Start BEFORE starting the queue auto-flush timer.
@@ -695,6 +727,10 @@ export class JoryioSDK {
695
727
  // that it is allowed (D-b).
696
728
  if (!this.isOptedOut) this.releaseDeferredIdentify();
697
729
 
730
+ // A tracked link's `jr_t` (D407): now if tracking is allowed, at the
731
+ // grant if consent is pending, never if it is off.
732
+ this.flushLinkIdentity();
733
+
698
734
  // The opt-out marker, if the switch changed since the server last heard
699
735
  // (an `optOut: true` in the config or a pre-init optOut() included).
700
736
  this.syncOptOutMarker();
@@ -1337,6 +1373,8 @@ export class JoryioSDK {
1337
1373
  this.outbox.discardNonWithdrawals();
1338
1374
  this.outbox.kick();
1339
1375
  if (this.config.inApp.enabled) this.inapp.stop();
1376
+ // A tracked link's token is never sent after a refusal.
1377
+ this.pendingLinkToken = null;
1340
1378
  return;
1341
1379
  }
1342
1380
 
@@ -1370,6 +1408,67 @@ export class JoryioSDK {
1370
1408
  });
1371
1409
  }
1372
1410
  this._push.syncExistingSubscription().catch(() => undefined);
1411
+ // A tracked link's token held while consent was pending (D407).
1412
+ this.flushLinkIdentity();
1413
+ }
1414
+
1415
+ /**
1416
+ * Recognise the person who clicked a message (D407): send a tracked link's
1417
+ * `jr_t` to POST /v1/identify-link, so this anonymous visit is the
1418
+ * recipient's. Only when tracking is allowed (consent granted, not opted
1419
+ * out, Do Not Track respected) and nobody is identified here: an
1420
+ * identify()-ed user or a signed-in store customer (storefront identity
1421
+ * token) always wins over a link - the server enforces the same and also
1422
+ * keeps a browser that is already someone else as that person. Consent
1423
+ * pending: held in memory and sent at the grant. Each token once per page.
1424
+ */
1425
+ private flushLinkIdentity(): void {
1426
+ const token = this.pendingLinkToken;
1427
+ if (!token) return;
1428
+ if (this.disabled || this.isOptedOut) {
1429
+ this.pendingLinkToken = null;
1430
+ return;
1431
+ }
1432
+ if (!this.canSend()) return; // consent pending / ingestion paused: keep it for the grant
1433
+ this.pendingLinkToken = null;
1434
+ if (this.sentLinkTokens.has(token)) return;
1435
+ if (this.effectiveUserId()) {
1436
+ this.logger.debug('Link identity not sent: a user is identified on this browser');
1437
+ return;
1438
+ }
1439
+ if (this.network.hasStorefrontIdentity()) {
1440
+ this.logger.debug('Link identity not sent: a signed-in store customer is on this browser');
1441
+ return;
1442
+ }
1443
+ this.sentLinkTokens.add(token);
1444
+ this.network
1445
+ .sendIdentifyLink(this.config.apiEndpoint, { token, anonymousId: this.identity.getAnonymousId() })
1446
+ .catch((error) => this.logger.debug('Link identity request failed:', error));
1447
+ }
1448
+
1449
+ /**
1450
+ * Recognise the person who clicked a tracked link, for a page that handles
1451
+ * URLs itself (a single-page app's router, a link opened in a webview).
1452
+ * Reads `jr_t` from `url`; when `url` is the address bar's, also removes
1453
+ * the token from it. The same rules as on page load: only when tracking
1454
+ * is allowed and nobody is identified here. Does nothing without `jr_t`.
1455
+ */
1456
+ identifyFromLink(url: string): void {
1457
+ if (!this.isInitialized || this.disabled) return;
1458
+ const token = readClickIdentityToken(url);
1459
+ if (!token) return;
1460
+ try {
1461
+ if (typeof window !== 'undefined' && window.location && readClickIdentityToken(window.location.href) === token) {
1462
+ const stripped = withoutClickIdentityToken(window.location.href);
1463
+ if (stripped && window.history && typeof window.history.replaceState === 'function') {
1464
+ window.history.replaceState(window.history.state, '', stripped);
1465
+ }
1466
+ }
1467
+ } catch {
1468
+ // Hygiene only.
1469
+ }
1470
+ this.pendingLinkToken = token;
1471
+ this.flushLinkIdentity();
1373
1472
  }
1374
1473
 
1375
1474
  /** Send the attribute and profile writes held while consent was pending. */
@@ -1998,9 +2097,15 @@ export class JoryioSDK {
1998
2097
  *
1999
2098
  * Change-detection matters: attributes are not deduplicated server-side, so
2000
2099
  * reporting unconditionally would spend a request on every page load.
2100
+ *
2101
+ * And only when this site uses web push (pushPermissionReported): on a site
2102
+ * that does not, the value says nothing anyone can act on, and writing it
2103
+ * cost a request per new visitor - and, for an anonymous visitor the SDK
2104
+ * sends nothing else for, created a profile of its own.
2001
2105
  */
2002
2106
  private reportPushPermissionIfChanged(): void {
2003
2107
  if (!this.isInitialized || this.isOptedOut) return;
2108
+ if (!this.pushPermissionReported()) return;
2004
2109
  try {
2005
2110
  const state = this._push.getPermissionState();
2006
2111
  const current = state === 'notDetermined' ? 'not_determined' : state;
@@ -2016,6 +2121,23 @@ export class JoryioSDK {
2016
2121
  }
2017
2122
  }
2018
2123
 
2124
+ /**
2125
+ * Does this SDK instance use web push, so `push_permission` is reported?
2126
+ *
2127
+ * - `webPush: true` in the init config: yes.
2128
+ * - subscribe() was called, or prepare() succeeded, on this page: yes, even
2129
+ * with `webPush: false` - the page asked for push, and the answer counts.
2130
+ * - `webPush: false`: no.
2131
+ * - unset: yes once this browser has used Joryio web push (an earlier
2132
+ * subscribe() / prepare(), or a registration from an earlier version).
2133
+ */
2134
+ private pushPermissionReported(): boolean {
2135
+ if (this.config.webPush === true) return true;
2136
+ if (this._push.usedOnThisPage()) return true;
2137
+ if (this.config.webPush === false) return false;
2138
+ return this._push.usedEarlier();
2139
+ }
2140
+
2019
2141
  /**
2020
2142
  * Set a single attribute
2021
2143
  */
@@ -2153,12 +2275,66 @@ export class JoryioSDK {
2153
2275
  * on a shared device.
2154
2276
  */
2155
2277
  async reset(): Promise<void> {
2278
+ return this.resetIdentity(undefined);
2279
+ }
2280
+
2281
+ /**
2282
+ * reset(), then adopt `anonymousId` instead of a new random id (BACKLOG
2283
+ * D366). For a host that keeps its own visitor id - a store tracker, a
2284
+ * site's own analytics id - so the SDK and the host stay ONE visitor after
2285
+ * a logout, without a random id in between.
2286
+ *
2287
+ * Everything reset() does happens: the user id, attributes, in-app state,
2288
+ * the SDK-authentication and storefront tokens and the session are
2289
+ * forgotten, and the push subscription moves to the new visitor. The id
2290
+ * must be 8 to 255 letters, digits, `.`, `_`, `:` or `-`, must not have the
2291
+ * shape of a Joryio profile id (24 lowercase hex) and must not be the user
2292
+ * id this SDK holds, nor the anonymous id it holds while a user is signed
2293
+ * in (that id is tied to the signed-in user's profile); a refused id is
2294
+ * logged and the call is a plain reset() - a random id - so a logout is
2295
+ * never skipped.
2296
+ *
2297
+ * Resolves `true` when the id was adopted, `false` when it was refused (a
2298
+ * random id was used instead) or the SDK is not initialized (nothing done).
2299
+ *
2300
+ * An anonymous id is a claim, not a credential: whoever holds an anonymous
2301
+ * id that is already tied to an identified profile is treated as that
2302
+ * visitor (in-app messages, events, push), unless SDK Authentication is on
2303
+ * - then anonymous writes to an identified profile are refused (403). Adopt
2304
+ * only ids your own app issued for this browser.
2305
+ */
2306
+ async resetTo(anonymousId: string): Promise<boolean> {
2307
+ if (!this.isInitialized) {
2308
+ this.logger.error('SDK not initialized');
2309
+ return false;
2310
+ }
2311
+ const userId = this.identity.getUserId();
2312
+ const refusal = resetToRefusal(
2313
+ anonymousId,
2314
+ [userId, this.withdrawalUserId],
2315
+ userId ? this.identity.getAnonymousId() : null,
2316
+ this.signedInAnonymousIds(),
2317
+ );
2318
+ if (refusal) this.logger.error(`${refusal}; a random anonymous id is used instead`);
2319
+ await this.resetIdentity(refusal ? undefined : anonymousId);
2320
+ return !refusal;
2321
+ }
2322
+
2323
+ /** Anonymous ids tied to a signed-in user when a reset signed them out (D366). */
2324
+ private signedInAnonymousIds(): string[] {
2325
+ const stored = this.storage.get<unknown>(SIGNED_IN_ANONYMOUS_IDS_KEY);
2326
+ return Array.isArray(stored) ? stored.filter((x): x is string => typeof x === 'string') : [];
2327
+ }
2328
+
2329
+ private async resetIdentity(anonymousId: string | undefined): Promise<void> {
2156
2330
  if (!this.isInitialized) {
2157
2331
  this.logger.error('SDK not initialized');
2158
2332
  return;
2159
2333
  }
2160
2334
 
2161
2335
  this.logger.info('Resetting user identity');
2336
+ // A link token held for the outgoing visitor is not the next one's (D407).
2337
+ this.pendingLinkToken = null;
2162
2338
 
2163
2339
  // --- Synchronous: everything that decides WHO the next call is about ---
2164
2340
 
@@ -2183,12 +2359,22 @@ export class JoryioSDK {
2183
2359
  // Leftovers refused with a 401 anyway are dropped, never reported to the
2184
2360
  // host's handler.
2185
2361
  this.network.retireSdkAuthToken();
2362
+ // The store customer's storefront identity token is theirs and this
2363
+ // visitor's (D383): the next visitor never carries it. (It is bound to the
2364
+ // old anonymous id anyway; dropped so it is not even held.)
2365
+ this.network.clearStorefrontIdentityToken();
2186
2366
  // A user kept only for withdrawals (D-b) is logged out too.
2187
2367
  this.forgetDeferredIdentify();
2188
2368
 
2369
+ // The outgoing user's anonymous id is tied to their profile: a later
2370
+ // resetTo() must never hand it to someone else (D366).
2371
+ if (this.identity.getUserId()) {
2372
+ this.storage.set(SIGNED_IN_ANONYMOUS_IDS_KEY, rememberSignedInAnonymousId(this.signedInAnonymousIds(), this.identity.getAnonymousId()));
2373
+ }
2374
+
2189
2375
  // New anonymous id, no user id.
2190
2376
  this.pinAnonymousWrites();
2191
- this.identity.reset();
2377
+ this.identity.reset(anonymousId);
2192
2378
  this.network.setCurrentUserId(this.identity.getUserId());
2193
2379
 
2194
2380
  // UTM before the session: the new session's Session Start (tracked by the
@@ -2230,6 +2416,7 @@ export class JoryioSDK {
2230
2416
  return;
2231
2417
  }
2232
2418
  this.logger.info('Wiping local SDK data');
2419
+ this.pendingLinkToken = null;
2233
2420
 
2234
2421
  // Push first, while the outgoing ids are still current (it captures them).
2235
2422
  const pushWiped = this._push.forget().catch(() => undefined);
@@ -2257,6 +2444,9 @@ export class JoryioSDK {
2257
2444
  // under the ids they were made with (contract item 36).
2258
2445
  this.outbox.discardNonWithdrawals();
2259
2446
  this.storage.remove(REPORTED_PUSH_PERMISSION_KEY);
2447
+ // Local data like any other (D366): resetTo's memory of signed-in users'
2448
+ // anonymous ids goes with the wipe, the same on all five SDKs.
2449
+ this.storage.remove(SIGNED_IN_ANONYMOUS_IDS_KEY);
2260
2450
  // "No Session Start queued for any session yet" - NOT the absence of the
2261
2451
  // marker, which reads as "sent" (rule 75): a wipe while tracking was off,
2262
2452
  // then a reload and a grant, resumed the post-wipe session with no
@@ -2288,6 +2478,7 @@ export class JoryioSDK {
2288
2478
  for (const key of [OUTBOX_KEY, PENDING_UNREGISTER_KEY]) collectUserIds(this.storage.get<unknown>(key), keepTokens);
2289
2479
  this.network.retireSdkAuthToken();
2290
2480
  this.network.dropStandbySdkAuthTokens(keepTokens);
2481
+ this.network.clearStorefrontIdentityToken();
2291
2482
  this.forgetDeferredIdentify();
2292
2483
  this.pinAnonymousWrites();
2293
2484
  this.identity.reset();
@@ -2771,6 +2962,32 @@ export class JoryioSDK {
2771
2962
  this.network.setSdkAuthenticationToken(token);
2772
2963
  }
2773
2964
 
2965
+ /**
2966
+ * Storefront identity token (store plugins) - set or replace the token
2967
+ * Joryio minted for a signed-in store customer's browser (null forgets it).
2968
+ * Sent only on anonymous requests of the visitor it was minted for. See
2969
+ * the `storefrontIdentityToken` init option.
2970
+ */
2971
+ setStorefrontIdentityToken(token: string | null): void {
2972
+ if (!this.isInitialized) {
2973
+ this.logger?.error('SDK not initialized');
2974
+ return;
2975
+ }
2976
+ this.network.setStorefrontIdentityToken(token);
2977
+ }
2978
+
2979
+ /**
2980
+ * Storefront identity token - register the function asked for a fresh token
2981
+ * (before the held one expires, or when the API refused it as expired).
2982
+ */
2983
+ setStorefrontIdentityTokenProvider(provider: StorefrontIdentityTokenProvider | null): void {
2984
+ if (!this.isInitialized) {
2985
+ this.logger?.error('SDK not initialized');
2986
+ return;
2987
+ }
2988
+ this.network.setStorefrontIdentityTokenProvider(provider);
2989
+ }
2990
+
2774
2991
  /**
2775
2992
  * SDK Authentication — register a callback fired when the backend rejects the
2776
2993
  * token with a 401 `sdk_authentication_error`. The callback receives the
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ import type {
12
12
  SdkAuthFailureInfo,
13
13
  SdkAuthFailureReason,
14
14
  SdkAuthFailureCallback,
15
+ StorefrontIdentityTokenProvider,
15
16
  } from './core/network';
16
17
  import { User, SubscriptionStatus } from './core/user';
17
18
  import type { SubscriptionChannel, SubscriptionPreferences } from './core/user';
@@ -60,6 +61,7 @@ export type {
60
61
  SdkAuthFailureInfo,
61
62
  SdkAuthFailureReason,
62
63
  SdkAuthFailureCallback,
64
+ StorefrontIdentityTokenProvider,
63
65
  };
64
66
 
65
67
  // Export SDK version
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * Usage:
9
9
  * <script>
10
- * !function(){var e=window.joryio=window.joryio||[];if(!e.initialize)if(e.invoked)window.console&&console.error&&console.error("Joryio snippet included twice.");else{e.invoked=!0,e.methods=["init","track","identify","addAlias","setAttributes","setAttribute","incrementAttribute","unsetAttribute","addToArray","removeFromArray","reset","flush","optOut","optIn","updateConsent","getTrackingConsent","isUserOptedOut","setSdkAuthenticationToken","setSdkAuthenticationErrorCallback","getAnonymousId","getUserId","ready","getIdentity","getSessionInfo","getUTMData","updateUTM","syncInAppCampaigns","getInAppCampaigns","displayInAppCampaign","dismissInAppMessage","trackInAppConversion","ecommerce","wipeData","destroy"],e.keep=["init","optOut","optIn","updateConsent","wipeData"],e.factory=function(t){return function(){var n=Array.prototype.slice.call(arguments);if(n.unshift(t),e.length>=1e3)for(var i=0;i<e.length;i++)if(e.keep.indexOf(e[i][0])<0){e.splice(i,1);break}return e.push(n),/^(get|is)[A-Z]/.test(t)?void 0:e}};for(var t=0;t<e.methods.length;t++){var n=e.methods[t];e[n]=e.factory(n)}e.load=function(e){var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://sdk.joryio.com/web/1/joryio.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n)},e.load()}}();
10
+ * !function(){var e=window.joryio=window.joryio||[];if(!e.initialize)if(e.invoked)window.console&&console.error&&console.error("Joryio snippet included twice.");else{e.invoked=!0,e.methods=["init","track","identify","identifyFromLink","addAlias","setAttributes","setAttribute","incrementAttribute","unsetAttribute","addToArray","removeFromArray","reset","resetTo","flush","optOut","optIn","updateConsent","getTrackingConsent","isUserOptedOut","setSdkAuthenticationToken","setSdkAuthenticationErrorCallback","setStorefrontIdentityToken","setStorefrontIdentityTokenProvider","getAnonymousId","getUserId","ready","getIdentity","getSessionInfo","getUTMData","updateUTM","syncInAppCampaigns","getInAppCampaigns","displayInAppCampaign","dismissInAppMessage","trackInAppConversion","ecommerce","wipeData","destroy"],e.keep=["init","optOut","optIn","updateConsent","wipeData"],e.factory=function(t){return function(){var n=Array.prototype.slice.call(arguments);if(n.unshift(t),e.length>=1e3)for(var i=0;i<e.length;i++)if(e.keep.indexOf(e[i][0])<0){e.splice(i,1);break}return e.push(n),/^(get|is)[A-Z]/.test(t)?void 0:e}};for(var t=0;t<e.methods.length;t++){var n=e.methods[t];e[n]=e.factory(n)}e.load=function(e){var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://sdk.joryio.com/web/1/joryio.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n)},e.load()}}();
11
11
  * joryio.init({ sdkKey: 'YOUR_SDK_KEY' });
12
12
  * </script>
13
13
  *
@@ -49,6 +49,7 @@
49
49
  'init',
50
50
  'track',
51
51
  'identify',
52
+ 'identifyFromLink',
52
53
  'addAlias',
53
54
  'setAttributes',
54
55
  'setAttribute',
@@ -57,6 +58,7 @@
57
58
  'addToArray',
58
59
  'removeFromArray',
59
60
  'reset',
61
+ 'resetTo',
60
62
  'flush',
61
63
  'optOut',
62
64
  'optIn',
@@ -65,6 +67,8 @@
65
67
  'isUserOptedOut',
66
68
  'setSdkAuthenticationToken',
67
69
  'setSdkAuthenticationErrorCallback',
70
+ 'setStorefrontIdentityToken',
71
+ 'setStorefrontIdentityTokenProvider',
68
72
  'getAnonymousId',
69
73
  'getUserId',
70
74
  'ready',