@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"joryio-editor.min.js","sources":["../src/core/page-edits.ts","../src/core/sdk-host-files.ts","../src/core/editor-gate.ts","../src/editor/visual-editor.ts","../src/editor/index.ts"],"sourcesContent":["/**\n * Page edits on web (BACKLOG D444 Phase 4, docs/PLACEMENTS_WEBSITE_LAYER.md 2).\n *\n * A page-edit campaign changes elements of the site's own page, found by CSS\n * selector: replace a text, an image, a link, hide an element, or insert a\n * placement next to it. Nothing else - no HTML, no script, no free-form DOM.\n *\n * - Text is set with `textContent` (never parsed as HTML); image and link\n * addresses must be absolute http(s); a selector that could escape the\n * anti-flicker style rule is refused. The server checks the same and this\n * SDK checks again: an edit it does not trust is skipped, never half-applied.\n * - Site settings first (`GET /v1/in-app/site-settings?sdkKey=`, public,\n * the same for every visitor; asked once per SDK session and refreshed at\n * most every SITE_SETTINGS_SESSION_REFRESH_SECONDS, kept in sessionStorage\n * so the session's later page loads do not wait for it): page edits off\n * for this site, or no live page-edit campaign, = nothing is asked or\n * applied on this page view. Otherwise the per-visitor answer.\n * - Anti-flicker: only edited elements are hidden (opacity, so the layout\n * does not move), for at most PAGE_EDIT_ANTI_FLICKER_MS from the start of\n * the page, never the whole body: the ones edited on this page last time,\n * or - on a first view, when there are none - the site's list from the site\n * settings (selectors only).\n * - Static edits from the last answer for this page apply at once, as each\n * element appears (MutationObserver); personalized edits apply when the\n * answer arrives and are never stored.\n * - A route change undoes this page's edits and applies the next page's.\n * - Exposure: `in_app.displayed` once an edit of the experience landed on an\n * element; a control visitor reports `in_app.control_viewed` once one of\n * the control's selectors is on the page.\n * - Server-applied edits (D450): a store plugin may already have written the\n * edits that are the same for every visitor into the page's HTML. Its\n * marker - a JSON block `#joryio-server-page-edits` and\n * `data-joryio-applied=\"<campaignId>:<editId>\"` on each changed element -\n * says which. The SDK never applies those again (no double insert, no\n * flicker), counts them as landed for the exposure (once, with its own\n * answer's token), keeps them out of the anti-flicker rule, and undoes one\n * (from `data-joryio-orig` and the element's `<template data-joryio-orig>`)\n * when the definitive answer for this visitor no longer carries it -\n * paused, edited, the visitor suppressed or in a control, page edits\n * switched off - or on a route change to another page.\n */\nimport { bucketHash } from '../utils/bucket-hash';\nimport type { IdentityManager } from './identity';\nimport type { SessionManager } from './session';\nimport type { Logger } from '../utils/logger';\nimport type { InAppAuthProvider } from './inapp';\nimport type { PlacementConsent } from './placements';\nimport { sdkIdentityHeaders } from './config';\nimport { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';\n\nexport const PAGE_EDIT_OPERATIONS = ['replace_text', 'replace_image', 'replace_link', 'hide', 'insert_placement'] as const;\nexport const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append'] as const;\nexport const PAGE_EDITS_CAPABILITY = 'page_edits';\n/** The longest edited elements stay hidden while the SDK waits. Never the whole body. */\nexport const PAGE_EDIT_ANTI_FLICKER_MS = 300;\n\nconst MAX_SELECTOR_LENGTH = 500;\nconst MAX_TEXT_LENGTH = 2000;\nconst MAX_URL_LENGTH = 2048;\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\nconst STYLE_ID = 'joryio-page-edits-anti-flicker';\n/**\n * Both stores are per workspace: the names carry a hash of the SDK key (the\n * flags cache's scheme), so two workspaces on one origin never share edits\n * or anti-flicker selectors. The unscoped names of earlier builds are never\n * read; they are removed on the first load.\n */\nconst LEGACY_ANSWER_STORE = 'jry_page_edits';\nconst LEGACY_SELECTOR_STORE = 'jry_page_edit_selectors';\nexport const pageEditsStorageKeys = (sdkKey: string): { answers: string; selectors: string; site: string } => {\n const h = bucketHash(sdkKey).toString(36);\n return { answers: `jry_page_edits_${h}`, selectors: `jry_page_edit_selectors_${h}`, site: `jry_page_edit_site_${h}` };\n};\nconst MAX_REMEMBERED_PAGES = 50;\nconst DEFAULT_TTL_SECONDS = 300;\n/**\n * The site settings are asked once per SDK session and then at most every\n * this many seconds within it (sessionStorage, per workspace, tied to the\n * session id: a new session asks again). The server's `ttlSeconds` (60) is\n * the HTTP cache lifetime for browsers and the CDN and no longer shortens\n * this: on a multi-page store every full page load used to re-ask, and the\n * answer is the same for every visitor and changes only when a page-edit\n * campaign is launched or page edits are switched on or off. The cost, by\n * design: a newly launched page-edit campaign reaches a visitor already on\n * the site within this time. Pausing is not delayed - `/page-edits` checks\n * every campaign's liveness itself on every page.\n */\nexport const SITE_SETTINGS_SESSION_REFRESH_SECONDS = 600;\n/** At most this many selectors of the site list go into the style rule (the server sends at most 200). */\nconst MAX_SITE_SELECTORS = 200;\n\n/**\n * The marker a store plugin writes with the edits it applied in the HTML\n * (backend common/web-experience/server-page-edits.ts, the plugins' shared\n * core; pinned by server-page-edits-parity.spec.ts).\n */\nexport const SERVER_PAGE_EDITS_MARKER_ID = 'joryio-server-page-edits';\nexport const SERVER_APPLIED_ATTR = 'data-joryio-applied';\nexport const SERVER_ORIG_ATTR = 'data-joryio-orig';\nexport const SERVER_SPOT_ATTR = 'data-joryio-server-spot';\nconst SERVER_MARKER_VERSION = 1;\n\ninterface ServerEdit {\n experienceId: string;\n variantId: string | null;\n edit: PageEditWire;\n}\n\nconst sameEdit = (a: PageEditWire, b: PageEditWire): boolean =>\n a.id === b.id &&\n a.selector === b.selector &&\n a.operation === b.operation &&\n (a.value ?? null) === (b.value ?? null) &&\n (a.placementKey ?? null) === (b.placementKey ?? null) &&\n (a.position ?? null) === (b.position ?? null) &&\n !b.personalized;\n\nfunction serverMarkerElement(): HTMLScriptElement | null {\n const head = document.head;\n if (!head) return null;\n for (const c of Array.from(head.children)) {\n if (c.id === SERVER_PAGE_EDITS_MARKER_ID) {\n return c.tagName === 'SCRIPT' && (c.getAttribute('type') || '').trim().toLowerCase() === 'application/json' ? (c as HTMLScriptElement) : null;\n }\n }\n return null;\n}\n\n/** An address the undo may write back: absolute http(s) or relative (no scheme). Anything else is dropped. */\nfunction safeRestoredUrl(v: unknown): string | null {\n if (typeof v !== 'string' || v.length > MAX_URL_LENGTH) return null;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(v)) return null;\n const t = v.trim();\n if (/^https?:\\/\\//i.test(t)) return v;\n // A scheme is letters before a ':' that comes before any '/', '?' or '#'.\n return /^[a-z][a-z0-9+.-]*:/i.test(t) ? null : v;\n}\n\nconst safeRestoredSrcset = (v: unknown): string | null =>\n typeof v === 'string' && v.split(',').every((c) => !c.trim() || safeRestoredUrl(c.trim().split(/\\s+/)[0]) !== null) ? v : null;\n\nconst HIDE_DECLARATION = 'display:none !important';\n\n/**\n * Inline text markup a replaced element's original content may come back with.\n * Everything else is unwrapped to its text (its children are kept, checked the same way):\n * no script, frame, object, embed, meta, base, link, style, form, svg or math element is\n * ever created, and no attribute outside RESTORE_ATTRIBUTES (no on*, style, srcdoc, data).\n */\nconst RESTORE_ELEMENTS = new Set(['A', 'ABBR', 'B', 'BDI', 'BDO', 'BR', 'CITE', 'CODE', 'DATA', 'DEL', 'DFN', 'EM', 'I', 'IMG', 'INS', 'KBD', 'MARK', 'Q', 'S', 'SAMP', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TIME', 'U', 'VAR', 'WBR']);\nconst RESTORE_ATTRIBUTES = new Set(['class', 'id', 'title', 'lang', 'dir', 'alt', 'width', 'height', 'datetime', 'href', 'src', 'srcset', 'rel', 'target']);\nconst MAX_RESTORE_NODES = 500;\n\nfunction restoreInline(from: DocumentFragment): DocumentFragment {\n const out = document.createDocumentFragment();\n let budget = MAX_RESTORE_NODES;\n const copy = (src: Node, into: Node): void => {\n for (const n of Array.from(src.childNodes)) {\n if (budget-- <= 0) return;\n if (n.nodeType === 3) {\n into.appendChild(document.createTextNode(n.nodeValue || ''));\n } else if (n.nodeType === 1) {\n const e = n as Element;\n if (e.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !RESTORE_ELEMENTS.has(e.tagName)) {\n // Not allowed: only its text and allowed descendants, never the element.\n if (!/^(SCRIPT|STYLE|TEMPLATE|IFRAME|OBJECT|EMBED|NOSCRIPT|TEXTAREA|TITLE)$/.test(e.tagName)) copy(e, into);\n continue;\n }\n const made = document.createElement(e.tagName.toLowerCase());\n for (const a of Array.from(e.attributes)) {\n const name = a.name.toLowerCase();\n if (!RESTORE_ATTRIBUTES.has(name)) continue;\n if (name === 'href' || name === 'src') {\n const v = safeRestoredUrl(a.value);\n if (v !== null) made.setAttribute(name, v);\n } else if (name === 'srcset') {\n const v = safeRestoredSrcset(a.value);\n if (v !== null) made.setAttribute(name, v);\n } else {\n made.setAttribute(name, a.value);\n }\n }\n into.appendChild(made);\n copy(e, made);\n }\n }\n };\n copy(from, out);\n return out;\n}\n\nconst tokensOf = (el: Element): string[] => (el.getAttribute(SERVER_APPLIED_ATTR) || '').split(/\\s+/).filter(Boolean);\n\n/** `GET /v1/in-app/site-settings` (backend common/web-experience/page-edit-site.ts). */\nexport interface SiteSettingsResponse {\n success?: boolean;\n ttlSeconds?: number;\n pageEdits?: { enabled?: boolean; active?: boolean; antiFlickerSelectors?: string[] };\n}\nexport interface PageEditSite {\n enabled: boolean;\n active: boolean;\n antiFlickerSelectors: string[];\n}\n\nexport type PageEditOperation = (typeof PAGE_EDIT_OPERATIONS)[number];\nexport type PageEditPosition = (typeof PAGE_EDIT_POSITIONS)[number];\n\nexport interface PageEditWire {\n id: string;\n selector: string;\n operation: PageEditOperation;\n value?: string;\n placementKey?: string;\n position?: PageEditPosition;\n personalized?: true;\n}\n\nexport interface PageEditExperienceWire {\n id: string;\n variantId: string | null;\n deliveryId: string | null;\n deliveryToken: string | null;\n isControl: boolean;\n controlToken: string | null;\n selectors: string[];\n edits: PageEditWire[];\n}\n\nexport interface PageEditsResponse {\n success?: boolean;\n ttlSeconds?: number;\n experiences?: PageEditExperienceWire[];\n}\n\nexport interface PageEditRuntime {\n /** As placements: null = send nothing; `granted` = personal serving and reporting. */\n consent: () => PlacementConsent | null;\n requestTimeoutMs?: number;\n noteStatus?: (status: number, data: any) => void;\n}\n\n/** Same rule as the server: nothing that could close the style rule, no comment, no control character. */\nexport function isSafeSelector(selector: unknown): selector is string {\n if (typeof selector !== 'string') return false;\n const s = selector.trim();\n if (!s || s.length > MAX_SELECTOR_LENGTH) return false;\n if (/[{};<@]/.test(s) || s.includes('/*') || s.includes('*/')) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(s)) return false;\n try {\n if (typeof document !== 'undefined') document.createDocumentFragment().querySelector(s);\n } catch {\n return false; // not a selector this browser parses\n }\n return true;\n}\n\nexport function isSafeEditUrl(url: unknown): url is string {\n if (typeof url !== 'string') return false;\n const u = url.trim();\n if (!u || u.length > MAX_URL_LENGTH) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f\\s]/.test(u)) return false;\n return /^https?:\\/\\/[^/?#\\s]+/i.test(u);\n}\n\n/** The edit as this SDK will apply it, or null - an edit it does not trust is skipped whole. */\nexport function trustedEdit(e: any): PageEditWire | null {\n if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector)) return null;\n const base = { id: e.id, selector: e.selector.trim(), ...(e.personalized === true ? { personalized: true as const } : {}) };\n switch (e.operation) {\n case 'hide':\n return { ...base, operation: 'hide' };\n case 'replace_text':\n return typeof e.value === 'string' && e.value.length <= MAX_TEXT_LENGTH ? { ...base, operation: 'replace_text', value: e.value } : null;\n case 'replace_image':\n case 'replace_link':\n return isSafeEditUrl(e.value) ? { ...base, operation: e.operation, value: e.value.trim() } : null;\n case 'insert_placement':\n return typeof e.placementKey === 'string' && PLACEMENT_KEY_PATTERN.test(e.placementKey)\n ? { ...base, operation: 'insert_placement', placementKey: e.placementKey, position: (PAGE_EDIT_POSITIONS as readonly string[]).includes(e.position) ? e.position : 'after' }\n : null;\n default:\n return null;\n }\n}\n\ninterface Applied {\n el: Element;\n editId: string;\n undo: () => void;\n}\n\ninterface Experience {\n wire: PageEditExperienceWire;\n edits: PageEditWire[];\n}\n\n/** The site settings as stored for one SDK session (`sid`), answered at `at`. */\ninterface StoredSite {\n sid: string;\n at: number;\n value: PageEditSite;\n}\n\nexport class PageEditManager {\n private page: PageContextTracker | null = null;\n private pageUnsubscribe: (() => void) | null = null;\n private experiences: Experience[] = [];\n private applied: Applied[] = [];\n private reported = new Set<string>();\n private observer: MutationObserver | null = null;\n private scheduled = false;\n private flickerTimer: ReturnType<typeof setTimeout> | null = null;\n /** When the current page started: the anti-flicker never lasts past this + PAGE_EDIT_ANTI_FLICKER_MS. */\n private pageStartedAt = 0;\n /** The last site settings answer, for its session id (mirrors the sessionStorage entry). */\n private site: StoredSite | null = null;\n private siteRequest: Promise<PageEditSite | null> | null = null;\n private readonly stores: { answers: string; selectors: string; site: string };\n /** Edits the page's HTML arrived with (token -> edit); null until the marker was read. */\n private server: Map<string, ServerEdit> | null = null;\n /** The page those were written for: a route change elsewhere undoes them. */\n private serverUrl: string | null = null;\n private generation = 0;\n private started = false;\n private destroyed = false;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private identity: IdentityManager,\n private session: SessionManager,\n private logger: Logger,\n private runtime: PageEditRuntime,\n private auth?: InAppAuthProvider,\n ) {\n this.stores = pageEditsStorageKeys(sdkKey);\n try {\n // Not workspace-scoped: another workspace on this origin may have written them.\n localStorage.removeItem(LEGACY_SELECTOR_STORE);\n sessionStorage.removeItem(LEGACY_ANSWER_STORE);\n } catch {\n /* storage blocked */\n }\n }\n\n setPageContext(tracker: PageContextTracker | null): void {\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n this.page = tracker;\n if (tracker) {\n this.pageUnsubscribe = tracker.onSignal((s) => {\n if (s.type === 'page_change' && this.started) this.loadPage();\n });\n }\n }\n\n /** Hide what was edited here last time, apply what is known, observe the DOM, ask the server. */\n start(): void {\n if (this.started || this.destroyed || typeof document === 'undefined') return;\n this.started = true;\n if (typeof MutationObserver !== 'undefined' && document.documentElement) {\n this.observer = new MutationObserver(() => this.schedule());\n this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n this.loadPage();\n }\n\n /**\n * The audience changed (identify, reset, consent): forget this visitor's\n * answers and ask again. `siteSettings: true` (reset, wipeData, a consent\n * change) forgets the stored site settings too; identify keeps them - they\n * are the same for every visitor of the site.\n */\n invalidate(opts: { siteSettings?: boolean } = {}): void {\n this.generation++;\n this.reported.clear();\n if (opts.siteSettings) this.forgetSite();\n try {\n sessionStorage.removeItem(this.stores.answers);\n } catch {\n /* ignore */\n }\n if (this.started) this.loadPage();\n }\n\n destroy(): void {\n this.destroyed = true;\n this.pageUnsubscribe?.();\n this.observer?.disconnect();\n this.observer = null;\n this.revertAll();\n this.showAll();\n }\n\n /** Currently applied edits, for tests and debugging. */\n appliedCount(): number {\n return this.applied.length;\n }\n\n /** Edits the page arrived with from the server and still carries, for tests and debugging. */\n serverAppliedCount(): number {\n return this.serverEdits().size;\n }\n\n // ── one page ─────────────────────────────────────────────────────────────\n\n private url(): string | null {\n return this.page ? this.page.current().url : currentPageUrl();\n }\n\n private loadPage(): void {\n const generation = ++this.generation;\n this.revertAll();\n const url = this.url();\n if (!url) {\n this.experiences = [];\n return;\n }\n this.pageStartedAt = Date.now();\n // The server's edits belong to the page they were written for.\n const server = this.serverEdits();\n if (this.serverUrl === null) this.serverUrl = url;\n else if (url !== this.serverUrl && server.size) this.reconcileServer([]);\n // 1. Anti-flicker: the elements edited on this page last time, at most 300 ms.\n const remembered = this.rememberedSelectors(url);\n this.hide(remembered);\n // 2. Static edits from the last answer for this page, applied as elements appear.\n this.experiences = this.cachedExperiences(url);\n this.applyAll();\n // 3. The site settings (cached), then the answer for this page and visitor.\n void this.siteThenFetch(url, generation, remembered.length > 0);\n }\n\n private async siteThenFetch(url: string, generation: number, rememberedAny: boolean): Promise<void> {\n // A stored answer for this session is used at once - no wait before the\n // per-visitor request - and refreshed in the background when it is older\n // than SITE_SETTINGS_SESSION_REFRESH_SECONDS. Only without one (first\n // page of a session) does the page wait for the site settings.\n const stored = this.storedSite();\n let site: PageEditSite | null;\n if (stored) {\n site = stored.value;\n if (Date.now() - stored.at >= SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) {\n void this.requestSite().then((fresh) => {\n // Was off or idle and is live now: this page asks after all.\n if (fresh && fresh.enabled && fresh.active && !(site!.enabled && site!.active) && generation === this.generation && !this.destroyed) {\n void this.fetch(url, generation);\n }\n });\n }\n } else {\n site = await this.siteSettings();\n }\n if (generation !== this.generation || this.destroyed) return;\n if (site && (!site.enabled || !site.active)) {\n // Off for this site, or nothing live: undo what the cache (or the server) applied, ask nothing.\n this.revertAll();\n this.reconcileServer([]);\n this.experiences = [];\n this.showAll();\n return;\n }\n // First view on this page: hold back the site's edited elements, inside the same 300 ms.\n if (site && !rememberedAny && site.antiFlickerSelectors.length) this.hide(site.antiFlickerSelectors);\n await this.fetch(url, generation);\n }\n\n /**\n * The site settings: one GET per SDK session, then at most one per\n * SITE_SETTINGS_SESSION_REFRESH_SECONDS within it, kept in sessionStorage\n * per workspace across the session's page loads. A CORS-simple request (no\n * custom header, the key in the query string - the server refuses a key in\n * a header there, the URL being the cache key), so no preflight. Null when\n * unknown (network error, an HTTP error, an answer it cannot read): then\n * the SDK asks /page-edits as it always did, and nothing is stored.\n */\n siteSettings(): Promise<PageEditSite | null> {\n const stored = this.storedSite();\n if (stored && Date.now() - stored.at < SITE_SETTINGS_SESSION_REFRESH_SECONDS * 1000) return Promise.resolve(stored.value);\n return this.requestSite();\n }\n\n /** The stored answer for the current session id (any age), or null. */\n private storedSite(): StoredSite | null {\n const sid = this.session.getSessionId();\n if (!sid) return null; // no session (after wipeData): nothing to tie it to\n if (this.site && this.site.sid === sid) return this.site;\n this.site = null;\n try {\n const raw = JSON.parse(sessionStorage.getItem(this.stores.site) || 'null');\n const v = raw?.value;\n if (raw && raw.sid === sid && typeof raw.at === 'number' && raw.at <= Date.now() && v && typeof v === 'object') {\n this.site = {\n sid,\n at: raw.at,\n value: {\n enabled: v.enabled !== false,\n active: v.active !== false,\n antiFlickerSelectors: (Array.isArray(v.antiFlickerSelectors) ? v.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),\n },\n };\n } else if (raw) {\n sessionStorage.removeItem(this.stores.site); // another session's answer\n }\n } catch {\n /* storage blocked or unreadable: ask */\n }\n return this.site;\n }\n\n private forgetSite(): void {\n this.site = null;\n try {\n sessionStorage.removeItem(this.stores.site);\n } catch {\n /* ignore */\n }\n }\n\n private requestSite(): Promise<PageEditSite | null> {\n if (this.siteRequest) return this.siteRequest;\n const request = (async (): Promise<PageEditSite | null> => {\n const sid = this.session.getSessionId();\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/site-settings?sdkKey=${encodeURIComponent(this.sdkKey)}`, { method: 'GET', credentials: 'omit' });\n if (!res.ok) {\n this.runtime.noteStatus?.(res.status, null);\n this.forgetSite();\n return null;\n }\n const data: SiteSettingsResponse = await res.json();\n const pe = data?.pageEdits;\n if (!pe || typeof pe !== 'object') {\n this.forgetSite();\n return null;\n }\n const value: PageEditSite = {\n enabled: pe.enabled !== false,\n active: pe.active !== false,\n antiFlickerSelectors: (Array.isArray(pe.antiFlickerSelectors) ? pe.antiFlickerSelectors : []).filter(isSafeSelector).slice(0, MAX_SITE_SELECTORS),\n };\n // data.ttlSeconds is the HTTP cache lifetime; the SDK keeps the\n // answer for the session (SITE_SETTINGS_SESSION_REFRESH_SECONDS).\n if (sid) {\n this.site = { sid, at: Date.now(), value };\n try {\n sessionStorage.setItem(this.stores.site, JSON.stringify(this.site));\n } catch {\n /* storage full or blocked: kept in memory for this page */\n }\n }\n return value;\n } catch (error) {\n this.logger.debug('Site settings request failed', error);\n // Unknown: a stale stored answer is not trusted past its refresh time.\n this.forgetSite();\n return null;\n } finally {\n this.siteRequest = null;\n }\n })();\n this.siteRequest = request;\n return request;\n }\n\n private async fetch(url: string, generation: number): Promise<void> {\n const consent = this.runtime.consent();\n if (consent === null || this.destroyed) {\n this.showAll();\n return;\n }\n const personal = consent === 'granted';\n const userId = personal ? this.identity.getUserId() : null;\n const anonymousId = personal ? this.identity.getAnonymousId() : null;\n const body = {\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n ...(personal ? { sessionId: this.session.getSessionId() } : {}),\n deviceType: 'web',\n locale: typeof navigator !== 'undefined' ? navigator.language : undefined,\n capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY],\n trackingConsent: consent,\n context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} },\n };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/page-edits`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),\n },\n body: JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n });\n if (generation !== this.generation) return;\n if (!res.ok) {\n // 429 and every other failure: keep what is applied (the cached static edits).\n this.runtime.noteStatus?.(res.status, null);\n return;\n }\n const data: PageEditsResponse = await res.json();\n if (generation !== this.generation || !data || data.success === false || !Array.isArray(data.experiences)) return;\n const experiences = data.experiences\n .filter((x) => x && typeof x.id === 'string')\n .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e): e is PageEditWire => !!e) }));\n this.revertAll();\n this.experiences = experiences;\n // The definitive answer: a server-applied edit it no longer carries is undone first.\n this.reconcileServer(experiences);\n this.remember(url, experiences, data.ttlSeconds);\n this.applyAll();\n } catch (error) {\n this.logger.debug('Page edits request failed', error);\n } finally {\n clearTimeout(timeout);\n if (generation === this.generation) this.showAll();\n }\n }\n\n // ── applying ─────────────────────────────────────────────────────────────\n\n private schedule(): void {\n if (this.scheduled || this.destroyed) return;\n this.scheduled = true;\n const run = () => {\n this.scheduled = false;\n this.applyAll();\n };\n if (typeof queueMicrotask === 'function') queueMicrotask(run);\n else void Promise.resolve().then(run);\n }\n\n private applyAll(): void {\n if (this.destroyed || typeof document === 'undefined') return;\n // Our own DOM writes would wake the observer; it is paused while we write.\n this.observer?.disconnect();\n try {\n for (const x of this.experiences) {\n if (x.wire.isControl) {\n const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);\n if (seen) this.reportControl(x.wire);\n continue;\n }\n let landed = false;\n for (const edit of x.edits) {\n const token = `${x.wire.id}:${edit.id}`;\n const server = this.serverEdits().get(token);\n const byServer = !!server && server.variantId === (x.wire.variantId ?? null) && sameEdit(server.edit, edit);\n for (const el of this.query(edit.selector)) {\n if (this.applied.some((a) => a.el === el && a.editId === edit.id)) {\n landed = true;\n continue;\n }\n // Already in the HTML the server sent: never applied a second time.\n if (byServer && tokensOf(el).includes(token)) {\n landed = true;\n continue;\n }\n const undo = this.applyOne(el, edit);\n if (undo) {\n this.applied.push({ el, editId: edit.id, undo });\n landed = true;\n }\n }\n }\n if (landed) this.reportDisplayed(x.wire);\n }\n } finally {\n if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n\n private query(selector: string): Element[] {\n try {\n return Array.from(document.querySelectorAll(selector)).filter((el) => !(el as HTMLElement).closest?.('[data-joryio-editor]'));\n } catch {\n return [];\n }\n }\n\n /** One edit on one element; returns how to undo it, or null when it does not fit the element. */\n private applyOne(el: Element, edit: PageEditWire): (() => void) | null {\n const h = el as HTMLElement;\n switch (edit.operation) {\n case 'replace_text': {\n const before = Array.from(el.childNodes);\n el.textContent = edit.value ?? '';\n return () => {\n el.textContent = '';\n before.forEach((n) => el.appendChild(n));\n };\n }\n case 'replace_image': {\n if (el.tagName !== 'IMG') return null;\n const src = el.getAttribute('src');\n const srcset = el.getAttribute('srcset');\n el.setAttribute('src', edit.value!);\n // A srcset would win over the new src in every browser.\n el.removeAttribute('srcset');\n return () => {\n if (src === null) el.removeAttribute('src');\n else el.setAttribute('src', src);\n if (srcset !== null) el.setAttribute('srcset', srcset);\n };\n }\n case 'replace_link': {\n if (el.tagName !== 'A') return null;\n const href = el.getAttribute('href');\n el.setAttribute('href', edit.value!);\n return () => (href === null ? el.removeAttribute('href') : el.setAttribute('href', href));\n }\n case 'hide': {\n const display = h.style.getPropertyValue('display');\n const priority = h.style.getPropertyPriority('display');\n h.style.setProperty('display', 'none', 'important');\n return () => (display ? h.style.setProperty('display', display, priority) : h.style.removeProperty('display'));\n }\n case 'insert_placement': {\n const spot = document.createElement('div');\n spot.setAttribute('data-joryio-placement', edit.placementKey!);\n spot.setAttribute('data-joryio-edit', edit.id);\n const where: InsertPosition =\n edit.position === 'before' ? 'beforebegin' : edit.position === 'prepend' ? 'afterbegin' : edit.position === 'append' ? 'beforeend' : 'afterend';\n el.insertAdjacentElement(where, spot);\n return () => spot.remove();\n }\n default:\n return null;\n }\n }\n\n private revertAll(): void {\n const applied = this.applied.splice(0).reverse();\n if (!applied.length) return;\n this.observer?.disconnect();\n try {\n for (const a of applied) {\n try {\n a.undo();\n } catch {\n /* the element may be gone */\n }\n }\n } finally {\n if (this.observer && typeof document !== 'undefined' && document.documentElement) {\n this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n }\n\n // ── anti-flicker ─────────────────────────────────────────────────────────\n\n private hide(selectors: string[]): void {\n const safe = selectors.filter(isSafeSelector);\n if (!safe.length || typeof document === 'undefined') return;\n // Never past PAGE_EDIT_ANTI_FLICKER_MS from the start of this page, however late the list arrived.\n const left = PAGE_EDIT_ANTI_FLICKER_MS - (Date.now() - (this.pageStartedAt || Date.now()));\n if (left <= 0) return;\n let style = document.getElementById(STYLE_ID) as HTMLStyleElement | null;\n if (!style) {\n style = document.createElement('style');\n style.id = STYLE_ID;\n (document.head || document.documentElement).appendChild(style);\n }\n // Only these elements, never the body; opacity, so the layout does not move.\n // Elements the server already edited are never held back.\n style.textContent = this.serverEdits().size\n ? `:is(${safe.join(',')}):not([${SERVER_APPLIED_ATTR}]){opacity:0 !important}`\n : `${safe.join(',')}{opacity:0 !important}`;\n if (this.flickerTimer) clearTimeout(this.flickerTimer);\n this.flickerTimer = setTimeout(() => this.showAll(), left);\n }\n\n private showAll(): void {\n if (this.flickerTimer) clearTimeout(this.flickerTimer);\n this.flickerTimer = null;\n try {\n document.getElementById(STYLE_ID)?.remove();\n } catch {\n /* ignore */\n }\n }\n\n // ── what is remembered (selectors and static edits only, never a personalized value) ──\n\n private subjectKey(): string {\n return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;\n }\n\n private remember(url: string, experiences: Experience[], ttlSeconds?: number): void {\n const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.map((e) => e.selector))))];\n try {\n const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};\n delete all[url];\n if (selectors.length) all[url] = selectors.slice(0, 50);\n const keys = Object.keys(all);\n for (const k of keys.slice(0, Math.max(0, keys.length - MAX_REMEMBERED_PAGES))) delete all[k];\n localStorage.setItem(this.stores.selectors, JSON.stringify(all));\n } catch {\n /* storage blocked: no anti-flicker next time, nothing else */\n }\n try {\n const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};\n const pages = stored.subject === this.subjectKey() && stored.pages ? stored.pages : {};\n pages[url] = {\n at: Date.now(),\n ttl: (ttlSeconds && ttlSeconds > 0 ? ttlSeconds : DEFAULT_TTL_SECONDS) * 1000,\n experiences: experiences\n .filter((x) => !x.wire.isControl)\n .map((x) => ({ ...x.wire, deliveryToken: null, edits: x.edits.filter((e) => !e.personalized) }))\n .filter((x) => x.edits.length),\n };\n sessionStorage.setItem(this.stores.answers, JSON.stringify({ subject: this.subjectKey(), pages }));\n } catch {\n /* ignore */\n }\n }\n\n private rememberedSelectors(url: string): string[] {\n try {\n const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};\n return Array.isArray(all[url]) ? all[url].filter((s: unknown) => typeof s === 'string') : [];\n } catch {\n return [];\n }\n }\n\n private cachedExperiences(url: string): Experience[] {\n try {\n const stored = JSON.parse(sessionStorage.getItem(this.stores.answers) || '{}') || {};\n if (stored.subject !== this.subjectKey()) return [];\n const entry = stored.pages?.[url];\n if (!entry || Date.now() - entry.at > entry.ttl) return [];\n // Applied, never reported: the exposure belongs to the answer with a token.\n return (entry.experiences || []).map((wire: PageEditExperienceWire) => ({\n wire: { ...wire, isControl: false, deliveryToken: null },\n edits: (wire.edits || []).map(trustedEdit).filter((e): e is PageEditWire => !!e && !e.personalized),\n }));\n } catch {\n return [];\n }\n }\n\n // ── edits the server applied (D450) ──────────────────────────────────────\n\n /** The marker, read once it is in the DOM (it sits right after <head>). */\n private serverEdits(): Map<string, ServerEdit> {\n if (this.server) return this.server;\n const found = new Map<string, ServerEdit>();\n if (typeof document === 'undefined') return found;\n // Trusted only where the plugin writes it: a JSON <script> directly in <head>\n // (the plugin inserts it right after <head>, before any page script). An\n // element with that id anywhere else - user content in the body, DOM\n // clobbering - is ignored.\n const el = serverMarkerElement();\n if (!el) {\n // Not (yet) in the DOM: asked again on the next call while the page is still loading.\n if (document.readyState !== 'loading') this.server = found;\n return found;\n }\n try {\n const data = JSON.parse(el.textContent || '{}');\n if (data && data.v === SERVER_MARKER_VERSION && Array.isArray(data.experiences)) {\n for (const x of data.experiences) {\n if (!x || typeof x.id !== 'string' || !Array.isArray(x.edits)) continue;\n for (const raw of x.edits) {\n const edit = trustedEdit(raw);\n if (edit && !edit.personalized) found.set(`${x.id}:${edit.id}`, { experienceId: x.id, variantId: typeof x.variantId === 'string' ? x.variantId : null, edit });\n }\n }\n }\n } catch {\n /* a marker this SDK cannot read: treated as none; the edits it lists stay as the page has them */\n }\n this.server = found;\n return found;\n }\n\n /**\n * Keep the server-applied edits the definitive answer still carries for this\n * visitor (same campaign, variant and edit); undo every other one.\n */\n private reconcileServer(experiences: Experience[]): void {\n const server = this.serverEdits();\n if (!server.size || typeof document === 'undefined') return;\n const keep = new Set<string>();\n for (const x of experiences) {\n if (x.wire.isControl) continue;\n for (const e of x.edits) {\n const token = `${x.wire.id}:${e.id}`;\n const s = server.get(token);\n if (s && s.variantId === (x.wire.variantId ?? null) && sameEdit(s.edit, e)) keep.add(token);\n }\n }\n const undo = [...server.keys()].filter((t) => !keep.has(t));\n if (!undo.length) return;\n this.observer?.disconnect();\n try {\n for (const token of undo) {\n this.undoServerEdit(token, server.get(token)!.edit);\n server.delete(token);\n }\n } finally {\n if (this.observer && document.documentElement) this.observer.observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n\n /** Put back what the server changed for one edit, from the undo data it left on each element. */\n private undoServerEdit(token: string, edit: PageEditWire): void {\n for (const el of Array.from(document.querySelectorAll(`[${SERVER_APPLIED_ATTR}]`))) {\n const tokens = tokensOf(el);\n if (!tokens.includes(token)) continue;\n let all: Record<string, any> = {};\n try {\n all = JSON.parse(el.getAttribute(SERVER_ORIG_ATTR) || '{}') || {};\n } catch {\n all = {};\n }\n const orig = all[token] || {};\n // Only an element that still shows exactly what the server applied is put back,\n // and only with values that pass the same checks as an edit.\n try {\n switch (edit.operation) {\n case 'replace_text': {\n const tpl = Array.from(el.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute(SERVER_ORIG_ATTR) === token) as HTMLTemplateElement | undefined;\n if (tpl && tpl.content && el.textContent === edit.value) {\n // Rebuilt node by node through an allowlist - never the template's markup made live.\n const restored = restoreInline(tpl.content);\n el.textContent = '';\n el.appendChild(restored);\n }\n break;\n }\n case 'replace_image':\n if (el.tagName === 'IMG' && el.getAttribute('src') === edit.value) {\n const src = safeRestoredUrl(orig.src);\n const srcset = safeRestoredSrcset(orig.srcset);\n if (src === null) el.removeAttribute('src');\n else el.setAttribute('src', src);\n if (srcset !== null) el.setAttribute('srcset', srcset);\n }\n break;\n case 'replace_link':\n if (el.tagName === 'A' && el.getAttribute('href') === edit.value) {\n const href = safeRestoredUrl(orig.href);\n if (href === null) el.removeAttribute('href');\n else el.setAttribute('href', href);\n }\n break;\n case 'hide': {\n // Never a style string from the marker: the original is put back only when the\n // attribute is exactly it plus the server's one declaration; otherwise that one\n // declaration is removed.\n const current = el.getAttribute('style') || '';\n const before = typeof orig.style === 'string' ? orig.style : null;\n const base = before === null ? '' : before.trim().replace(/;+$/, '');\n if (current === (base ? base + ';' : '') + HIDE_DECLARATION) {\n if (before === null) el.removeAttribute('style');\n else el.setAttribute('style', before);\n } else if ((el as HTMLElement).style?.getPropertyValue('display') === 'none') {\n (el as HTMLElement).style.removeProperty('display');\n }\n break;\n }\n default:\n break;\n }\n } catch {\n /* the element changed since: leave it */\n }\n const left = tokens.filter((t) => t !== token);\n if (left.length) el.setAttribute(SERVER_APPLIED_ATTR, left.join(' '));\n else el.removeAttribute(SERVER_APPLIED_ATTR);\n delete all[token];\n if (Object.keys(all).length) el.setAttribute(SERVER_ORIG_ATTR, JSON.stringify(all));\n else el.removeAttribute(SERVER_ORIG_ATTR);\n }\n if (edit.operation === 'insert_placement') {\n for (const spot of Array.from(document.querySelectorAll(`div[${SERVER_SPOT_ATTR}][data-joryio-placement]`))) {\n if (spot.getAttribute(SERVER_SPOT_ATTR) === token && spot.getAttribute('data-joryio-placement') === edit.placementKey) spot.remove();\n }\n }\n }\n\n // ── reporting ────────────────────────────────────────────────────────────\n\n private reportDisplayed(x: PageEditExperienceWire): void {\n if (!x.deliveryToken || this.runtime.consent() !== 'granted') return;\n const once = `displayed:${x.deliveryId || x.deliveryToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post({\n campaignId: x.id,\n ...(x.variantId ? { variantId: x.variantId } : {}),\n deliveryToken: x.deliveryToken,\n action: 'displayed',\n displayedAt: new Date().toISOString(),\n });\n }\n\n private reportControl(x: PageEditExperienceWire): void {\n if (!x.controlToken || this.runtime.consent() !== 'granted') return;\n const once = `control:${x.controlToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post({ action: 'control_viewed', controlToken: x.controlToken, viewedAt: new Date().toISOString() });\n }\n\n private post(body: Record<string, any>): void {\n const userId = this.identity.getUserId();\n const full = { ...body, ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId(), sessionId: this.session.getSessionId(), deviceType: 'web' };\n fetch(`${this.apiEndpoint}/v1/in-app/track`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : this.identity.getAnonymousId()) || {}),\n },\n body: JSON.stringify(full),\n keepalive: true,\n })\n .then((r) => {\n if (!r.ok) this.runtime.noteStatus?.(r.status, null);\n })\n .catch((error) => this.logger.debug('Page edit report failed', error));\n }\n}\n","/**\n * The files the core loads on demand from the SDK host, next to\n * `joryio.min.js`: the point-and-click editor (`joryio-editor.min.js`,\n * src/core/editor-gate.ts) and the default card feed (`joryio-cards-ui.min.js`,\n * src/core/cards.ts). Kept out of the core so that a visitor who never needs\n * them never downloads them (BACKLOG D444).\n */\nimport { SDK_VERSION } from './config';\n\nexport const SDK_HOST = 'https://sdk.joryio.com';\n\n/** A core bundle's own file name: what a script tag loads (sdk.joryio.com, the npm package's dist/). */\nconst CORE_FILE = /\\/joryio(?:\\.umd)?(?:\\.min)?\\.js$/;\n\n/**\n * The folder the running core was loaded from (with a trailing slash), when\n * it was loaded by a script tag as `joryio.min.js` over https - for example\n * `https://sdk.joryio.com/web/1.4.0-beta.4/`. Null when bundled into the\n * site's own code (the script is then the site's file), or not over https.\n */\nexport function coreFolderOf(src: string | null | undefined): string | null {\n if (!src || typeof src !== 'string') return null;\n let u: URL;\n try {\n u = new URL(src);\n } catch {\n return null;\n }\n if (u.protocol !== 'https:' || !CORE_FILE.test(u.pathname)) return null;\n return `${u.origin}${u.pathname.replace(/[^/]*$/, '')}`;\n}\n\n/**\n * Read while this module is evaluated, i.e. while the core's script runs:\n * `document.currentScript` is null afterwards (and for a module script),\n * then the last `<script src=\".../joryio.min.js\">` on the page is used.\n */\nfunction readOwnFolder(): string | null {\n if (typeof document === 'undefined') return null;\n try {\n const current = document.currentScript as HTMLScriptElement | null;\n const fromCurrent = coreFolderOf(current && current.src);\n if (fromCurrent || (current && current.src)) return fromCurrent;\n const tags = document.querySelectorAll('script[src]');\n for (let i = tags.length - 1; i >= 0; i--) {\n const folder = coreFolderOf((tags[i] as HTMLScriptElement).src);\n if (folder) return folder;\n }\n } catch {\n /* no DOM access */\n }\n return null;\n}\nconst OWN_FOLDER = readOwnFolder();\n\n/**\n * Where a lazily loaded file comes from, in order:\n * 1. the folder the core itself was loaded from (`coreFolderOf`), so a core\n * from `sdk.joryio.com/web/1.4.0-beta.4/` (a beta, whose SDK_VERSION\n * still says 1.4.0) or from the npm package's `dist/` on a CDN loads the\n * side files of the same build - unless that folder is the major channel\n * `sdk.joryio.com/web/<major>/`, which moves: then 2 goes first;\n * 2. the exact SDK version's folder on the SDK host (immutable, the same\n * build as this core);\n * 3. the major channel, as a fallback (a version not on the CDN, such as a\n * local build).\n * An init option (`editorScriptUrl`, `cardsUiScriptUrl`) replaces all of\n * them, for a self-hosted SDK.\n */\nexport function sdkHostFileUrls(file: string, override?: string, ownFolder: string | null = OWN_FOLDER): string[] {\n if (override) return [override];\n const major = SDK_VERSION.split('.')[0];\n const exact = `${SDK_HOST}/web/${SDK_VERSION}/${file}`;\n const channel = `${SDK_HOST}/web/${major}/${file}`;\n const urls = ownFolder && ownFolder !== `${SDK_HOST}/web/${major}/` ? [`${ownFolder}${file}`, exact, channel] : [exact, channel];\n return urls.filter((u, i) => urls.indexOf(u) === i);\n}\n\n/** Inject one script tag; resolves when it ran (onload), rejects on an error (a 404, a blocking CSP). */\nexport function loadSdkScript(src: string, marker: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const s = document.createElement('script');\n s.src = src;\n s.async = true;\n s.setAttribute(marker, 'bundle');\n s.onload = () => resolve();\n s.onerror = () => {\n s.remove();\n reject(new Error(`could not load ${src}`));\n };\n (document.head || document.documentElement).appendChild(s);\n });\n}\n","/**\n * The point-and-click editor's door in the core bundle (BACKLOG D444 Phase 4,\n * docs/PLACEMENTS_WEBSITE_LAYER.md 3).\n *\n * The visual editor itself (highlight, panel, selector computation) is a\n * separate file, `joryio-editor.min.js`, served from the same SDK host next to\n * `joryio.min.js`, so the ~every-visitor bundle carries only this handshake:\n *\n * 1. only when the tab was opened with `?joryio_editor=1` AND by another\n * window (`window.opener`) AND page edits are not switched off in the\n * site's code (`pageEdits: false`), post `joryio:editor-ready` to the\n * opener (no secret in it);\n * 2. accept `joryio:editor-token` only from that opener window, and check\n * the token with `POST /v1/in-app/editor/verify`, which answers the\n * dashboard origin it was minted for (bound to this site's origin and\n * this SDK key's workspace; refused when page edits are off);\n * 3. only then load the editor bundle and hand it the verified dashboard\n * origin and the opener. Nothing is loaded for any other visitor.\n */\nimport type { Logger } from '../utils/logger';\nimport { sdkIdentityHeaders } from './config';\nimport { loadSdkScript, sdkHostFileUrls } from './sdk-host-files';\n\nexport const EDITOR_QUERY_FLAG = 'joryio_editor';\nexport const EDITOR_MESSAGES = {\n READY: 'joryio:editor-ready',\n TOKEN: 'joryio:editor-token',\n ACTIVE: 'joryio:editor-active',\n PICK: 'joryio:editor-pick',\n CLOSE: 'joryio:editor-close',\n CLOSED: 'joryio:editor-closed',\n} as const;\n\n/** The global the editor bundle registers itself under, and the contract version between the two files. */\nexport const EDITOR_GLOBAL = '__joryioEditor';\nexport const EDITOR_API_VERSION = 1;\n/** The file next to joryio.min.js on the SDK host. */\nexport const EDITOR_BUNDLE_FILE = 'joryio-editor.min.js';\n\nexport interface EditorBundleApi {\n version: number;\n start(ctx: { dashboardOrigin: string; opener: Window; logger: Logger; onStop: () => void }): { stop(): void };\n}\n\n/**\n * Where the editor bundle is loaded from: the exact SDK version's folder on\n * the SDK host, then the major channel (see sdkHostFileUrls).\n * `editorScriptUrl` (init) replaces both, for a self-hosted SDK.\n */\nexport function editorBundleUrls(override?: string): string[] {\n return sdkHostFileUrls(EDITOR_BUNDLE_FILE, override);\n}\n\n/** True when this tab was opened by the dashboard's editor (the flag and an opener). */\nexport function editorRequested(): boolean {\n try {\n return typeof window !== 'undefined' && !!window.opener && new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) === '1';\n } catch {\n return false;\n }\n}\n\nfunction loadScript(src: string): Promise<void> {\n return loadSdkScript(src, 'data-joryio-editor');\n}\n\nexport class EditorGate {\n private opener: Window | null = null;\n private dashboardOrigin: string | null = null;\n private verifying = false;\n private session: { stop(): void } | null = null;\n private off: (() => void) | null = null;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private logger: Logger,\n private options: { scriptUrl?: string; load?: (src: string) => Promise<void> } = {},\n ) {}\n\n /** Step 1. Does nothing unless the dashboard's editor opened this tab. */\n start(): void {\n if (!editorRequested() || this.opener) return;\n this.opener = window.opener as Window;\n const onMessage = (e: MessageEvent) => void this.onMessage(e);\n window.addEventListener('message', onMessage);\n this.off = () => window.removeEventListener('message', onMessage);\n try {\n // No secret in it, so any target origin: the dashboard checks it came from the tab it opened.\n this.opener.postMessage({ type: EDITOR_MESSAGES.READY }, '*');\n } catch {\n /* the opener went away */\n }\n }\n\n isActive(): boolean {\n return !!this.session;\n }\n\n stop(): void {\n const session = this.session;\n this.session = null;\n session?.stop();\n this.off?.();\n this.off = null;\n this.dashboardOrigin = null;\n this.opener = null;\n }\n\n private async onMessage(e: MessageEvent): Promise<void> {\n const data = e.data as { type?: string; token?: string } | null;\n if (!data || typeof data.type !== 'string' || this.dashboardOrigin) return;\n if (data.type !== EDITOR_MESSAGES.TOKEN || e.source !== this.opener || typeof data.token !== 'string' || this.verifying) return;\n this.verifying = true;\n try {\n const res = await fetch(`${this.apiEndpoint}/v1/in-app/editor/verify`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey, ...sdkIdentityHeaders() },\n body: JSON.stringify({ token: data.token }),\n });\n const answer = res.ok ? await res.json() : null;\n // The token says which dashboard may talk to this tab; the message must have come from it.\n if (!answer?.valid || typeof answer.dashboardOrigin !== 'string' || answer.dashboardOrigin !== e.origin) {\n this.logger.warn('Joryio editor: the editor token was not accepted for this site');\n return;\n }\n this.dashboardOrigin = answer.dashboardOrigin;\n // The message listener of the handshake is done; the editor installs its own.\n this.off?.();\n this.off = null;\n await this.loadAndStart(answer.dashboardOrigin);\n } catch (error) {\n this.logger.debug('Joryio editor verification failed', error);\n } finally {\n this.verifying = false;\n }\n }\n\n /** Step 3: the bundle, only now. */\n private async loadAndStart(dashboardOrigin: string): Promise<void> {\n const load = this.options.load ?? loadScript;\n let api: EditorBundleApi | undefined = (window as any)[EDITOR_GLOBAL];\n for (const src of api ? [] : editorBundleUrls(this.options.scriptUrl)) {\n try {\n await load(src);\n api = (window as any)[EDITOR_GLOBAL];\n if (api) break;\n } catch (error) {\n this.logger.debug('Joryio editor bundle failed to load', error);\n }\n }\n if (!api || api.version !== EDITOR_API_VERSION || typeof api.start !== 'function' || !this.opener) {\n this.logger.warn('Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)');\n return;\n }\n this.session = api.start({ dashboardOrigin, opener: this.opener, logger: this.logger, onStop: () => this.stop() });\n }\n}\n","/**\n * The point-and-click picker (BACKLOG D444 Phase 4,\n * docs/PLACEMENTS_WEBSITE_LAYER.md 3) - the body of `joryio-editor.min.js`.\n *\n * The handshake lives in the core bundle (src/core/editor-gate.ts): this\n * file is loaded, and this class constructed, only once the server vouched\n * for the editor token, with the dashboard origin the token names. From then\n * on it accepts messages only from that origin and that opener window, and\n * posts only to them. It lets the person point at an element, computes a\n * robust selector, offers the operations that fit, and posts\n * `joryio:editor-pick` back.\n *\n * It reads the page the person already sees and writes nothing to it but its\n * own highlight and panel (built from text nodes, never HTML). No free-form\n * DOM editing: a pick is a selector + one of the five page-edit operations.\n */\nimport type { Logger } from '../utils/logger';\nimport { isSafeSelector, isSafeEditUrl, type PageEditOperation } from '../core/page-edits';\nimport { EDITOR_MESSAGES } from '../core/editor-gate';\n\nexport { EDITOR_MESSAGES };\n\n/** Attributes that name an element on purpose, most stable first. */\nconst NAMING_ATTRIBUTES = ['data-joryio-id', 'data-testid', 'data-test', 'data-qa', 'data-cy', 'data-id', 'name'];\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\n\n/** CSS.escape, for browsers (and test DOMs) without it. */\nexport function cssEscape(value: string): string {\n const css = (globalThis as any).CSS;\n if (css && typeof css.escape === 'function') return css.escape(value);\n let out = '';\n for (let i = 0; i < value.length; i++) {\n const ch = value[i];\n const code = value.charCodeAt(i);\n if (code === 0) out += '\\uFFFD';\n else if (/[0-9]/.test(ch) && (i === 0 || (i === 1 && value[0] === '-'))) out += `\\\\${code.toString(16)} `;\n else if (/[A-Za-z0-9_-]/.test(ch) || code >= 0x80) out += ch;\n else out += `\\\\${ch}`;\n }\n return out;\n}\n\nconst unique = (doc: Document, selector: string, el: Element): boolean => {\n try {\n const hits = doc.querySelectorAll(selector);\n return hits.length === 1 && hits[0] === el;\n } catch {\n return false;\n }\n};\n\n/** An id that looks generated (long digit runs, framework hashes) changes between builds; skip it. */\nconst stableId = (id: string) => !!id && id.length <= 64 && !/\\d{4,}/.test(id) && !/^(ember|react|radix|headlessui|mui)[-_:]/i.test(id) && !/:/.test(id);\n\n/**\n * A selector that finds this element and only it, preferring what the site\n * named on purpose: an id, then a naming data attribute, then a path of\n * tag + nth-of-type from the nearest named ancestor (or the body).\n */\nexport function robustSelector(el: Element): string | null {\n const doc = el.ownerDocument;\n if (!doc) return null;\n const named = (node: Element): string | null => {\n if (stableId(node.id)) {\n const s = `#${cssEscape(node.id)}`;\n if (unique(doc, s, node)) return s;\n }\n for (const attr of NAMING_ATTRIBUTES) {\n const v = node.getAttribute(attr);\n if (!v || v.length > 100) continue;\n const s = `${node.tagName.toLowerCase()}[${attr}=\"${v.replace(/[\"\\\\]/g, '\\\\$&')}\"]`;\n if (unique(doc, s, node)) return s;\n }\n return null;\n };\n const own = named(el);\n if (own) return isSafeSelector(own) ? own : null;\n const parts: string[] = [];\n let node: Element | null = el;\n while (node && node !== doc.body && node !== doc.documentElement) {\n const anchor = parts.length ? named(node) : null;\n if (anchor) {\n parts.unshift(anchor);\n break;\n }\n const tag = node.tagName.toLowerCase();\n const parent: Element | null = node.parentElement;\n const same = parent ? Array.from(parent.children).filter((c) => c.tagName === node!.tagName) : [];\n parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(node) + 1})` : tag);\n node = parent;\n if (node === doc.body) parts.unshift('body');\n }\n const selector = parts.join(' > ');\n return selector && isSafeSelector(selector) && unique(doc, selector, el) ? selector : null;\n}\n\n/** The operations that fit an element: an image can change its picture, a link its address. */\nexport function operationsFor(el: Element): PageEditOperation[] {\n const ops: PageEditOperation[] = [];\n if (el.tagName !== 'IMG' && (el.textContent || '').trim()) ops.push('replace_text');\n if (el.tagName === 'IMG') ops.push('replace_image');\n if (el.tagName === 'A') ops.push('replace_link');\n ops.push('hide', 'insert_placement');\n return ops;\n}\n\nexport interface EditorPick {\n type: typeof EDITOR_MESSAGES.PICK;\n selector: string;\n operation: PageEditOperation;\n value?: string;\n placementKey?: string;\n position?: 'before' | 'after' | 'prepend' | 'append';\n tag: string;\n text: string;\n}\n\nexport class VisualEditor {\n private listeners: Array<() => void> = [];\n private highlight: HTMLElement | null = null;\n private panel: HTMLElement | null = null;\n private selected: Element | null = null;\n private active = false;\n\n constructor(\n private dashboardOrigin: string,\n private opener: Window,\n private logger: Logger,\n private onStop: () => void = () => undefined,\n ) {}\n\n /** The token was vouched for by the server: show the picker. */\n start(): void {\n if (this.active) return;\n this.active = true;\n const onMessage = (e: MessageEvent) => {\n const data = e.data as { type?: string } | null;\n if (!data || typeof data.type !== 'string') return;\n if (e.origin !== this.dashboardOrigin || e.source !== this.opener) return;\n if (data.type === EDITOR_MESSAGES.CLOSE) this.stop();\n };\n window.addEventListener('message', onMessage);\n this.listeners.push(() => window.removeEventListener('message', onMessage));\n this.activate();\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n stop(): void {\n if (!this.active) return;\n this.send({ type: EDITOR_MESSAGES.CLOSED });\n this.active = false;\n for (const off of this.listeners.splice(0)) off();\n this.highlight?.remove();\n this.panel?.remove();\n this.highlight = this.panel = null;\n this.selected = null;\n try {\n this.onStop();\n } catch (error) {\n this.logger.debug('Joryio editor stop callback failed', error);\n }\n }\n\n private send(message: Record<string, unknown>): void {\n if (!this.active) return;\n try {\n this.opener.postMessage(message, this.dashboardOrigin);\n } catch {\n /* the dashboard tab closed */\n }\n }\n\n private activate(): void {\n const doc = document;\n const highlight = doc.createElement('div');\n highlight.setAttribute('data-joryio-editor', 'highlight');\n highlight.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483646;border:2px solid #14b8a6;background:rgba(20,184,166,.12);border-radius:3px;display:none';\n const panel = doc.createElement('div');\n panel.setAttribute('data-joryio-editor', 'panel');\n panel.style.cssText = 'position:fixed;left:16px;right:16px;bottom:16px;z-index:2147483647;max-width:560px;margin:0 auto;background:#0f172a;color:#fff;font:14px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:10px;box-shadow:0 8px 30px rgba(0,0,0,.3)';\n panel.textContent = 'Joryio editor - click an element on the page. Esc to finish.';\n doc.body.appendChild(highlight);\n doc.body.appendChild(panel);\n this.highlight = highlight;\n this.panel = panel;\n const inEditor = (t: EventTarget | null) => t instanceof Element && !!t.closest('[data-joryio-editor]');\n const onMove = (e: MouseEvent) => {\n if (this.selected || inEditor(e.target)) return;\n this.outline(e.target instanceof Element ? e.target : null);\n };\n const onClick = (e: MouseEvent) => {\n if (inEditor(e.target)) return;\n e.preventDefault();\n e.stopPropagation();\n if (e.target instanceof Element) this.select(e.target);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape') this.selected ? this.unselect() : this.stop();\n };\n doc.addEventListener('mousemove', onMove, true);\n doc.addEventListener('click', onClick, true);\n doc.addEventListener('keydown', onKey, true);\n this.listeners.push(\n () => doc.removeEventListener('mousemove', onMove, true),\n () => doc.removeEventListener('click', onClick, true),\n () => doc.removeEventListener('keydown', onKey, true),\n );\n this.send({ type: EDITOR_MESSAGES.ACTIVE, url: `${location.origin}${location.pathname}` });\n }\n\n private outline(el: Element | null): void {\n if (!this.highlight) return;\n if (!el || el === document.body || el === document.documentElement) {\n this.highlight.style.display = 'none';\n return;\n }\n const r = el.getBoundingClientRect();\n Object.assign(this.highlight.style, { display: 'block', top: `${r.top}px`, left: `${r.left}px`, width: `${r.width}px`, height: `${r.height}px` });\n }\n\n private unselect(): void {\n this.selected = null;\n if (this.panel) this.panel.textContent = 'Joryio editor - click an element on the page. Esc to finish.';\n }\n\n /** The element is chosen: its selector and the operations that fit it, as buttons. */\n select(el: Element): void {\n const selector = robustSelector(el);\n if (!this.panel) return;\n if (!selector) {\n this.panel.textContent = 'This element has no stable selector. Choose its parent or another element.';\n return;\n }\n this.selected = el;\n this.outline(el);\n const panel = this.panel;\n panel.textContent = '';\n const line = (text: string, mono = false) => {\n const p = document.createElement('div');\n p.textContent = text;\n if (mono) p.style.cssText = 'font-family:ui-monospace,monospace;font-size:12px;opacity:.8;word-break:break-all;margin:4px 0 8px';\n panel.appendChild(p);\n };\n line(`<${el.tagName.toLowerCase()}> ${(el.textContent || '').trim().slice(0, 60)}`);\n line(selector, true);\n const input = document.createElement('input');\n input.setAttribute('data-joryio-editor', 'value');\n input.style.cssText = 'width:100%;box-sizing:border-box;padding:6px 8px;border-radius:6px;border:0;margin-bottom:8px;color:#0f172a';\n input.placeholder = 'New text, https:// address or placement key';\n panel.appendChild(input);\n const row = document.createElement('div');\n row.style.cssText = 'display:flex;flex-wrap:wrap;gap:6px';\n const labels: Record<PageEditOperation, string> = {\n replace_text: 'Replace text',\n replace_image: 'Replace image',\n replace_link: 'Replace link',\n hide: 'Hide',\n insert_placement: 'Insert placement after',\n };\n for (const op of operationsFor(el)) {\n const b = document.createElement('button');\n b.type = 'button';\n b.textContent = labels[op];\n b.setAttribute('data-joryio-op', op);\n b.style.cssText = 'padding:6px 10px;border-radius:6px;border:0;background:#14b8a6;color:#fff;cursor:pointer';\n b.addEventListener('click', (e) => {\n e.preventDefault();\n e.stopPropagation();\n this.pick(el, selector, op, input.value.trim());\n });\n row.appendChild(b);\n }\n panel.appendChild(row);\n }\n\n /** Validate like the server does, then hand the pick to the dashboard. */\n pick(el: Element, selector: string, operation: PageEditOperation, value: string): boolean {\n const base: EditorPick = { type: EDITOR_MESSAGES.PICK, selector, operation, tag: el.tagName.toLowerCase(), text: (el.textContent || '').trim().slice(0, 200) };\n let msg: EditorPick | null = null;\n if (operation === 'hide') msg = base;\n else if (operation === 'replace_text') msg = value || base.text ? { ...base, value: (value || base.text).slice(0, 2000) } : null;\n else if (operation === 'replace_image' || operation === 'replace_link') msg = isSafeEditUrl(value) ? { ...base, value } : null;\n else if (operation === 'insert_placement') msg = PLACEMENT_KEY_PATTERN.test(value) ? { ...base, placementKey: value, position: 'after' } : null;\n if (!msg) {\n if (this.panel) {\n const warn = document.createElement('div');\n warn.style.cssText = 'margin-top:6px;color:#fca5a5';\n warn.textContent =\n operation === 'insert_placement' ? 'Enter a placement key (lowercase letters, digits, _).' : 'Enter an address starting with https:// (or http://).';\n this.panel.appendChild(warn);\n }\n return false;\n }\n this.send(msg as unknown as Record<string, unknown>);\n this.unselect();\n return true;\n }\n}\n","/**\n * The visual editor bundle - `joryio-editor.min.js` on the SDK host, next to\n * `joryio.min.js` (BACKLOG D444 Phase 4 follow-up).\n *\n * Loaded by the core's EditorGate (src/core/editor-gate.ts) only in a tab the\n * Joryio dashboard opened for the point-and-click editor, and only after the\n * server vouched for the editor token. It registers one global and does\n * nothing else on its own: no request, no listener, until the gate calls\n * `start` with the verified dashboard origin.\n */\nimport { VisualEditor } from './visual-editor';\nimport { EDITOR_API_VERSION, EDITOR_GLOBAL, type EditorBundleApi } from '../core/editor-gate';\n\nconst api: EditorBundleApi = {\n version: EDITOR_API_VERSION,\n start({ dashboardOrigin, opener, logger, onStop }) {\n const editor = new VisualEditor(dashboardOrigin, opener, logger, onStop);\n editor.start();\n return { stop: () => editor.stop() };\n },\n};\n\nif (typeof window !== 'undefined' && !(window as any)[EDITOR_GLOBAL]) {\n (window as any)[EDITOR_GLOBAL] = api;\n}\n\nexport { api as editorApi };\n"],"names":["isSafeSelector","selector","s","trim","length","test","includes","document","createDocumentFragment","querySelector","_a","CORE_FILE","coreFolderOf","src","u","URL","protocol","pathname","origin","replace","current","currentScript","fromCurrent","tags","querySelectorAll","i","folder","readOwnFolder","EDITOR_GLOBAL","NAMING_ATTRIBUTES","PLACEMENT_KEY_PATTERN","unique","doc","el","hits","VisualEditor","constructor","dashboardOrigin","opener","logger","onStop","this","listeners","highlight","panel","selected","active","start","onMessage","e","data","type","source","stop","window","addEventListener","push","removeEventListener","activate","isActive","send","off","splice","remove","_b","error","debug","message","postMessage","createElement","setAttribute","style","cssText","textContent","body","appendChild","inEditor","t","Element","closest","onMove","target","outline","onClick","preventDefault","stopPropagation","select","onKey","key","unselect","url","location","documentElement","display","r","getBoundingClientRect","Object","assign","top","left","width","height","ownerDocument","named","node","id","value","css","globalThis","CSS","escape","out","ch","code","charCodeAt","toString","cssEscape","attr","v","getAttribute","tagName","toLowerCase","own","parts","anchor","unshift","tag","parent","parentElement","same","Array","from","children","filter","c","indexOf","join","robustSelector","line","text","mono","p","slice","input","placeholder","row","labels","replace_text","replace_image","replace_link","hide","insert_placement","op","ops","operationsFor","b","pick","operation","base","msg","isSafeEditUrl","placementKey","position","warn","api","version","editor"],"mappings":";;;;;yBAoPM,SAAUA,EAAeC,GAC7B,GAAwB,iBAAbA,EAAuB,OAAO,EACzC,MAAMC,EAAID,EAASE,OACnB,IAAKD,GAAKA,EAAEE,OA/Lc,IA+LgB,OAAO,EACjD,GAAI,UAAUC,KAAKH,IAAMA,EAAEI,SAAS,OAASJ,EAAEI,SAAS,MAAO,OAAO,EAEtE,GAAI,wBAAwBD,KAAKH,GAAI,OAAO,EAC5C,IAC0B,oBAAbK,UAA0BA,SAASC,yBAAyBC,cAAcP,EACvF,CAAE,MAAAQ,GACA,OAAO,CACT,CACA,OAAO,CACT,CCrPA,MAAMC,EAAY,oCAQZ,SAAUC,EAAaC,GAC3B,IAAKA,GAAsB,iBAARA,EAAkB,OAAO,KAC5C,IAAIC,EACJ,IACEA,EAAI,IAAIC,IAAIF,EACd,CAAE,MAAAH,GACA,OAAO,IACT,CACA,MAAmB,WAAfI,EAAEE,UAA0BL,EAAUN,KAAKS,EAAEG,UAC1C,GAAGH,EAAEI,SAASJ,EAAEG,SAASE,QAAQ,SAAU,MADiB,IAErE,EAOA,WACE,GAAwB,oBAAbZ,S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D,IAAkCE,EAAMjI,EAAsBzB,KAAKqG,GAAQV,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAM6D,IAAMG,aAAcvD,EAAOwD,SAAU,UAAY,OACtIH,EAAK,CACR,GAAItH,KAAKG,MAAO,CACd,MAAMuH,EAAO5J,SAAS8D,cAAc,OACpC8F,EAAK5F,MAAMC,QAAU,+BACrB2F,EAAK1F,YACW,qBAAdoF,EAAmC,wDAA0D,wDAC/FpH,KAAKG,MAAM+B,YAAYwF,EACzB,CACA,OAAO,CACT,CAGA,OAFA1H,KAAKmB,KAAKmG,GACVtH,KAAKgD,YACE,CACT,EC9RF,MAAM2E,EAAuB,CAC3BC,QFqBgC,EEpBhC,KAAAtH,EAAMV,gBAAEA,EAAeC,OAAEA,EAAMC,OAAEA,EAAMC,OAAEA,IACvC,MAAM8H,EAAS,IAAInI,EAAaE,EAAiBC,EAAQC,EAAQC,GAEjE,OADA8H,EAAOvH,QACA,CAAEM,KAAM,IAAMiH,EAAOjH,OAC9B,GAGoB,oBAAXC,QAA4BA,OAAe1B,KACnD0B,OAAe1B,GAAiBwI"}
package/dist/joryio-sw.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.1
2
+ * Joryio Web SDK v1.4.0-beta.4
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
  */