@joryio/web-sdk 1.4.0-beta.1 → 1.4.0-beta.4

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +1 -1
  3. package/dist/cards-ui/card-feed-view.d.ts +4 -0
  4. package/dist/cards-ui/card-feed-view.d.ts.map +1 -0
  5. package/dist/cards-ui/index.d.ts +4 -0
  6. package/dist/cards-ui/index.d.ts.map +1 -0
  7. package/dist/core/cards-ui-contract.d.ts +30 -0
  8. package/dist/core/cards-ui-contract.d.ts.map +1 -0
  9. package/dist/core/cards.d.ts +130 -0
  10. package/dist/core/cards.d.ts.map +1 -0
  11. package/dist/core/config.d.ts +21 -1
  12. package/dist/core/config.d.ts.map +1 -1
  13. package/dist/core/editor-gate.d.ts +47 -0
  14. package/dist/core/editor-gate.d.ts.map +1 -0
  15. package/dist/core/flags.d.ts +73 -0
  16. package/dist/core/flags.d.ts.map +1 -0
  17. package/dist/core/inapp.d.ts +13 -1
  18. package/dist/core/inapp.d.ts.map +1 -1
  19. package/dist/core/links.d.ts +27 -0
  20. package/dist/core/links.d.ts.map +1 -0
  21. package/dist/core/network.d.ts.map +1 -1
  22. package/dist/core/page-context.d.ts +101 -0
  23. package/dist/core/page-context.d.ts.map +1 -0
  24. package/dist/core/page-edits.d.ts +129 -0
  25. package/dist/core/page-edits.d.ts.map +1 -0
  26. package/dist/core/placements.d.ts +218 -0
  27. package/dist/core/placements.d.ts.map +1 -0
  28. package/dist/core/sdk-host-files.d.ts +5 -0
  29. package/dist/core/sdk-host-files.d.ts.map +1 -0
  30. package/dist/core/sdk.d.ts +36 -0
  31. package/dist/core/sdk.d.ts.map +1 -1
  32. package/dist/editor/index.d.ts +4 -0
  33. package/dist/editor/index.d.ts.map +1 -0
  34. package/dist/editor/visual-editor.d.ts +39 -0
  35. package/dist/editor/visual-editor.d.ts.map +1 -0
  36. package/dist/index.d.mts +201 -3
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/joryio-cards-ui.min.js +7 -0
  40. package/dist/joryio-cards-ui.min.js.map +1 -0
  41. package/dist/joryio-editor.min.js +7 -0
  42. package/dist/joryio-editor.min.js.map +1 -0
  43. package/dist/joryio-sw.js +1 -1
  44. package/dist/joryio.cjs.js +7200 -3513
  45. package/dist/joryio.min.js +2 -2
  46. package/dist/joryio.min.js.map +1 -1
  47. package/dist/joryio.mjs +7192 -3514
  48. package/dist/joryio.umd.js +7200 -3513
  49. package/package.json +4 -1
  50. package/src/cards-ui/card-feed-view.ts +249 -0
  51. package/src/cards-ui/index.ts +26 -0
  52. package/src/core/cards-ui-contract.ts +58 -0
  53. package/src/core/cards.ts +843 -0
  54. package/src/core/config.ts +86 -2
  55. package/src/core/editor-gate.ts +158 -0
  56. package/src/core/flags.ts +372 -0
  57. package/src/core/inapp.ts +283 -152
  58. package/src/core/links.ts +104 -0
  59. package/src/core/network.ts +5 -2
  60. package/src/core/page-context.ts +460 -0
  61. package/src/core/page-edits.ts +1036 -0
  62. package/src/core/placements.ts +1431 -0
  63. package/src/core/sdk-host-files.ts +93 -0
  64. package/src/core/sdk.ts +378 -1
  65. package/src/editor/index.ts +27 -0
  66. package/src/editor/visual-editor.ts +301 -0
  67. package/src/index.ts +33 -0
  68. package/src/snippet/loader.js +25 -1
package/src/core/inapp.ts CHANGED
@@ -3,10 +3,22 @@
3
3
  * Handles in-app message campaigns, display, and tracking
4
4
  */
5
5
 
6
+ import {
7
+ hasPageTargeting,
8
+ isPageTrigger,
9
+ PAGE_CONTEXT_CAPABILITY,
10
+ pageTargetingMatches,
11
+ pageTriggerMet,
12
+ type PageContextTracker,
13
+ type PageSignal,
14
+ type PageTargeting,
15
+ } from './page-context';
6
16
  import { Logger } from '../utils/logger';
7
17
  import type { InAppDisplayOptions } from './config';
18
+ import { sdkIdentityHeaders } from './config';
8
19
  import { IdentityManager } from './identity';
9
20
  import { SessionManager } from './session';
21
+ import type { LinkRouter } from './links';
10
22
  import { StorageManager } from './storage';
11
23
  import { SdkAuthFailureInfo } from './network';
12
24
 
@@ -142,6 +154,12 @@ export interface InAppCampaign {
142
154
  */
143
155
  reevaluateBeforeDisplay?: boolean;
144
156
  watchedAttributes?: string[];
157
+ /**
158
+ * The pages it may show on (D444 Phase 4, page-context.ts). Checked on THIS
159
+ * device before every display and on every route change; the server sends
160
+ * such a campaign only to an SDK that declares `page_context`.
161
+ */
162
+ pageTargeting?: PageTargeting;
145
163
  }
146
164
 
147
165
  export interface InAppTrigger {
@@ -157,7 +175,12 @@ export interface InAppTrigger {
157
175
  | 'event'
158
176
  | 'attribute_change'
159
177
  | 'attribute_threshold'
160
- | 'push_notification_tap';
178
+ | 'push_notification_tap'
179
+ // Page triggers (D444 Phase 4, page-context.ts): fired by this SDK only.
180
+ | 'page_view'
181
+ | 'exit_intent'
182
+ | 'scroll_depth'
183
+ | 'time_on_page';
161
184
  event?: string;
162
185
  attribute?: string;
163
186
  operator?: string;
@@ -417,6 +440,8 @@ export function cssValue(raw: unknown): string | null {
417
440
  }
418
441
 
419
442
  export class InAppMessagingManager {
443
+ /** The SDK's link router (`setLinkHandler`); set by the SDK after construction. */
444
+ links: LinkRouter | null = null;
420
445
  /** Messages waiting out a display delay, so they can be cancelled. */
421
446
  private pendingDelays = new Map<string, ReturnType<typeof setTimeout>>();
422
447
 
@@ -505,11 +530,56 @@ export class InAppMessagingManager {
505
530
  * needs to be told before someone publishes into silence.
506
531
  */
507
532
  private capabilities(): string[] {
508
- const caps = ['content.native'];
533
+ // `placements` + `content.data`: this build draws placements and hands
534
+ // their data to the app (placements.ts) - the same words every SDK sends.
535
+ const caps = ['content.native', 'placements', 'content.data'];
509
536
  if (this.allowHtmlJsInAppMessages) caps.push('content.html');
537
+ // `page_context`: this build checks a campaign's page rules and fires page triggers.
538
+ if (this.page) caps.push(PAGE_CONTEXT_CAPABILITY);
510
539
  return caps;
511
540
  }
512
541
 
542
+ private page: PageContextTracker | null = null;
543
+ private pageUnsubscribe: (() => void) | null = null;
544
+ /** Campaigns a page trigger already fired on THIS page (cleared on a route change). */
545
+ private pageFired = new Set<string>();
546
+
547
+ /**
548
+ * Page context (D444 Phase 4): page rules are checked before every display,
549
+ * page triggers fire held campaigns, and a route change re-checks the
550
+ * campaigns that wait for a page.
551
+ */
552
+ setPageContext(tracker: PageContextTracker | null): void {
553
+ this.pageUnsubscribe?.();
554
+ this.pageUnsubscribe = null;
555
+ this.page = tracker;
556
+ if (tracker) this.pageUnsubscribe = tracker.onSignal((signal) => this.onPageSignal(signal));
557
+ }
558
+
559
+ /** Whether the current page allows this campaign. No rules = yes; rules and no page tracker = no. */
560
+ private pageAllows(campaign: InAppCampaign): boolean {
561
+ if (!hasPageTargeting(campaign.pageTargeting)) return true;
562
+ return !!this.page && pageTargetingMatches(campaign.pageTargeting, this.page.current());
563
+ }
564
+
565
+ private onPageSignal(signal: PageSignal): void {
566
+ if (!this.page) return;
567
+ if (signal.type === 'page_change') this.pageFired.clear();
568
+ const progress = this.page.progress();
569
+ for (const campaign of this.campaigns.values()) {
570
+ const triggers = campaign.triggers || [];
571
+ const pageTrigger = triggers.find((t) => isPageTrigger(t) && pageTriggerMet(t, signal, progress));
572
+ // A campaign that shows "immediately" but only on some pages shows on
573
+ // arriving at one of them.
574
+ const arrives = signal.type === 'page_change' && hasPageTargeting(campaign.pageTargeting) && triggers.some((t) => t.type === 'immediate');
575
+ if (!pageTrigger && !arrives) continue;
576
+ if (this.pageFired.has(campaign.id)) continue;
577
+ if (!this.pageAllows(campaign)) continue;
578
+ this.pageFired.add(campaign.id);
579
+ this.displayCampaign(campaign).catch((error) => this.logger.error('In-app display failed:', error));
580
+ }
581
+ }
582
+
513
583
  /**
514
584
  * Run a host-app callback. A callback that throws must never stop the SDK's
515
585
  * own bookkeeping (the dismissal, the impression, the cleanup) - contract
@@ -843,11 +913,23 @@ export class InAppMessagingManager {
843
913
  // the TOP origin). Rejects javascript:/data:/mailto:/tel: and protocol-
844
914
  // relative `//host` (open-redirect) — those aren't routed here.
845
915
  if (!/^(https?:\/\/|\/(?!\/))/i.test(url)) return;
846
- if (target === '_top' || target === '_self') {
847
- if (window.top) window.top.location.href = url;
848
- } else {
849
- window.open(url, '_blank', 'noopener');
916
+ const go = () => {
917
+ if (target === '_top' || target === '_self') {
918
+ if (window.top) window.top.location.href = url;
919
+ } else {
920
+ window.open(url, '_blank', 'noopener');
921
+ }
922
+ };
923
+ // The site-wide link handler (setLinkHandler) sees it first, a
924
+ // root-relative link resolved against the page.
925
+ if (!this.links) return go();
926
+ let absolute = url;
927
+ try {
928
+ absolute = new URL(url, window.location.href).href;
929
+ } catch {
930
+ // Unparseable: the handler gets it as written.
850
931
  }
932
+ this.links.route(absolute, 'in_app', { campaignId }, go);
851
933
  },
852
934
  closeMessage: (campaignId: string) => {
853
935
  if (!this.displayedMessages.has(campaignId)) return;
@@ -1041,6 +1123,7 @@ export class InAppMessagingManager {
1041
1123
  headers: {
1042
1124
  'Content-Type': 'application/json',
1043
1125
  'X-SDK-Key': this.sdkKey,
1126
+ ...sdkIdentityHeaders(),
1044
1127
  ...(this.auth?.getSdkAuthHeaders(subjectUser, subjectUser ? null : this.identity.getAnonymousId()) || {}),
1045
1128
  },
1046
1129
  body: JSON.stringify({
@@ -1140,7 +1223,8 @@ export class InAppMessagingManager {
1140
1223
  private processImmediateTriggers(): void {
1141
1224
  for (const campaign of this.campaigns.values()) {
1142
1225
  const triggers = campaign.triggers || [];
1143
- const hasImmediateTrigger = triggers.some((t) => t.type === 'immediate');
1226
+ // `page_view` (D444 Phase 4) counts the page the sync arrived on as viewed.
1227
+ const hasImmediateTrigger = triggers.some((t) => t.type === 'immediate' || (t.type === 'page_view' && !!this.page));
1144
1228
  if (hasImmediateTrigger) {
1145
1229
  this.displayCampaign(campaign).catch((error) =>
1146
1230
  this.logger.error('In-app display failed:', error));
@@ -1190,32 +1274,10 @@ export class InAppMessagingManager {
1190
1274
  * typo look like it worked.
1191
1275
  */
1192
1276
  private triggerFilterMatches(trigger: InAppTrigger, properties?: Record<string, any>): boolean {
1193
- if (!trigger.attribute) return true;
1194
- const actual = properties?.[trigger.attribute];
1195
- const expected = trigger.value;
1196
- switch (trigger.operator) {
1197
- case undefined:
1198
- case 'equals':
1199
- case 'eq':
1200
- return actual === expected;
1201
- case 'not_equals':
1202
- case 'neq':
1203
- return actual !== expected;
1204
- case 'greater_than':
1205
- case 'gt':
1206
- return Number(actual) > Number(expected);
1207
- case 'less_than':
1208
- case 'lt':
1209
- return Number(actual) < Number(expected);
1210
- case 'contains':
1211
- return String(actual ?? '').includes(String(expected));
1212
- case 'exists':
1213
- return actual !== undefined && actual !== null;
1214
- default:
1215
- return false;
1216
- }
1277
+ return inAppTriggerFilterMatches(trigger, properties);
1217
1278
  }
1218
1279
 
1280
+
1219
1281
  /**
1220
1282
  * Fetch a re-check campaign's content, re-verifying eligibility server-side.
1221
1283
  *
@@ -1235,6 +1297,7 @@ export class InAppMessagingManager {
1235
1297
  headers: {
1236
1298
  'Content-Type': 'application/json',
1237
1299
  'X-SDK-Key': this.sdkKey,
1300
+ ...sdkIdentityHeaders(),
1238
1301
  ...(this.auth?.getSdkAuthHeaders(this.identity.getUserId(), this.identity.getUserId() ? null : this.identity.getAnonymousId()) || {}),
1239
1302
  },
1240
1303
  body: JSON.stringify({
@@ -1244,6 +1307,9 @@ export class InAppMessagingManager {
1244
1307
  userAttributes: this.identity.getAttributes(),
1245
1308
  pendingAttributes: this.identity.pending.pending(this.identity.getAnonymousId()),
1246
1309
  deviceType: 'web',
1310
+ // The page decides on the server for a re-check (D444 Phase 4).
1311
+ capabilities: this.capabilities(),
1312
+ ...(this.page ? { context: this.page.current() } : {}),
1247
1313
  }),
1248
1314
  signal: controller.signal,
1249
1315
  });
@@ -1285,6 +1351,11 @@ export class InAppMessagingManager {
1285
1351
  // in one burst (an event fired twice, a re-sync's immediate trigger) both
1286
1352
  // passed it and the message appeared - and was counted - twice.
1287
1353
  const id = campaign.id;
1354
+ // Page rules (D444 Phase 4): not on this page - nothing claimed, nothing counted.
1355
+ if (!this.pageAllows(campaign)) {
1356
+ this.logger.debug(`Campaign ${id} not for this page`);
1357
+ return;
1358
+ }
1288
1359
  if (this.claimed.has(id) || this.displayedMessages.has(id) || this.pendingDelays.has(id)) {
1289
1360
  this.logger.debug(`Campaign ${id} already displayed, scheduled or being prepared`);
1290
1361
  return;
@@ -1912,11 +1983,18 @@ export class InAppMessagingManager {
1912
1983
  // the wrong branch in the first place - and a stored `dismiss`
1913
1984
  // button that still carries a stale url would open it.
1914
1985
  (b.action === 'url' || b.action === 'deep_link') &&
1915
- b.url &&
1916
- /^https?:\/\//i.test(b.url)
1986
+ b.url
1917
1987
  ) {
1918
- // http(s) only - same rule as every other renderer.
1919
- window.open(b.url, '_blank', 'noopener');
1988
+ // http(s) opens - same rule as every other renderer - and an
1989
+ // app deep link only reaches the site-wide link handler
1990
+ // (setLinkHandler), which sees every link first. Anything else
1991
+ // (javascript:, data:, ...) is refused before it.
1992
+ const url = b.url;
1993
+ const open = () => {
1994
+ if (/^https?:\/\//i.test(url)) window.open(url, '_blank', 'noopener');
1995
+ };
1996
+ if (this.links) this.links.route(url, 'in_app', { campaignId: campaign.id }, open);
1997
+ else open();
1920
1998
  }
1921
1999
  // EVERY button dismisses, and an unknown action was already decoded
1922
2000
  // to dismiss server-side, so a future action type cannot leave a
@@ -2173,123 +2251,7 @@ export class InAppMessagingManager {
2173
2251
  css: string,
2174
2252
  type: InAppCampaign['type'],
2175
2253
  ): string {
2176
- const cid = JSON.stringify(campaignId);
2177
- const key = JSON.stringify(HOST_BRIDGE_KEY);
2178
- // Content-sized types: the HOST picks the width (min(maxWidth, viewport -
2179
- // margin)) and only the height follows the content. The body used to be
2180
- // inline-block so its width could be measured and the frame set to it -
2181
- // which let the frame start narrow and stay narrow. Now the body is a
2182
- // normal block at the frame's width; flow-root keeps the first and last
2183
- // child's margins inside it, so its height is the content's height.
2184
- // That height is measured from the BODY: the root's scrollHeight is never
2185
- // less than the frame itself, so a message that got shorter (wider
2186
- // viewport, a form message replaced by a line) could never shrink back.
2187
- const contentSized = type === 'modal' || type === 'slideup';
2188
- const bodySizing = contentSized ? 'body{display:flow-root;}' : '';
2189
- const bootstrap = `(function(){
2190
- var CID=${cid},KEY=${key},SIZED=${contentSized ? 'true' : 'false'};
2191
- // Per-device visibility: tag the root with the REAL device class from the
2192
- // HOST page viewport (the iframe is message-sized, so its own innerWidth is
2193
- // useless here). The jr-vp-* → jr-hide-* rules in <style> then hide elements
2194
- // the dashboard marked "Mobile only" / "Desktop only". <=480 = mobile.
2195
- try{var __vp=0;try{__vp=window.parent.innerWidth||0;}catch(e){}if(!__vp)__vp=window.innerWidth||0;document.documentElement.className+=(__vp<=480?' jr-vp-mobile':' jr-vp-desktop');}catch(e){}
2196
- function host(){try{return window.parent[KEY]||null;}catch(e){return null;}}
2197
- function call(m,args){var b=host();if(b&&typeof b[m]==='function'){try{return b[m].apply(b,[CID].concat(args||[]));}catch(e){}}}
2198
- window.joryioBridge={
2199
- logCustomEvent:function(name,props){call('logCustomEvent',[name,props]);},
2200
- setCustomUserAttribute:function(k,v){call('setCustomUserAttribute',[k,v]);},
2201
- changeUser:function(uid){call('changeUser',[uid]);},
2202
- requestPushPermission:function(){call('requestPushPermission',[]);},
2203
- logConversion:function(ev){call('logConversion',[ev||'in_app_conversion']);},
2204
- submitForm:function(values){return call('submitForm',[values]);},
2205
- logClick:function(action){call('logClick',[action]);},
2206
- navigate:function(url,target){call('navigate',[url,target]);},
2207
- closeMessage:function(){call('closeMessage',[]);}
2208
- };
2209
- document.addEventListener('click',function(e){
2210
- var el=e.target;
2211
- while(el&&el!==document.body&&el!==document.documentElement){
2212
- var action=el.getAttribute&&el.getAttribute('data-joryio-action');
2213
- if(action&&typeof window.joryioBridge[action]==='function'){e.preventDefault();window.joryioBridge[action](el.getAttribute('data-joryio-event')||undefined);return;}
2214
- var tag=el.tagName;
2215
- if(tag==='A'||tag==='BUTTON'){
2216
- var da=el.getAttribute('data-action');
2217
- var href=tag==='A'?el.getAttribute('href'):null;
2218
- window.joryioBridge.logClick(da||(href?'link_click':'cta_click'));
2219
- // Route only http(s)/root-relative links through the host (top-nav,
2220
- // since the sandbox can't navigate the top page itself). Leave
2221
- // #anchors, mailto:, tel:, sms: to the browser. Any other link
2222
- // would navigate THIS frame away from the message: cancelled (rule 57).
2223
- if(href&&/^(https?:\\/\\/|\\/(?!\\/))/i.test(href)){e.preventDefault();window.joryioBridge.navigate(href,el.getAttribute('target'));}
2224
- else if(href&&!/^(#|mailto:|tel:|sms:)/i.test(href)){e.preventDefault();}
2225
- return;
2226
- }
2227
- el=el.parentNode;
2228
- }
2229
- },true);
2230
- // Forms (data-jry-form): serialize, hand the values to the host, show the
2231
- // answer in place. A redirect goes through navigate (the sandbox cannot).
2232
- document.addEventListener('submit',function(ev){var f=ev.target;if(!(f&&f.tagName==='FORM'&&f.hasAttribute('data-jry-form')))return;ev.preventDefault();if(f.getAttribute('data-jry-busy'))return;
2233
- var d={},els=f.querySelectorAll('input,select,textarea');for(var i=0;i<els.length;i++){var el=els[i],n=el.name;if(!n||el.disabled)continue;if(el.type==='checkbox'){if(!el.checked)continue;if(d[n]===undefined)d[n]=[];d[n].push(el.value||'on')}else if(el.type==='radio'){if(el.checked)d[n]=el.value}else d[n]=el.value}
2234
- function msg(text,ok){var b=f.querySelector('[data-jry-message]');if(!b){b=document.createElement('div');b.setAttribute('data-jry-message','');b.setAttribute('role','status');f.appendChild(b)}b.textContent=text;b.className=ok?'jry-form-success':'jry-form-error';reportSize()}
2235
- f.setAttribute('data-jry-busy','1');var btn=f.querySelector('button[type="submit"],input[type="submit"]');if(btn)btn.disabled=true;
2236
- var p=window.joryioBridge.submitForm(d);if(!p||typeof p.then!=='function'){msg('This form cannot be sent here.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false;return}
2237
- p.then(function(r){if(r&&r.ok){if(r.redirect){window.joryioBridge.navigate(r.redirect,'_top');return}var els2=f.querySelectorAll('input,select,textarea,button');for(var j=0;j<els2.length;j++){els2[j].disabled=true}msg(r.message||'Thank you.',true)}else{msg((r&&(r.message||(r.errors&&r.errors[0])))||'Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false}}).catch(function(){msg('Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false});
2238
- },true);
2239
- function reportSize(){try{var b=document.body,de=document.documentElement;var w=Math.max(b?b.scrollWidth:0,de.scrollWidth);var h=SIZED&&b?Math.ceil(Math.max(b.scrollHeight,b.getBoundingClientRect?b.getBoundingClientRect().height:0)):Math.max(b?b.scrollHeight:0,de.scrollHeight);call('setSize',[w,h]);}catch(e){}}
2240
- if(document.readyState!=='loading')reportSize();else document.addEventListener('DOMContentLoaded',reportSize);
2241
- window.addEventListener('load',reportSize);
2242
- try{if(window.ResizeObserver&&document.body){new ResizeObserver(reportSize).observe(document.body);}}catch(e){}
2243
- })();`;
2244
- // Per-device visibility rules (kept in sync with the editor's
2245
- // inAppEditorPanels.VISIBILITY_RULES_CSS). The bootstrap above sets the
2246
- // jr-vp-* root class from the real device.
2247
- const visRules =
2248
- '.jr-vp-mobile .jr-hide-mobile{display:none!important}.jr-vp-desktop .jr-hide-desktop{display:none!important}';
2249
- /*
2250
- * A per-document CSP, and the nonce is the point.
2251
- *
2252
- * The server keeps the author's markup as written (sanitizeInAppHtml drops
2253
- * only <base> and meta refresh), so author <script> blocks and on*
2254
- * handlers ARE in this document. Because this iframe is `allow-scripts
2255
- * allow-same-origin`, they would run at the HOST PAGE'S ORIGIN - XSS on a
2256
- * customer's site, reachable from a compromised marketing account.
2257
- *
2258
- * `script-src 'nonce-...'` is the control: only the bootstrap below carries
2259
- * the nonce, so nothing the author wrote executes. There is no server
2260
- * sanitiser in front of it; this CSP is the first line, not a backstop.
2261
- *
2262
- * The rest is least-privilege for content that is only ever a message:
2263
- * default-src 'none' nothing is allowed unless named below
2264
- * style-src unsafe-inline author style="" attributes are kept, so this
2265
- * must stay permissive; styles cannot execute
2266
- * img/media/font https: data: no http subresources - the mixed-content
2267
- * control Android enforced and iOS could not
2268
- * upgrade-insecure-requests an author's http image is upgraded rather
2269
- * than simply broken, so it still has a chance to load
2270
- * connect-src 'none' the bridge is a same-origin property call, not a
2271
- * fetch, so nothing legitimate needs the network
2272
- */
2273
- const nonce = randomNonce();
2274
- const csp = [
2275
- "default-src 'none'",
2276
- `script-src 'nonce-${nonce}'`,
2277
- "style-src 'unsafe-inline'",
2278
- 'img-src https: data:',
2279
- 'media-src https: data:',
2280
- 'font-src https: data:',
2281
- "connect-src 'none'",
2282
- "form-action 'none'",
2283
- "base-uri 'none'",
2284
- 'upgrade-insecure-requests',
2285
- ].join('; ');
2286
-
2287
- // The author's CSS goes inside <style>: a `</style>` in it would end the
2288
- // sheet and inject markup (a meta refresh, a form) into the message
2289
- // document. `</` is written `<\/` - the same characters to the CSS parser,
2290
- // never an end tag to the HTML parser (rule 57).
2291
- css = escapeStyleText(css);
2292
- return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><meta name="viewport" content="width=device-width, initial-scale=1"><style>html,body{margin:0;padding:0;}img,video{max-width:100%;height:auto;}${bodySizing}${visRules}${css}</style></head><body>${html}<script nonce="${nonce}">${bootstrap}</script></body></html>`;
2254
+ return buildInAppSrcdoc(campaignId, html, css, type);
2293
2255
  }
2294
2256
 
2295
2257
  /**
@@ -2424,6 +2386,7 @@ export class InAppMessagingManager {
2424
2386
  headers: {
2425
2387
  'Content-Type': 'application/json',
2426
2388
  'X-SDK-Key': this.sdkKey,
2389
+ ...sdkIdentityHeaders(),
2427
2390
  ...(this.auth?.getSdkAuthHeaders(subjectUser, subjectUser ? null : this.identity.getAnonymousId()) || {}),
2428
2391
  },
2429
2392
  body: JSON.stringify({
@@ -2531,6 +2494,7 @@ export class InAppMessagingManager {
2531
2494
  headers: {
2532
2495
  'Content-Type': 'application/json',
2533
2496
  'X-SDK-Key': this.sdkKey,
2497
+ ...sdkIdentityHeaders(),
2534
2498
  ...(this.auth?.getSdkAuthHeaders(subjectUser, subjectUser ? null : data.anonymousId ?? null) || {}),
2535
2499
  },
2536
2500
  body: JSON.stringify(data),
@@ -2799,6 +2763,8 @@ export class InAppMessagingManager {
2799
2763
  * Destroy in-app messaging
2800
2764
  */
2801
2765
  destroy(): void {
2766
+ this.pageUnsubscribe?.();
2767
+ this.pageUnsubscribe = null;
2802
2768
  this.logger.info('Destroying in-app messaging');
2803
2769
 
2804
2770
  // Every timer, including display delays and the sync retry, which used
@@ -2830,3 +2796,168 @@ export class InAppMessagingManager {
2830
2796
  }
2831
2797
  }
2832
2798
  }
2799
+
2800
+ /**
2801
+ * The srcdoc of a sandboxed in-app content frame. `bridgeKey` names the host
2802
+ * window object the frame calls into: the overlay manager's
2803
+ * (HOST_BRIDGE_KEY) or the placements manager's (placements.ts). One builder,
2804
+ * so the nonce CSP and the bootstrap cannot drift between the two surfaces.
2805
+ */
2806
+ export function buildInAppSrcdoc(
2807
+ campaignId: string,
2808
+ html: string,
2809
+ css: string,
2810
+ type: InAppCampaign['type'] | 'placement',
2811
+ bridgeKey: string = HOST_BRIDGE_KEY,
2812
+ ): string {
2813
+ const cid = JSON.stringify(campaignId);
2814
+ const key = JSON.stringify(bridgeKey);
2815
+ // Content-sized types: the HOST picks the width (min(maxWidth, viewport -
2816
+ // margin)) and only the height follows the content. The body used to be
2817
+ // inline-block so its width could be measured and the frame set to it -
2818
+ // which let the frame start narrow and stay narrow. Now the body is a
2819
+ // normal block at the frame's width; flow-root keeps the first and last
2820
+ // child's margins inside it, so its height is the content's height.
2821
+ // That height is measured from the BODY: the root's scrollHeight is never
2822
+ // less than the frame itself, so a message that got shorter (wider
2823
+ // viewport, a form message replaced by a line) could never shrink back.
2824
+ const contentSized = type === 'modal' || type === 'slideup' || type === 'placement';
2825
+ const bodySizing = contentSized ? 'body{display:flow-root;}' : '';
2826
+ const bootstrap = `(function(){
2827
+ var CID=${cid},KEY=${key},SIZED=${contentSized ? 'true' : 'false'};
2828
+ // Per-device visibility: tag the root with the REAL device class from the
2829
+ // HOST page viewport (the iframe is message-sized, so its own innerWidth is
2830
+ // useless here). The jr-vp-* → jr-hide-* rules in <style> then hide elements
2831
+ // the dashboard marked "Mobile only" / "Desktop only". <=480 = mobile.
2832
+ try{var __vp=0;try{__vp=window.parent.innerWidth||0;}catch(e){}if(!__vp)__vp=window.innerWidth||0;document.documentElement.className+=(__vp<=480?' jr-vp-mobile':' jr-vp-desktop');}catch(e){}
2833
+ function host(){try{return window.parent[KEY]||null;}catch(e){return null;}}
2834
+ function call(m,args){var b=host();if(b&&typeof b[m]==='function'){try{return b[m].apply(b,[CID].concat(args||[]));}catch(e){}}}
2835
+ window.joryioBridge={
2836
+ logCustomEvent:function(name,props){call('logCustomEvent',[name,props]);},
2837
+ setCustomUserAttribute:function(k,v){call('setCustomUserAttribute',[k,v]);},
2838
+ changeUser:function(uid){call('changeUser',[uid]);},
2839
+ requestPushPermission:function(){call('requestPushPermission',[]);},
2840
+ logConversion:function(ev){call('logConversion',[ev||'in_app_conversion']);},
2841
+ submitForm:function(values){return call('submitForm',[values]);},
2842
+ logClick:function(action){call('logClick',[action]);},
2843
+ navigate:function(url,target){call('navigate',[url,target]);},
2844
+ closeMessage:function(){call('closeMessage',[]);}
2845
+ };
2846
+ document.addEventListener('click',function(e){
2847
+ var el=e.target;
2848
+ while(el&&el!==document.body&&el!==document.documentElement){
2849
+ var action=el.getAttribute&&el.getAttribute('data-joryio-action');
2850
+ if(action&&typeof window.joryioBridge[action]==='function'){e.preventDefault();window.joryioBridge[action](el.getAttribute('data-joryio-event')||undefined);return;}
2851
+ var tag=el.tagName;
2852
+ if(tag==='A'||tag==='BUTTON'){
2853
+ var da=el.getAttribute('data-action');
2854
+ var href=tag==='A'?el.getAttribute('href'):null;
2855
+ window.joryioBridge.logClick(da||(href?'link_click':'cta_click'));
2856
+ // Route only http(s)/root-relative links through the host (top-nav,
2857
+ // since the sandbox can't navigate the top page itself). Leave
2858
+ // #anchors, mailto:, tel:, sms: to the browser. Any other link
2859
+ // would navigate THIS frame away from the message: cancelled (rule 57).
2860
+ if(href&&/^(https?:\\/\\/|\\/(?!\\/))/i.test(href)){e.preventDefault();window.joryioBridge.navigate(href,el.getAttribute('target'));}
2861
+ else if(href&&!/^(#|mailto:|tel:|sms:)/i.test(href)){e.preventDefault();}
2862
+ return;
2863
+ }
2864
+ el=el.parentNode;
2865
+ }
2866
+ },true);
2867
+ // Forms (data-jry-form): serialize, hand the values to the host, show the
2868
+ // answer in place. A redirect goes through navigate (the sandbox cannot).
2869
+ document.addEventListener('submit',function(ev){var f=ev.target;if(!(f&&f.tagName==='FORM'&&f.hasAttribute('data-jry-form')))return;ev.preventDefault();if(f.getAttribute('data-jry-busy'))return;
2870
+ var d={},els=f.querySelectorAll('input,select,textarea');for(var i=0;i<els.length;i++){var el=els[i],n=el.name;if(!n||el.disabled)continue;if(el.type==='checkbox'){if(!el.checked)continue;if(d[n]===undefined)d[n]=[];d[n].push(el.value||'on')}else if(el.type==='radio'){if(el.checked)d[n]=el.value}else d[n]=el.value}
2871
+ function msg(text,ok){var b=f.querySelector('[data-jry-message]');if(!b){b=document.createElement('div');b.setAttribute('data-jry-message','');b.setAttribute('role','status');f.appendChild(b)}b.textContent=text;b.className=ok?'jry-form-success':'jry-form-error';reportSize()}
2872
+ f.setAttribute('data-jry-busy','1');var btn=f.querySelector('button[type="submit"],input[type="submit"]');if(btn)btn.disabled=true;
2873
+ var p=window.joryioBridge.submitForm(d);if(!p||typeof p.then!=='function'){msg('This form cannot be sent here.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false;return}
2874
+ p.then(function(r){if(r&&r.ok){if(r.redirect){window.joryioBridge.navigate(r.redirect,'_top');return}var els2=f.querySelectorAll('input,select,textarea,button');for(var j=0;j<els2.length;j++){els2[j].disabled=true}msg(r.message||'Thank you.',true)}else{msg((r&&(r.message||(r.errors&&r.errors[0])))||'Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false}}).catch(function(){msg('Something went wrong. Please try again.',false);f.removeAttribute('data-jry-busy');if(btn)btn.disabled=false});
2875
+ },true);
2876
+ function reportSize(){try{var b=document.body,de=document.documentElement;var w=Math.max(b?b.scrollWidth:0,de.scrollWidth);var h=SIZED&&b?Math.ceil(Math.max(b.scrollHeight,b.getBoundingClientRect?b.getBoundingClientRect().height:0)):Math.max(b?b.scrollHeight:0,de.scrollHeight);call('setSize',[w,h]);}catch(e){}}
2877
+ if(document.readyState!=='loading')reportSize();else document.addEventListener('DOMContentLoaded',reportSize);
2878
+ window.addEventListener('load',reportSize);
2879
+ try{if(window.ResizeObserver&&document.body){new ResizeObserver(reportSize).observe(document.body);}}catch(e){}
2880
+ })();`;
2881
+ // Per-device visibility rules (kept in sync with the editor's
2882
+ // inAppEditorPanels.VISIBILITY_RULES_CSS). The bootstrap above sets the
2883
+ // jr-vp-* root class from the real device.
2884
+ const visRules =
2885
+ '.jr-vp-mobile .jr-hide-mobile{display:none!important}.jr-vp-desktop .jr-hide-desktop{display:none!important}';
2886
+ /*
2887
+ * A per-document CSP, and the nonce is the point.
2888
+ *
2889
+ * The server keeps the author's markup as written (sanitizeInAppHtml drops
2890
+ * only <base> and meta refresh), so author <script> blocks and on*
2891
+ * handlers ARE in this document. Because this iframe is `allow-scripts
2892
+ * allow-same-origin`, they would run at the HOST PAGE'S ORIGIN - XSS on a
2893
+ * customer's site, reachable from a compromised marketing account.
2894
+ *
2895
+ * `script-src 'nonce-...'` is the control: only the bootstrap below carries
2896
+ * the nonce, so nothing the author wrote executes. There is no server
2897
+ * sanitiser in front of it; this CSP is the first line, not a backstop.
2898
+ *
2899
+ * The rest is least-privilege for content that is only ever a message:
2900
+ * default-src 'none' nothing is allowed unless named below
2901
+ * style-src unsafe-inline author style="" attributes are kept, so this
2902
+ * must stay permissive; styles cannot execute
2903
+ * img/media/font https: data: no http subresources - the mixed-content
2904
+ * control Android enforced and iOS could not
2905
+ * upgrade-insecure-requests an author's http image is upgraded rather
2906
+ * than simply broken, so it still has a chance to load
2907
+ * connect-src 'none' the bridge is a same-origin property call, not a
2908
+ * fetch, so nothing legitimate needs the network
2909
+ */
2910
+ const nonce = randomNonce();
2911
+ const csp = [
2912
+ "default-src 'none'",
2913
+ `script-src 'nonce-${nonce}'`,
2914
+ "style-src 'unsafe-inline'",
2915
+ 'img-src https: data:',
2916
+ 'media-src https: data:',
2917
+ 'font-src https: data:',
2918
+ "connect-src 'none'",
2919
+ "form-action 'none'",
2920
+ "base-uri 'none'",
2921
+ 'upgrade-insecure-requests',
2922
+ ].join('; ');
2923
+
2924
+ // The author's CSS goes inside <style>: a `</style>` in it would end the
2925
+ // sheet and inject markup (a meta refresh, a form) into the message
2926
+ // document. `</` is written `<\/` - the same characters to the CSS parser,
2927
+ // never an end tag to the HTML parser (rule 57).
2928
+ css = escapeStyleText(css);
2929
+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><meta name="viewport" content="width=device-width, initial-scale=1"><style>html,body{margin:0;padding:0;}img,video{max-width:100%;height:auto;}${bodySizing}${visRules}${css}</style></head><body>${html}<script nonce="${nonce}">${bootstrap}</script></body></html>`;
2930
+ }
2931
+
2932
+ /**
2933
+ * A trigger's own property condition, e.g. "add_to_cart where value > 100".
2934
+ * Shared by overlays (onEventTracked) and placements (the event-trigger
2935
+ * window), so the two cannot disagree on what an operator means. An UNKNOWN
2936
+ * operator does not match - failing closed.
2937
+ */
2938
+ export function inAppTriggerFilterMatches(trigger: InAppTrigger, properties?: Record<string, any>): boolean {
2939
+ if (!trigger.attribute) return true;
2940
+ const actual = properties?.[trigger.attribute];
2941
+ const expected = trigger.value;
2942
+ switch (trigger.operator) {
2943
+ case undefined:
2944
+ case 'equals':
2945
+ case 'eq':
2946
+ return actual === expected;
2947
+ case 'not_equals':
2948
+ case 'neq':
2949
+ return actual !== expected;
2950
+ case 'greater_than':
2951
+ case 'gt':
2952
+ return Number(actual) > Number(expected);
2953
+ case 'less_than':
2954
+ case 'lt':
2955
+ return Number(actual) < Number(expected);
2956
+ case 'contains':
2957
+ return String(actual ?? '').includes(String(expected));
2958
+ case 'exists':
2959
+ return actual !== undefined && actual !== null;
2960
+ default:
2961
+ return false;
2962
+ }
2963
+ }