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

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 (71) hide show
  1. package/CHANGELOG.md +46 -0
  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 +131 -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 +74 -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 +219 -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 +37 -0
  31. package/dist/core/sdk.d.ts.map +1 -1
  32. package/dist/core/subscription.d.ts +6 -0
  33. package/dist/core/subscription.d.ts.map +1 -0
  34. package/dist/editor/index.d.ts +4 -0
  35. package/dist/editor/index.d.ts.map +1 -0
  36. package/dist/editor/visual-editor.d.ts +39 -0
  37. package/dist/editor/visual-editor.d.ts.map +1 -0
  38. package/dist/index.d.mts +206 -3
  39. package/dist/index.d.ts +9 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/joryio-cards-ui.min.js +7 -0
  42. package/dist/joryio-cards-ui.min.js.map +1 -0
  43. package/dist/joryio-editor.min.js +7 -0
  44. package/dist/joryio-editor.min.js.map +1 -0
  45. package/dist/joryio-sw.js +1 -1
  46. package/dist/joryio.cjs.js +7215 -3508
  47. package/dist/joryio.min.js +2 -2
  48. package/dist/joryio.min.js.map +1 -1
  49. package/dist/joryio.mjs +7207 -3509
  50. package/dist/joryio.umd.js +7214 -3507
  51. package/package.json +4 -1
  52. package/src/cards-ui/card-feed-view.ts +249 -0
  53. package/src/cards-ui/index.ts +26 -0
  54. package/src/core/cards-ui-contract.ts +58 -0
  55. package/src/core/cards.ts +846 -0
  56. package/src/core/config.ts +86 -2
  57. package/src/core/editor-gate.ts +158 -0
  58. package/src/core/flags.ts +378 -0
  59. package/src/core/inapp.ts +283 -152
  60. package/src/core/links.ts +104 -0
  61. package/src/core/network.ts +3 -0
  62. package/src/core/page-context.ts +460 -0
  63. package/src/core/page-edits.ts +1036 -0
  64. package/src/core/placements.ts +1434 -0
  65. package/src/core/sdk-host-files.ts +93 -0
  66. package/src/core/sdk.ts +383 -1
  67. package/src/core/subscription.ts +27 -0
  68. package/src/editor/index.ts +27 -0
  69. package/src/editor/visual-editor.ts +301 -0
  70. package/src/index.ts +35 -0
  71. package/src/snippet/loader.js +25 -1
@@ -2,7 +2,23 @@
2
2
  * SDK Configuration Types and Defaults
3
3
  */
4
4
 
5
- export const SDK_VERSION = '1.4.0'; // keep in sync with package.json — the backend serves this in X-SDK-Version headers
5
+ export const SDK_VERSION = '1.4.0'; // keep in sync with package.json (sdk-version-parity.spec.ts pins it)
6
+
7
+ /**
8
+ * Sent on EVERY request to the API, so the dashboard can show which SDK
9
+ * version each app runs and when a newer one is out (D427). Same wire names
10
+ * on all five SDKs: `X-Joryio-SDK` is the platform (the header the backend's
11
+ * SDK-key guard and bot detection already read), `X-Joryio-SDK-Version` this
12
+ * build's version. The web SDK has no bridge, so it never sends
13
+ * `X-Joryio-SDK-Wrapper`. The public SDK routes allow these in CORS.
14
+ */
15
+ export const SDK_PLATFORM_HEADER = 'X-Joryio-SDK';
16
+ export const SDK_VERSION_HEADER = 'X-Joryio-SDK-Version';
17
+ export const SDK_PLATFORM = 'web';
18
+
19
+ export function sdkIdentityHeaders(): Record<string, string> {
20
+ return { [SDK_PLATFORM_HEADER]: SDK_PLATFORM, [SDK_VERSION_HEADER]: SDK_VERSION };
21
+ }
6
22
  export const DEFAULT_API_ENDPOINT = 'https://api-eu1.joryio.com/api';
7
23
 
8
24
  /**
@@ -110,6 +126,13 @@ export interface InAppOptions {
110
126
  */
111
127
  allowHtmlJsInAppMessages?: boolean;
112
128
 
129
+ /**
130
+ * Fill every `<div data-joryio-placement="key">` on the page (and those added
131
+ * later) with its placement. On by default; off = only insertPlacement()
132
+ * draws. Placements work whether or not overlays (`enabled`) are on.
133
+ */
134
+ autoMountPlacements?: boolean;
135
+
113
136
  // Callback hooks
114
137
  onMessageDisplay?: (message: any) => void;
115
138
  onMessageClick?: (message: any, action: string) => void;
@@ -121,6 +144,48 @@ export interface InitConfig {
121
144
  // Required
122
145
  sdkKey: string;
123
146
 
147
+ /**
148
+ * Page context for targeting (D444 Phase 4): what the SDK may report about
149
+ * the page besides its URL (origin + path, never the query string). Nothing
150
+ * is read that is not listed here. Set the page's own variables with
151
+ * `setPageVariables()`.
152
+ */
153
+ pageContext?: {
154
+ /** Global variables to report, by name (`pageType`, `shop.page.type`). */
155
+ pageVariables?: string[];
156
+ /** dataLayer keys to report (`pageType`, `ecommerce.value`): the latest pushed value of each. */
157
+ dataLayerVariables?: string[];
158
+ /** The dataLayer array's global name. Default `dataLayer`. */
159
+ dataLayerName?: string;
160
+ };
161
+
162
+ /**
163
+ * Page edits on this site (D444 Phase 4). Default on: the SDK applies the
164
+ * page edits Joryio sends and opens the point-and-click editor when the
165
+ * dashboard asks. `false`: it never applies a page edit, never holds an
166
+ * element back and never loads the editor - whatever the server says.
167
+ * (Workspace-wide: Settings -> Placements -> Allow page edits on this website.)
168
+ */
169
+ pageEdits?: boolean;
170
+
171
+ /**
172
+ * Where the point-and-click editor's file is loaded from. Default: the
173
+ * folder `joryio.min.js` itself was loaded from (a beta at
174
+ * `sdk.joryio.com/web/1.4.0-beta.4/`, the npm package's `dist/` on a CDN),
175
+ * then the SDK host (`https://sdk.joryio.com/web/<version>/joryio-editor.min.js`,
176
+ * then `/web/<major>/`). Set it only when you host the SDK files yourself.
177
+ */
178
+ editorScriptUrl?: string;
179
+
180
+ /**
181
+ * Where the default card feed's file (`mountCardFeed`) is loaded from.
182
+ * Default: the folder `joryio.min.js` itself was loaded from, then the SDK
183
+ * host (`https://sdk.joryio.com/web/<version>/joryio-cards-ui.min.js`, then
184
+ * `/web/<major>/`), the first time the page mounts a feed. Set it only when
185
+ * you host the SDK files yourself.
186
+ */
187
+ cardsUiScriptUrl?: string;
188
+
124
189
  // API Configuration
125
190
  apiEndpoint?: string;
126
191
 
@@ -230,14 +295,19 @@ export interface InitConfig {
230
295
  plugins?: Array<Plugin>;
231
296
  }
232
297
 
233
- export interface ResolvedConfig extends Required<Omit<InitConfig, 'userId' | 'plugins' | 'inApp' | 'sdkAuthenticationToken' | 'trackingConsent' | 'webPush' | 'storefrontIdentityToken' | 'storefrontIdentityTokenProvider'>> {
298
+ export interface ResolvedConfig extends Required<Omit<InitConfig, 'userId' | 'plugins' | 'inApp' | 'pageContext' | 'sdkAuthenticationToken' | 'trackingConsent' | 'webPush' | 'storefrontIdentityToken' | 'storefrontIdentityTokenProvider' | 'editorScriptUrl' | 'cardsUiScriptUrl'>> {
234
299
  userId?: string;
300
+ /** Undefined = the SDK host (see InitConfig.editorScriptUrl). */
301
+ editorScriptUrl?: string;
302
+ /** Undefined = the SDK host (see InitConfig.cardsUiScriptUrl). */
303
+ cardsUiScriptUrl?: string;
235
304
  /** Undefined = not set by the app (see InitConfig.webPush). */
236
305
  webPush?: boolean;
237
306
  /** Undefined = not set by the app (see InitConfig.trackingConsent). */
238
307
  trackingConsent?: 'granted' | 'denied' | 'pending';
239
308
  plugins: Array<Plugin>;
240
309
  inApp: Required<InAppOptions>;
310
+ pageContext: { pageVariables: string[]; dataLayerVariables: string[]; dataLayerName: string };
241
311
  // Optional — absent until the host app supplies a token.
242
312
  sdkAuthenticationToken?: string;
243
313
  storefrontIdentityToken?: string;
@@ -354,6 +424,7 @@ export function resolveConfig(config: InitConfig): ResolvedConfig {
354
424
  zIndex: config.inApp?.displayOptions?.zIndex || 999999,
355
425
  },
356
426
  allowHtmlJsInAppMessages: config.inApp?.allowHtmlJsInAppMessages === true,
427
+ autoMountPlacements: config.inApp?.autoMountPlacements !== false,
357
428
  onMessageDisplay: config.inApp?.onMessageDisplay || (() => {}),
358
429
  onMessageClick: config.inApp?.onMessageClick || (() => {}),
359
430
  onMessageDismiss: config.inApp?.onMessageDismiss || (() => {}),
@@ -379,6 +450,19 @@ export function resolveConfig(config: InitConfig): ResolvedConfig {
379
450
  trackPageProperties: config.trackPageProperties !== false,
380
451
  trackDeviceProperties: config.trackDeviceProperties !== false,
381
452
  inApp: inAppOptions,
453
+ pageContext: {
454
+ pageVariables: Array.isArray(config.pageContext?.pageVariables) ? config.pageContext!.pageVariables.filter((v) => typeof v === 'string') : [],
455
+ dataLayerVariables: Array.isArray(config.pageContext?.dataLayerVariables)
456
+ ? config.pageContext!.dataLayerVariables.filter((v) => typeof v === 'string')
457
+ : [],
458
+ dataLayerName:
459
+ typeof config.pageContext?.dataLayerName === 'string' && /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(config.pageContext.dataLayerName)
460
+ ? config.pageContext.dataLayerName
461
+ : 'dataLayer',
462
+ },
463
+ pageEdits: config.pageEdits !== false,
464
+ editorScriptUrl: typeof config.editorScriptUrl === 'string' && /^https:\/\//i.test(config.editorScriptUrl) ? config.editorScriptUrl : undefined,
465
+ cardsUiScriptUrl: typeof config.cardsUiScriptUrl === 'string' && /^https:\/\//i.test(config.cardsUiScriptUrl) ? config.cardsUiScriptUrl : undefined,
382
466
  // Tri-state on purpose: unset ("decide from this browser") is not `false`.
383
467
  webPush: config.webPush === true ? true : config.webPush === false ? false : undefined,
384
468
  persistQueue: config.persistQueue !== false,
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The point-and-click editor's door in the core bundle (BACKLOG D444 Phase 4,
3
+ * docs/PLACEMENTS_WEBSITE_LAYER.md 3).
4
+ *
5
+ * The visual editor itself (highlight, panel, selector computation) is a
6
+ * separate file, `joryio-editor.min.js`, served from the same SDK host next to
7
+ * `joryio.min.js`, so the ~every-visitor bundle carries only this handshake:
8
+ *
9
+ * 1. only when the tab was opened with `?joryio_editor=1` AND by another
10
+ * window (`window.opener`) AND page edits are not switched off in the
11
+ * site's code (`pageEdits: false`), post `joryio:editor-ready` to the
12
+ * opener (no secret in it);
13
+ * 2. accept `joryio:editor-token` only from that opener window, and check
14
+ * the token with `POST /v1/in-app/editor/verify`, which answers the
15
+ * dashboard origin it was minted for (bound to this site's origin and
16
+ * this SDK key's workspace; refused when page edits are off);
17
+ * 3. only then load the editor bundle and hand it the verified dashboard
18
+ * origin and the opener. Nothing is loaded for any other visitor.
19
+ */
20
+ import type { Logger } from '../utils/logger';
21
+ import { sdkIdentityHeaders } from './config';
22
+ import { loadSdkScript, sdkHostFileUrls } from './sdk-host-files';
23
+
24
+ export const EDITOR_QUERY_FLAG = 'joryio_editor';
25
+ export const EDITOR_MESSAGES = {
26
+ READY: 'joryio:editor-ready',
27
+ TOKEN: 'joryio:editor-token',
28
+ ACTIVE: 'joryio:editor-active',
29
+ PICK: 'joryio:editor-pick',
30
+ CLOSE: 'joryio:editor-close',
31
+ CLOSED: 'joryio:editor-closed',
32
+ } as const;
33
+
34
+ /** The global the editor bundle registers itself under, and the contract version between the two files. */
35
+ export const EDITOR_GLOBAL = '__joryioEditor';
36
+ export const EDITOR_API_VERSION = 1;
37
+ /** The file next to joryio.min.js on the SDK host. */
38
+ export const EDITOR_BUNDLE_FILE = 'joryio-editor.min.js';
39
+
40
+ export interface EditorBundleApi {
41
+ version: number;
42
+ start(ctx: { dashboardOrigin: string; opener: Window; logger: Logger; onStop: () => void }): { stop(): void };
43
+ }
44
+
45
+ /**
46
+ * Where the editor bundle is loaded from: the exact SDK version's folder on
47
+ * the SDK host, then the major channel (see sdkHostFileUrls).
48
+ * `editorScriptUrl` (init) replaces both, for a self-hosted SDK.
49
+ */
50
+ export function editorBundleUrls(override?: string): string[] {
51
+ return sdkHostFileUrls(EDITOR_BUNDLE_FILE, override);
52
+ }
53
+
54
+ /** True when this tab was opened by the dashboard's editor (the flag and an opener). */
55
+ export function editorRequested(): boolean {
56
+ try {
57
+ return typeof window !== 'undefined' && !!window.opener && new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) === '1';
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+
63
+ function loadScript(src: string): Promise<void> {
64
+ return loadSdkScript(src, 'data-joryio-editor');
65
+ }
66
+
67
+ export class EditorGate {
68
+ private opener: Window | null = null;
69
+ private dashboardOrigin: string | null = null;
70
+ private verifying = false;
71
+ private session: { stop(): void } | null = null;
72
+ private off: (() => void) | null = null;
73
+
74
+ constructor(
75
+ private apiEndpoint: string,
76
+ private sdkKey: string,
77
+ private logger: Logger,
78
+ private options: { scriptUrl?: string; load?: (src: string) => Promise<void> } = {},
79
+ ) {}
80
+
81
+ /** Step 1. Does nothing unless the dashboard's editor opened this tab. */
82
+ start(): void {
83
+ if (!editorRequested() || this.opener) return;
84
+ this.opener = window.opener as Window;
85
+ const onMessage = (e: MessageEvent) => void this.onMessage(e);
86
+ window.addEventListener('message', onMessage);
87
+ this.off = () => window.removeEventListener('message', onMessage);
88
+ try {
89
+ // No secret in it, so any target origin: the dashboard checks it came from the tab it opened.
90
+ this.opener.postMessage({ type: EDITOR_MESSAGES.READY }, '*');
91
+ } catch {
92
+ /* the opener went away */
93
+ }
94
+ }
95
+
96
+ isActive(): boolean {
97
+ return !!this.session;
98
+ }
99
+
100
+ stop(): void {
101
+ const session = this.session;
102
+ this.session = null;
103
+ session?.stop();
104
+ this.off?.();
105
+ this.off = null;
106
+ this.dashboardOrigin = null;
107
+ this.opener = null;
108
+ }
109
+
110
+ private async onMessage(e: MessageEvent): Promise<void> {
111
+ const data = e.data as { type?: string; token?: string } | null;
112
+ if (!data || typeof data.type !== 'string' || this.dashboardOrigin) return;
113
+ if (data.type !== EDITOR_MESSAGES.TOKEN || e.source !== this.opener || typeof data.token !== 'string' || this.verifying) return;
114
+ this.verifying = true;
115
+ try {
116
+ const res = await fetch(`${this.apiEndpoint}/v1/in-app/editor/verify`, {
117
+ method: 'POST',
118
+ headers: { 'Content-Type': 'application/json', 'X-SDK-Key': this.sdkKey, ...sdkIdentityHeaders() },
119
+ body: JSON.stringify({ token: data.token }),
120
+ });
121
+ const answer = res.ok ? await res.json() : null;
122
+ // The token says which dashboard may talk to this tab; the message must have come from it.
123
+ if (!answer?.valid || typeof answer.dashboardOrigin !== 'string' || answer.dashboardOrigin !== e.origin) {
124
+ this.logger.warn('Joryio editor: the editor token was not accepted for this site');
125
+ return;
126
+ }
127
+ this.dashboardOrigin = answer.dashboardOrigin;
128
+ // The message listener of the handshake is done; the editor installs its own.
129
+ this.off?.();
130
+ this.off = null;
131
+ await this.loadAndStart(answer.dashboardOrigin);
132
+ } catch (error) {
133
+ this.logger.debug('Joryio editor verification failed', error);
134
+ } finally {
135
+ this.verifying = false;
136
+ }
137
+ }
138
+
139
+ /** Step 3: the bundle, only now. */
140
+ private async loadAndStart(dashboardOrigin: string): Promise<void> {
141
+ const load = this.options.load ?? loadScript;
142
+ let api: EditorBundleApi | undefined = (window as any)[EDITOR_GLOBAL];
143
+ for (const src of api ? [] : editorBundleUrls(this.options.scriptUrl)) {
144
+ try {
145
+ await load(src);
146
+ api = (window as any)[EDITOR_GLOBAL];
147
+ if (api) break;
148
+ } catch (error) {
149
+ this.logger.debug('Joryio editor bundle failed to load', error);
150
+ }
151
+ }
152
+ if (!api || api.version !== EDITOR_API_VERSION || typeof api.start !== 'function' || !this.opener) {
153
+ this.logger.warn('Joryio editor: the editor could not be loaded (check that your Content-Security-Policy allows sdk.joryio.com)');
154
+ return;
155
+ }
156
+ this.session = api.start({ dashboardOrigin, opener: this.opener, logger: this.logger, onStop: () => this.stop() });
157
+ }
158
+ }
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Feature flags + remote config (Joryio BACKLOG D446).
3
+ *
4
+ * - `getFlag(key, default)` and the typed getters read the answer held on the
5
+ * device; they never wait for the network. Before the first answer, for a
6
+ * flag the server did not send, or for a value of the wrong type, they return
7
+ * the in-code default.
8
+ * - Nothing is fetched until the app uses flags (the first getter, getAllFlags,
9
+ * refreshFlags or onFlagsUpdated on this device), so a site that never reads
10
+ * a flag costs no request. From then on the answer (`POST /v1/flags/evaluate`,
11
+ * every active flag in one call) is
12
+ * kept in localStorage for the same visitor, and refreshed on start, when the
13
+ * page becomes visible again (at most once per FLAGS_MIN_REFRESH_SECONDS), on
14
+ * identify / reset, and on `refreshFlags()`. Browsers have no silent push
15
+ * (every web push must show a notification), so `jry_sync: "flags"` does not
16
+ * apply on the web.
17
+ * - An exposure (`flag.exposure`) is logged the first time a value is read in
18
+ * a session: once per flag and variant per session, unless the answer said
19
+ * `logExposure: false` (server-side sampling). The server re-evaluates every
20
+ * exposure, so only real assignments count.
21
+ * - Without tracking consent nothing is sent: no request names the visitor,
22
+ * no exposure is logged, and the getters return the in-code default.
23
+ *
24
+ * The same names and wire values on all five SDKs.
25
+ */
26
+ import { JoryioSubscription, joryioSubscription } from './subscription';
27
+ import { Logger } from '../utils/logger';
28
+ import { bucketHash } from '../utils/bucket-hash';
29
+ import { sdkIdentityHeaders } from './config';
30
+ import { IdentityManager } from './identity';
31
+ import { SessionManager } from './session';
32
+
33
+ /** A refresh asked for within this many seconds of the last one is skipped (start, identify and refreshFlags() always go). */
34
+ export const FLAGS_MIN_REFRESH_SECONDS = 60;
35
+ /** Exposures are sent in one request this long after the first read. */
36
+ export const FLAG_EXPOSURE_FLUSH_MS = 1000;
37
+ /** The silent-push value that refreshes flags on the native SDKs (not applicable on the web). */
38
+ export const FLAG_SYNC_PUSH_VALUE = 'flags';
39
+
40
+ export type FlagValueType = 'boolean' | 'string' | 'number' | 'json';
41
+ /**
42
+ * Why the person got this value - the server's wire value, passed to the app
43
+ * unchanged. `override`: a journey's Feature flag step set it for them.
44
+ * `experiment`: an arm of a running feature flag experiment campaign (its
45
+ * holdout is `holdout`). Same list as the backend FLAG_REASONS.
46
+ */
47
+ export type FlagReason = 'off' | 'rule' | 'default' | 'holdout' | 'archived' | 'override' | 'experiment';
48
+
49
+ /** One flag as the server sent it. */
50
+ export interface FlagResult {
51
+ value: unknown;
52
+ variant: string;
53
+ valueType: FlagValueType;
54
+ reason: FlagReason;
55
+ version: number;
56
+ logExposure: boolean;
57
+ }
58
+
59
+ export type FlagsUpdatedCallback = (changedKeys: string[]) => void;
60
+
61
+ interface FlagsAuth {
62
+ getSdkAuthHeaders(subjectUserId?: string | null, anonymousId?: string | null): Record<string, string>;
63
+ }
64
+
65
+ interface FlagsRuntime {
66
+ /** true when the SDK may send (initialized, consent granted, not suspended). */
67
+ canSend: () => boolean;
68
+ requestTimeoutMs?: number;
69
+ noteStatus?: (status: number, data: unknown) => void;
70
+ /** Attributes the app set on this device, matched by attribute rules. */
71
+ attributes?: () => Record<string, unknown>;
72
+ }
73
+
74
+ interface Stored {
75
+ subject: string;
76
+ etag: string;
77
+ fetchedAt: number;
78
+ flags: Record<string, FlagResult>;
79
+ }
80
+
81
+ /**
82
+ * The cached answer is per workspace: the key carries a hash of the SDK key
83
+ * (the same hash the StorageManager prefixes every other key with), so two
84
+ * workspaces on one origin - which may know the same person by the same
85
+ * external id - never read each other's flags. The unscoped key of builds
86
+ * before 2026-11-21 is never read; it is removed on the first load.
87
+ */
88
+ const LEGACY_STORAGE_KEY = 'jry_flags';
89
+ export const flagsStorageKey = (sdkKey: string): string => `jry_flags_${bucketHash(sdkKey).toString(36)}`;
90
+ const nowMs = () => Date.now();
91
+
92
+ export class FlagsManager {
93
+ private flags: Record<string, FlagResult> = {};
94
+ private etag = '';
95
+ private fetchedAt = 0;
96
+ private generation = 0;
97
+ private inflight: Promise<void> | null = null;
98
+ private inflightGeneration = 0;
99
+ private listeners = new Set<FlagsUpdatedCallback>();
100
+ /** `<sessionId>|<person>|<flag>|<variant>` already reported this session. */
101
+ private exposed = new Set<string>();
102
+ /**
103
+ * Exposures waiting to be sent, each batch with the identity it was read
104
+ * under (who, session, attributes, generation) - captured when the first
105
+ * exposure of the batch was queued. A batch is always sent as the person who
106
+ * read the values, never as whoever is identified when the timer fires.
107
+ */
108
+ private pending: { body: Record<string, unknown>; generation: number; exposures: Array<{ key: string; variant: string }> } | null = null;
109
+ private flushTimer: ReturnType<typeof setTimeout> | null = null;
110
+ /** The app reads flags on this device (a stored answer, or a call this page). */
111
+ private used = false;
112
+ private onVisible = () => {
113
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') void this.refresh(false);
114
+ };
115
+
116
+ constructor(
117
+ private readonly apiEndpoint: string,
118
+ private readonly sdkKey: string,
119
+ private readonly identity: IdentityManager,
120
+ private readonly session: SessionManager,
121
+ private readonly logger: Logger,
122
+ private readonly runtime: FlagsRuntime,
123
+ private readonly auth?: FlagsAuth | null,
124
+ ) {
125
+ this.load();
126
+ }
127
+
128
+ /** Start: read the stored answer, refresh it, and refresh again when the page is shown. */
129
+ start(): void {
130
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', this.onVisible);
131
+ if (this.used) void this.refresh(true);
132
+ }
133
+
134
+ /** The first use on a page that had no stored answer fetches one (the getter itself returns at once). */
135
+ private use(): void {
136
+ if (this.used) return;
137
+ this.used = true;
138
+ void this.refresh(true);
139
+ }
140
+
141
+ destroy(): void {
142
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', this.onVisible);
143
+ if (this.flushTimer) clearTimeout(this.flushTimer);
144
+ this.flushTimer = null;
145
+ this.listeners.clear();
146
+ }
147
+
148
+ /** The visitor or consent changed: the held answer belongs to someone else. */
149
+ onIdentityChanged(): void {
150
+ this.generation++;
151
+ // The batch carries its own snapshot, so it still goes as the previous person.
152
+ this.flush();
153
+ const before = Object.keys(this.flags);
154
+ this.flags = {};
155
+ this.etag = '';
156
+ this.fetchedAt = 0;
157
+ this.save();
158
+ if (before.length) this.emit(before);
159
+ if (this.used) void this.refresh(true);
160
+ }
161
+
162
+ getFlag<T = unknown>(key: string, defaultValue: T): T {
163
+ const f = this.read(key);
164
+ return f ? (f.value as T) : defaultValue;
165
+ }
166
+
167
+ getBoolFlag(key: string, defaultValue: boolean): boolean {
168
+ const f = this.read(key, 'boolean');
169
+ return f && typeof f.value === 'boolean' ? f.value : defaultValue;
170
+ }
171
+
172
+ getStringFlag(key: string, defaultValue: string): string {
173
+ const f = this.read(key, 'string');
174
+ return f && typeof f.value === 'string' ? f.value : defaultValue;
175
+ }
176
+
177
+ getNumberFlag(key: string, defaultValue: number): number {
178
+ const f = this.read(key, 'number');
179
+ return f && typeof f.value === 'number' ? f.value : defaultValue;
180
+ }
181
+
182
+ getJsonFlag<T = unknown>(key: string, defaultValue: T): T {
183
+ const f = this.read(key, 'json');
184
+ return f ? (f.value as T) : defaultValue;
185
+ }
186
+
187
+ /** Every flag the device holds, as key -> value. Reading them all logs no exposure. */
188
+ getAllFlags(): Record<string, unknown> {
189
+ if (!this.runtime.canSend()) return {};
190
+ this.use();
191
+ const out: Record<string, unknown> = {};
192
+ for (const [k, f] of Object.entries(this.flags)) out[k] = f.value;
193
+ return out;
194
+ }
195
+
196
+ /** Ask the server now (always goes, unlike the automatic refreshes). */
197
+ async refreshFlags(): Promise<void> {
198
+ this.used = true;
199
+ await this.refresh(true);
200
+ }
201
+
202
+ /** Called with the keys whose value changed. Returns a JoryioSubscription. */
203
+ onFlagsUpdated(callback: FlagsUpdatedCallback): JoryioSubscription {
204
+ if (typeof callback !== 'function') return joryioSubscription(() => undefined);
205
+ // One entry per subscription, so the same function subscribed twice is two subscriptions.
206
+ const entry: FlagsUpdatedCallback = (keys) => callback(keys);
207
+ this.listeners.add(entry);
208
+ this.use();
209
+ return joryioSubscription(() => {
210
+ this.listeners.delete(entry);
211
+ });
212
+ }
213
+
214
+ // ── internals ────────────────────────────────────────────────────────────
215
+
216
+ private read(key: string, type?: FlagValueType): FlagResult | null {
217
+ if (!this.runtime.canSend()) return null;
218
+ this.use();
219
+ const f = this.flags[key];
220
+ if (!f || (type && f.valueType !== type)) return null;
221
+ this.noteExposure(key, f);
222
+ return f;
223
+ }
224
+
225
+ private noteExposure(key: string, f: FlagResult): void {
226
+ if (!f.logExposure) return;
227
+ // The person is part of the mark: after an account switch in the same
228
+ // session the next person's first read is their own exposure.
229
+ const mark = `${this.session.getSessionId()}|${this.subjectKey()}|${key}|${f.variant}`;
230
+ if (this.exposed.has(mark)) return;
231
+ this.exposed.add(mark);
232
+ if (!this.pending || this.pending.generation !== this.generation) {
233
+ // A batch from before an identity change is sent first, as its own person.
234
+ if (this.pending) this.flush();
235
+ this.pending = { body: this.requestBody(), generation: this.generation, exposures: [] };
236
+ }
237
+ this.pending.exposures.push({ key, variant: f.variant });
238
+ if (!this.flushTimer) this.flushTimer = setTimeout(() => this.flush(), FLAG_EXPOSURE_FLUSH_MS);
239
+ }
240
+
241
+ /** Send the queued exposures (one request, the same identity as the evaluation). */
242
+ flush(): void {
243
+ if (this.flushTimer) clearTimeout(this.flushTimer);
244
+ this.flushTimer = null;
245
+ const batch = this.pending;
246
+ this.pending = null;
247
+ // Consent withdrawn since the reads: nothing is sent.
248
+ if (!batch || !batch.exposures.length || !this.runtime.canSend()) return;
249
+ const body = { ...batch.body, exposures: batch.exposures.slice(0, 100) };
250
+ this.post('/v1/flags/exposures', body, true).catch((error) => this.logger.debug('Flag exposures failed', error));
251
+ }
252
+
253
+ private subjectKey(): string {
254
+ return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
255
+ }
256
+
257
+ private requestBody(): Record<string, unknown> {
258
+ const userId = this.identity.getUserId();
259
+ return {
260
+ ...(userId ? { userId } : {}),
261
+ anonymousId: this.identity.getAnonymousId(),
262
+ sessionId: this.session.getSessionId(),
263
+ attributes: this.runtime.attributes?.() ?? {},
264
+ context: {
265
+ platform: 'web',
266
+ locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
267
+ url: typeof location !== 'undefined' ? location.href.split('?')[0] : undefined,
268
+ },
269
+ };
270
+ }
271
+
272
+ private async refresh(force: boolean): Promise<void> {
273
+ if (!this.runtime.canSend() || !this.used) return;
274
+ if (this.inflight) {
275
+ // A request in flight for a previous visitor: wait for it, then ask for this one.
276
+ const stale = this.inflightGeneration !== this.generation;
277
+ await this.inflight;
278
+ if (stale) await this.refresh(true);
279
+ return;
280
+ }
281
+ if (!force && nowMs() - this.fetchedAt < FLAGS_MIN_REFRESH_SECONDS * 1000) return;
282
+ const generation = this.generation;
283
+ this.inflightGeneration = generation;
284
+ this.inflight = (async () => {
285
+ try {
286
+ const res = await this.post('/v1/flags/evaluate', { ...this.requestBody(), ...(this.etag ? { etag: this.etag } : {}) }, false);
287
+ if (!res) return;
288
+ if (generation !== this.generation) return; // answer for a previous visitor
289
+ this.fetchedAt = nowMs();
290
+ if (res.notModified) {
291
+ this.save();
292
+ return;
293
+ }
294
+ if (!res.flags || typeof res.flags !== 'object') return;
295
+ const next = res.flags as Record<string, FlagResult>;
296
+ const changed = Object.keys({ ...this.flags, ...next }).filter(
297
+ (k) => JSON.stringify(this.flags[k]?.value) !== JSON.stringify(next[k]?.value) || this.flags[k]?.variant !== next[k]?.variant,
298
+ );
299
+ this.flags = next;
300
+ this.etag = typeof res.etag === 'string' ? res.etag : '';
301
+ this.save();
302
+ if (changed.length) this.emit(changed);
303
+ } catch (error) {
304
+ this.logger.debug('Flags refresh failed; keeping the held flags', error);
305
+ } finally {
306
+ this.inflight = null;
307
+ }
308
+ })();
309
+ return this.inflight;
310
+ }
311
+
312
+ private async post(path: string, body: Record<string, unknown>, keepalive: boolean): Promise<any> {
313
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
314
+ const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);
315
+ const userId = typeof body.userId === 'string' ? body.userId : null;
316
+ try {
317
+ const response = await fetch(`${this.apiEndpoint}${path}`, {
318
+ method: 'POST',
319
+ headers: {
320
+ 'Content-Type': 'application/json',
321
+ 'X-SDK-Key': this.sdkKey,
322
+ ...sdkIdentityHeaders(),
323
+ ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : (body.anonymousId as string) ?? null) || {}),
324
+ },
325
+ body: JSON.stringify(body),
326
+ ...(keepalive ? { keepalive: true } : {}),
327
+ ...(controller ? { signal: controller.signal } : {}),
328
+ });
329
+ if (!response.ok) {
330
+ this.runtime.noteStatus?.(response.status, null);
331
+ return null;
332
+ }
333
+ return await response.json();
334
+ } finally {
335
+ clearTimeout(timeout);
336
+ }
337
+ }
338
+
339
+ private emit(keys: string[]): void {
340
+ for (const cb of Array.from(this.listeners)) {
341
+ try {
342
+ cb(keys);
343
+ } catch (error) {
344
+ this.logger.error('onFlagsUpdated callback failed', error);
345
+ }
346
+ }
347
+ }
348
+
349
+ private load(): void {
350
+ try {
351
+ if (typeof localStorage === 'undefined') return;
352
+ // Not workspace-scoped: another workspace on this origin may have written it.
353
+ localStorage.removeItem(LEGACY_STORAGE_KEY);
354
+ const raw = localStorage.getItem(flagsStorageKey(this.sdkKey));
355
+ if (!raw) return;
356
+ const s: Stored = JSON.parse(raw);
357
+ // Another visitor's answer is never used.
358
+ if (!s || s.subject !== this.subjectKey() || typeof s.flags !== 'object') return;
359
+ this.flags = s.flags;
360
+ this.etag = s.etag || '';
361
+ this.used = true;
362
+ // The stored answer is used at once, but a start refresh always goes.
363
+ this.fetchedAt = 0;
364
+ } catch {
365
+ /* unreadable storage: start empty */
366
+ }
367
+ }
368
+
369
+ private save(): void {
370
+ try {
371
+ if (typeof localStorage === 'undefined') return;
372
+ const s: Stored = { subject: this.subjectKey(), etag: this.etag, fetchedAt: this.fetchedAt, flags: this.flags };
373
+ localStorage.setItem(flagsStorageKey(this.sdkKey), JSON.stringify(s));
374
+ } catch {
375
+ /* storage full or blocked: memory only */
376
+ }
377
+ }
378
+ }