@superwall/runtime 1.1.0

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 (42) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +93 -0
  3. package/dist/bridge/base64.d.ts +9 -0
  4. package/dist/bridge/base64.js +34 -0
  5. package/dist/bridge/index.d.ts +30 -0
  6. package/dist/bridge/index.js +49 -0
  7. package/dist/bridge/transport.d.ts +14 -0
  8. package/dist/bridge/transport.js +43 -0
  9. package/dist/config.d.ts +237 -0
  10. package/dist/config.js +138 -0
  11. package/dist/index.d.ts +12 -0
  12. package/dist/index.js +11 -0
  13. package/dist/localization/index.d.ts +24 -0
  14. package/dist/localization/index.js +71 -0
  15. package/dist/localization/periods.d.ts +1 -0
  16. package/dist/localization/periods.js +753 -0
  17. package/dist/mock.d.ts +74 -0
  18. package/dist/mock.js +206 -0
  19. package/dist/products.d.ts +62 -0
  20. package/dist/products.js +105 -0
  21. package/dist/session/index.d.ts +103 -0
  22. package/dist/session/index.js +732 -0
  23. package/dist/session/state.d.ts +27 -0
  24. package/dist/session/state.js +60 -0
  25. package/dist/session/types.d.ts +93 -0
  26. package/dist/session/types.js +1 -0
  27. package/dist/session/variables.d.ts +121 -0
  28. package/dist/session/variables.js +5 -0
  29. package/package.json +51 -0
  30. package/src/bridge/base64.ts +56 -0
  31. package/src/bridge/index.ts +77 -0
  32. package/src/bridge/transport.ts +63 -0
  33. package/src/config.ts +408 -0
  34. package/src/index.ts +57 -0
  35. package/src/localization/index.ts +110 -0
  36. package/src/localization/periods.ts +790 -0
  37. package/src/mock.ts +333 -0
  38. package/src/products.ts +221 -0
  39. package/src/session/index.ts +1066 -0
  40. package/src/session/state.ts +112 -0
  41. package/src/session/types.ts +123 -0
  42. package/src/session/variables.ts +139 -0
@@ -0,0 +1,1066 @@
1
+ import {
2
+ type TIncomingMessage,
3
+ type TIncomingMessageCallbackResult,
4
+ type TIncomingMessagePermissionResult,
5
+ type TIncomingMessageTransactionAbandon,
6
+ type TIncomingMessageTransactionComplete,
7
+ type TOutgoingMessage,
8
+ type TPermissionStatus,
9
+ type TPermissionTypeMessage,
10
+ } from "@superwall/protocol";
11
+ import { getLocalizedPeriod } from "../localization/periods";
12
+ import { createSuperwallBridge, type SuperwallBridge } from "../bridge";
13
+ import { productsFromConfig, type SuperwallConfig } from "../config";
14
+ import {
15
+ createTranslator,
16
+ languageCandidates,
17
+ resolveLocale,
18
+ type SuperwallTranslateValues,
19
+ type SuperwallTranslator,
20
+ } from "../localization";
21
+ import { recordFromVariables } from "./variables";
22
+ import {
23
+ createSuperwallProduct,
24
+ mergeIncomingProducts,
25
+ mergeProductVariables,
26
+ productReferenceFromInput,
27
+ productVariablesFromTemplateVariables,
28
+ productsByReference,
29
+ type SuperwallProduct,
30
+ type SuperwallProductInput,
31
+ } from "../products";
32
+ import { buildSuperwallState } from "./state";
33
+
34
+ import type {
35
+ SuperwallCallbackResult,
36
+ SuperwallEventMap,
37
+ SuperwallEventName,
38
+ SuperwallPurchaseFailure,
39
+ SuperwallPurchaseOptions,
40
+ SuperwallPurchaseResult,
41
+ SuperwallRuntimeSnapshot,
42
+ SuperwallSessionOptions,
43
+ SuperwallSessionStartOptions,
44
+ SuperwallTransaction,
45
+ SuperwallTrialState,
46
+ } from "./types";
47
+
48
+ export * from "./types";
49
+
50
+ type Listener = () => void;
51
+
52
+ export type PageViewInput = {
53
+ type: Extract<TOutgoingMessage, { event_name: "page_view" }>["type"];
54
+ name: string;
55
+ navigationId: string;
56
+ position: number;
57
+ previousName?: string;
58
+ previousPosition?: number;
59
+ timeOnPreviousMs?: number;
60
+ };
61
+
62
+ type PendingPurchase = {
63
+ product: SuperwallProduct;
64
+ resolve: (result: SuperwallPurchaseResult) => void;
65
+ timeoutId?: ReturnType<typeof setTimeout>;
66
+ };
67
+
68
+ type PendingPermission = {
69
+ resolve: (status: TPermissionStatus) => void;
70
+ };
71
+
72
+ type PendingCallback<TData = Record<string, unknown>> = {
73
+ name: string;
74
+ resolve: (result: SuperwallCallbackResult<TData>) => void;
75
+ };
76
+
77
+ const permissionTypeToStateName = (permissionType: TPermissionTypeMessage): string =>
78
+ permissionType.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());
79
+
80
+ const callbackNameToStateName = (name: string): string => {
81
+ const segments = name
82
+ .replace(/[^a-zA-Z0-9]/g, " ")
83
+ .trim()
84
+ .replace(/\s+/g, " ")
85
+ .split(" ")
86
+ .filter(Boolean);
87
+
88
+ if (segments.length === 0) {
89
+ return "callback";
90
+ }
91
+
92
+ return segments
93
+ .map((segment, index) =>
94
+ index === 0
95
+ ? segment.charAt(0).toLowerCase() + segment.slice(1)
96
+ : segment.charAt(0).toUpperCase() + segment.slice(1),
97
+ )
98
+ .join("");
99
+ };
100
+
101
+ const initialTrialState = (config: SuperwallConfig | undefined): SuperwallTrialState => {
102
+ switch (config?.introductoryOfferEligibility) {
103
+ case "alwaysEligible":
104
+ return { eligible: true };
105
+ case "alwaysIneligible":
106
+ return { eligible: false };
107
+ default:
108
+ return {};
109
+ }
110
+ };
111
+
112
+ const DAY_MS = 24 * 60 * 60 * 1000;
113
+
114
+ /**
115
+ * Mirrors the schema editor's computeTrialPeriodEndDate: "Jul 23, 2026",
116
+ * month name localized to the active locale where the runtime supports it.
117
+ */
118
+ const computeTrialPeriodEndDate = (
119
+ trialPeriodDays: unknown,
120
+ language: string | undefined,
121
+ ): string | undefined => {
122
+ const parsedDays =
123
+ typeof trialPeriodDays === "number" ? trialPeriodDays : Number(trialPeriodDays);
124
+ if (!Number.isFinite(parsedDays) || parsedDays <= 0) {
125
+ return undefined;
126
+ }
127
+
128
+ const endDate = new Date();
129
+ endDate.setDate(endDate.getDate() + Math.trunc(parsedDays));
130
+
131
+ let month: string;
132
+ try {
133
+ month = endDate.toLocaleString(language?.replace(/_/g, "-") ?? "default", { month: "short" });
134
+ } catch {
135
+ month = endDate.toLocaleString("default", { month: "short" });
136
+ }
137
+
138
+ return `${month} ${endDate.getDate()}, ${endDate.getFullYear()}`;
139
+ };
140
+
141
+ const createRequestId = (prefix: string) => {
142
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
143
+ return `${prefix}-${crypto.randomUUID()}`;
144
+ }
145
+
146
+ return `${prefix}-${Math.random().toString(36).slice(2)}`;
147
+ };
148
+
149
+ /**
150
+ * The session's public contract, separated from the implementation so the
151
+ * product generic can be declared covariant (`out`): `TProduct` appears in
152
+ * output positions only, so a session refined with custom product variables
153
+ * is always usable where a base session is expected (e.g. a shared React
154
+ * context). The implementation is written against the base `SuperwallProduct`
155
+ * — refinement happens once, in `createSuperwallSession`.
156
+ */
157
+ export interface SuperwallSession<out TProduct extends SuperwallProduct = SuperwallProduct> {
158
+ /**
159
+ * Subscribes to a single incoming SDK event by name, or "message" for all
160
+ * incoming messages. Returns an unsubscribe function.
161
+ */
162
+ on: <E extends SuperwallEventName>(
163
+ event: E,
164
+ handler: (payload: SuperwallEventMap[E]) => void,
165
+ ) => () => void;
166
+ /** Subscribes to snapshot changes (`useSyncExternalStore`-compatible). */
167
+ subscribe: (listener: () => void) => () => void;
168
+ getSnapshot: () => SuperwallRuntimeSnapshot<TProduct>;
169
+ readonly products: readonly TProduct[];
170
+ readonly config: SuperwallConfig | undefined;
171
+ readonly locale: string;
172
+ /**
173
+ * Resolves a message key for the active locale, interpolating `{name}`
174
+ * params. Unknown keys return the key itself, so literal copy is safe.
175
+ */
176
+ t: (key: string, values?: SuperwallTranslateValues) => string;
177
+ /** Overrides the locale (normally auto-detected from the device). */
178
+ setLocale: (locale: string | undefined) => void;
179
+ configure: (config: SuperwallConfig) => void;
180
+ start: (options?: SuperwallSessionStartOptions) => void;
181
+ postMessage: (message: TOutgoingMessage) => void;
182
+ accept: (messages: TIncomingMessage[]) => void;
183
+ accept64: (message: string) => void;
184
+ ping: (message?: Partial<Extract<TOutgoingMessage, { event_name: "ping" }>>) => void;
185
+ close: () => void;
186
+ /**
187
+ * Asks the SDK to restore purchases. The message protocol has no restore
188
+ * result event; successful restores surface as `transaction_complete` or a
189
+ * dismissed paywall.
190
+ */
191
+ restore: () => void;
192
+ openUrl: (url: string, options?: { browserType?: "payment_sheet" }) => void;
193
+ openExternalUrl: (url: string) => void;
194
+ openDeepLink: (link: string) => void;
195
+ custom: (data: string) => void;
196
+ customPlacement: (name: string, params?: Record<string, unknown>) => void;
197
+ requestStoreReview: (
198
+ reviewType: Extract<TOutgoingMessage, { event_name: "request_store_review" }>["review_type"],
199
+ ) => void;
200
+ setUserAttributes: (attributes: Record<string, string>) => void;
201
+ pageView: (input: PageViewInput) => void;
202
+ scheduleTrialReminder: (input: {
203
+ id: string;
204
+ title: string;
205
+ subtitle?: string;
206
+ body: string;
207
+ delayMs: number;
208
+ }) => void;
209
+ hapticFeedback: (
210
+ hapticType: Extract<TOutgoingMessage, { event_name: "haptic_feedback" }>["haptic_type"],
211
+ ) => void;
212
+ requestPermission: (permissionType: TPermissionTypeMessage) => Promise<TPermissionStatus>;
213
+ requestCallback: <TData extends Record<string, unknown> = Record<string, unknown>>(
214
+ name: string,
215
+ options?: {
216
+ behavior?: "blocking" | "non-blocking";
217
+ variables?: Record<string, unknown>;
218
+ },
219
+ ) => Promise<SuperwallCallbackResult<TData>>;
220
+ /**
221
+ * Starts a purchase and resolves with the outcome — never throws for flow
222
+ * results: `{ status: "completed" | "abandoned" | "failed" }`.
223
+ */
224
+ purchase: (
225
+ input: SuperwallProductInput,
226
+ options?: SuperwallPurchaseOptions,
227
+ ) => Promise<SuperwallPurchaseResult<TProduct>>;
228
+ getProduct: (reference: string) => TProduct | undefined;
229
+ }
230
+
231
+ class SuperwallSessionImpl implements SuperwallSession {
232
+ private bridge: SuperwallBridge;
233
+ private listeners = new Set<Listener>();
234
+ private pendingPurchases = new Map<string, PendingPurchase>();
235
+ private pendingPermissions = new Map<string, PendingPermission>();
236
+ private pendingCallbacks = new Map<string, PendingCallback>();
237
+ private eventHandlers = new Map<SuperwallEventName, ReadonlySet<unknown>>();
238
+ private snapshot: SuperwallRuntimeSnapshot;
239
+ private translator: SuperwallTranslator;
240
+ private localeOverride?: string;
241
+ private rawProducts: readonly SuperwallProduct[];
242
+ private localizedProductsCache?: {
243
+ raw: readonly SuperwallProduct[];
244
+ languages: string;
245
+ products: readonly SuperwallProduct[];
246
+ };
247
+
248
+ constructor(options: SuperwallSessionOptions = {}) {
249
+ this.bridge = options.bridge ?? createSuperwallBridge(options);
250
+ const products = options.products ?? productsFromConfig(options.config);
251
+ this.rawProducts = products;
252
+
253
+ const variables = options.variables ?? {};
254
+ const locale = resolveLocale(undefined, options.config?.localization);
255
+ this.translator = createTranslator(options.config?.localization, locale);
256
+
257
+ this.snapshot = {
258
+ status: "idle",
259
+ config: options.config,
260
+ products,
261
+ productsByReference: productsByReference(products),
262
+ variables,
263
+ device: {},
264
+ user: {},
265
+ params: {},
266
+ trial: initialTrialState(options.config),
267
+ locale,
268
+ permissionStatuses: {},
269
+ callbackStates: {},
270
+ state: buildSuperwallState({ variables, products }),
271
+ messages: [...this.bridge.messages],
272
+ };
273
+
274
+ this.bridge.addListener((message) => {
275
+ this.handleIncomingMessage(message);
276
+ this.emit(message.event_name, message);
277
+ this.emit("message", message);
278
+ });
279
+ }
280
+
281
+ /**
282
+ * Subscribes to a single incoming SDK event by name, or "message" for all
283
+ * incoming messages. Returns an unsubscribe function.
284
+ */
285
+ public on<E extends SuperwallEventName>(
286
+ event: E,
287
+ handler: (payload: SuperwallEventMap[E]) => void,
288
+ ) {
289
+ const handlers = this.handlersFor(event) ?? new Set<(payload: SuperwallEventMap[E]) => void>();
290
+ this.eventHandlers.set(event, handlers);
291
+
292
+ handlers.add(handler);
293
+ return () => {
294
+ handlers.delete(handler);
295
+ };
296
+ }
297
+
298
+ /**
299
+ * `on`/`emit` enforce that handlers stored under an event name only ever
300
+ * receive that event's payload; TypeScript cannot carry that key↔value
301
+ * correlation through a heterogeneous store (microsoft/TypeScript#47109),
302
+ * so this accessor is the one place it is asserted.
303
+ */
304
+ private handlersFor<E extends SuperwallEventName>(
305
+ event: E,
306
+ ): Set<(payload: SuperwallEventMap[E]) => void> | undefined {
307
+ return this.eventHandlers.get(event) as
308
+ | Set<(payload: SuperwallEventMap[E]) => void>
309
+ | undefined;
310
+ }
311
+
312
+ private emit<E extends SuperwallEventName>(event: E, payload: SuperwallEventMap[E]) {
313
+ const handlers = this.handlersFor(event);
314
+ if (!handlers) return;
315
+
316
+ for (const handler of handlers) {
317
+ handler(payload);
318
+ }
319
+ }
320
+
321
+ public subscribe = (listener: Listener) => {
322
+ this.listeners.add(listener);
323
+ return () => {
324
+ this.listeners.delete(listener);
325
+ };
326
+ };
327
+
328
+ public getSnapshot = () => this.snapshot;
329
+
330
+ public get products() {
331
+ return this.snapshot.products;
332
+ }
333
+
334
+ public get config() {
335
+ return this.snapshot.config;
336
+ }
337
+
338
+ public get locale() {
339
+ return this.snapshot.locale;
340
+ }
341
+
342
+ /**
343
+ * Resolves a message key for the active locale, interpolating `{name}`
344
+ * params. Unknown keys return the key itself, so literal copy is safe.
345
+ */
346
+ public t = (key: string, values?: SuperwallTranslateValues): string =>
347
+ this.translator.t(key, values);
348
+
349
+ /** Overrides the locale (normally auto-detected from the device). */
350
+ public setLocale(locale: string | undefined) {
351
+ this.localeOverride = locale;
352
+ this.patch({});
353
+ }
354
+
355
+ public configure(config: SuperwallConfig) {
356
+ if (config === this.snapshot.config) {
357
+ return;
358
+ }
359
+
360
+ const patch: Partial<SuperwallRuntimeSnapshot> = { config };
361
+
362
+ // Reseed product slots from the new config unless the SDK has already
363
+ // delivered real products (the SDK always wins over config seeds).
364
+ const hasSdkProducts = this.rawProducts.some((product) => product.source === "sdk");
365
+ if (!hasSdkProducts) {
366
+ this.rawProducts = productsFromConfig(config);
367
+ }
368
+
369
+ // Re-derive forced trial eligibility; "automatic" keeps whatever the SDK
370
+ // has signaled so far.
371
+ if (
372
+ config.introductoryOfferEligibility === "alwaysEligible" ||
373
+ config.introductoryOfferEligibility === "alwaysIneligible"
374
+ ) {
375
+ patch.trial = initialTrialState(config);
376
+ }
377
+
378
+ this.patch(patch);
379
+ }
380
+
381
+ public start(options: SuperwallSessionStartOptions = {}) {
382
+ if (this.snapshot.status !== "listening") {
383
+ this.bridge.start();
384
+ this.patch({ status: "listening" });
385
+ }
386
+
387
+ if (options.sendPing) {
388
+ this.ping(options.ping);
389
+ }
390
+ }
391
+
392
+ public postMessage(message: TOutgoingMessage) {
393
+ this.bridge.postMessage(message);
394
+ this.patch({ messages: this.bridge.messages });
395
+ }
396
+
397
+ public accept(messages: TIncomingMessage[]) {
398
+ this.bridge.accept(messages);
399
+ }
400
+
401
+ public accept64(message: string) {
402
+ this.bridge.accept64(message);
403
+ }
404
+
405
+ public ping(message: Partial<Extract<TOutgoingMessage, { event_name: "ping" }>> = {}) {
406
+ this.postMessage({
407
+ event_name: "ping",
408
+ substitutions: [],
409
+ page_styles: [],
410
+ version: "4.0.0",
411
+ ...message,
412
+ });
413
+ }
414
+
415
+ public close() {
416
+ this.postMessage({ event_name: "close" });
417
+ }
418
+
419
+ /**
420
+ * Asks the SDK to restore purchases. The message protocol has no restore
421
+ * result event, so this cannot resolve with an outcome; a successful restore
422
+ * typically dismisses the paywall or arrives as `transaction_complete`
423
+ * (observable via `on("transaction_complete", ...)`).
424
+ */
425
+ public restore() {
426
+ this.postMessage({ event_name: "restore" });
427
+ }
428
+
429
+ public openUrl(url: string, options: { browserType?: "payment_sheet" } = {}) {
430
+ this.postMessage({
431
+ event_name: "open_url",
432
+ url,
433
+ browser_type: options.browserType,
434
+ });
435
+ }
436
+
437
+ public openExternalUrl(url: string) {
438
+ this.postMessage({
439
+ event_name: "open_url_external",
440
+ url,
441
+ });
442
+ }
443
+
444
+ public openDeepLink(link: string) {
445
+ this.postMessage({
446
+ event_name: "open_deep_link",
447
+ link,
448
+ });
449
+ }
450
+
451
+ public custom(data: string) {
452
+ this.postMessage({
453
+ event_name: "custom",
454
+ data,
455
+ });
456
+ }
457
+
458
+ public customPlacement(name: string, params: Record<string, unknown> = {}) {
459
+ this.postMessage({
460
+ event_name: "custom_placement",
461
+ name,
462
+ params,
463
+ });
464
+ }
465
+
466
+ public requestStoreReview(
467
+ reviewType: Extract<TOutgoingMessage, { event_name: "request_store_review" }>["review_type"],
468
+ ) {
469
+ this.postMessage({
470
+ event_name: "request_store_review",
471
+ review_type: reviewType,
472
+ });
473
+ }
474
+
475
+ public setUserAttributes(attributes: Record<string, string>) {
476
+ this.postMessage({
477
+ event_name: "user_attribute_updated",
478
+ attributes: Object.entries(attributes).map(([key, value]) => ({
479
+ key,
480
+ value,
481
+ })),
482
+ });
483
+ }
484
+
485
+ public pageView(input: PageViewInput) {
486
+ this.postMessage({
487
+ event_name: "page_view",
488
+ type: input.type,
489
+ page_name: input.name,
490
+ page_node_id: input.name,
491
+ navigation_node_id: input.navigationId,
492
+ flow_position: input.position,
493
+ previous_page_node_id: input.previousName,
494
+ previous_flow_position: input.previousPosition,
495
+ time_on_previous_page_ms: input.timeOnPreviousMs,
496
+ });
497
+ }
498
+
499
+ public scheduleTrialReminder(input: {
500
+ id: string;
501
+ title: string;
502
+ subtitle?: string;
503
+ body: string;
504
+ delayMs: number;
505
+ }) {
506
+ this.postMessage({
507
+ event_name: "schedule_notification",
508
+ id: input.id,
509
+ type: "TRIAL_STARTED",
510
+ title: input.title,
511
+ subtitle: input.subtitle,
512
+ body: input.body,
513
+ delay: input.delayMs,
514
+ });
515
+ }
516
+
517
+ public hapticFeedback(
518
+ hapticType: Extract<TOutgoingMessage, { event_name: "haptic_feedback" }>["haptic_type"],
519
+ ) {
520
+ this.postMessage({
521
+ event_name: "haptic_feedback",
522
+ haptic_type: hapticType,
523
+ });
524
+ }
525
+
526
+ public requestPermission(permissionType: TPermissionTypeMessage): Promise<TPermissionStatus> {
527
+ const requestId = createRequestId(`permission-${permissionType}`);
528
+
529
+ const result = new Promise<TPermissionStatus>((resolve) => {
530
+ this.pendingPermissions.set(requestId, { resolve });
531
+ });
532
+
533
+ this.postMessage({
534
+ event_name: "request_permission",
535
+ permission_type: permissionType,
536
+ request_id: requestId,
537
+ });
538
+
539
+ return result;
540
+ }
541
+
542
+ public requestCallback<TData extends Record<string, unknown> = Record<string, unknown>>(
543
+ name: string,
544
+ options: {
545
+ behavior?: "blocking" | "non-blocking";
546
+ variables?: Record<string, unknown>;
547
+ } = {},
548
+ ): Promise<SuperwallCallbackResult<TData>> {
549
+ const requestId = createRequestId(`callback-${name}`);
550
+ const behavior = options.behavior ?? "blocking";
551
+
552
+ const result = new Promise<SuperwallCallbackResult>((resolve) => {
553
+ this.pendingCallbacks.set(requestId, { name, resolve });
554
+ });
555
+
556
+ this.postMessage({
557
+ event_name: "request_callback",
558
+ request_id: requestId,
559
+ name,
560
+ behavior,
561
+ variables: options.variables,
562
+ });
563
+
564
+ // TData is the caller's claim about the SDK-owned payload — the same
565
+ // unverifiable-claim seam as `createSuperwallSession`.
566
+ return result as Promise<SuperwallCallbackResult<TData>>;
567
+ }
568
+
569
+ public purchase(
570
+ input: SuperwallProductInput,
571
+ options: SuperwallPurchaseOptions = {},
572
+ ): Promise<SuperwallPurchaseResult> {
573
+ const product = this.resolveProduct(input);
574
+ const timeoutMs = options.timeoutMs ?? this.snapshot.config?.purchaseTimeoutMs;
575
+
576
+ // A retry for the same product replaces the previous attempt: settle the
577
+ // old promise and disarm its timer so it can't fire against the new one.
578
+ this.cancelPendingPurchase(product.reference, "superseded");
579
+
580
+ const result = new Promise<SuperwallPurchaseResult>((resolve) => {
581
+ const pending: PendingPurchase = { product, resolve };
582
+
583
+ if (timeoutMs !== undefined) {
584
+ pending.timeoutId = setTimeout(() => {
585
+ this.failPurchase(product.reference, "timeout");
586
+ }, timeoutMs);
587
+ }
588
+
589
+ this.pendingPurchases.set(product.reference, pending);
590
+ });
591
+
592
+ this.patch({
593
+ pendingPurchase: {
594
+ reference: product.reference,
595
+ product,
596
+ },
597
+ lastPurchaseFailure: undefined,
598
+ });
599
+
600
+ this.postMessage({
601
+ event_name: "purchase",
602
+ product: product.reference,
603
+ product_identifier: product.productIdentifier ?? product.productId ?? product.id,
604
+ should_dismiss: options.shouldDismiss ?? this.snapshot.config?.dismissOnPurchase,
605
+ });
606
+
607
+ return result;
608
+ }
609
+
610
+ public getProduct(reference: string) {
611
+ return this.snapshot.productsByReference[reference];
612
+ }
613
+
614
+ private handleIncomingMessage(message: TIncomingMessage) {
615
+ switch (message.event_name) {
616
+ case "paywall_open":
617
+ // A (re)presentation resets transaction state: settle any in-flight
618
+ // purchases so their timers and promises can't leak into the new view.
619
+ for (const reference of Array.from(this.pendingPurchases.keys())) {
620
+ this.cancelPendingPurchase(reference, "superseded");
621
+ }
622
+
623
+ this.patch({
624
+ paywall: {
625
+ id: message.paywall_id,
626
+ identifier: message.paywall_identifier,
627
+ },
628
+ pendingPurchase: undefined,
629
+ lastTransaction: undefined,
630
+ lastPurchaseFailure: undefined,
631
+ messages: this.bridge.messages,
632
+ });
633
+ break;
634
+ case "products":
635
+ this.setProducts(mergeIncomingProducts(this.rawProducts, message.products));
636
+ break;
637
+ case "template_variables": {
638
+ const productVariables = productVariablesFromTemplateVariables(message.variables);
639
+ this.patch({
640
+ variables: message.variables,
641
+ device: recordFromVariables(message.variables, "device"),
642
+ user: recordFromVariables(message.variables, "user"),
643
+ params: recordFromVariables(message.variables, "params"),
644
+ messages: this.bridge.messages,
645
+ });
646
+
647
+ if (productVariables.size > 0) {
648
+ this.setProducts(mergeProductVariables(this.rawProducts, productVariables));
649
+ }
650
+ break;
651
+ }
652
+ case "template_substitutions_prefix": {
653
+ // The SDK signals introductory-offer eligibility by switching the
654
+ // substitutions prefix to "freeTrial". Config overrides win.
655
+ if (this.snapshot.config?.introductoryOfferEligibility === "alwaysEligible") break;
656
+ if (this.snapshot.config?.introductoryOfferEligibility === "alwaysIneligible") break;
657
+
658
+ this.patch({
659
+ trial: { eligible: message.prefix === "freeTrial" },
660
+ messages: this.bridge.messages,
661
+ });
662
+ break;
663
+ }
664
+ case "experiment":
665
+ this.patch({
666
+ experiment: {
667
+ experimentId: message.experimentId,
668
+ variantId: message.variantId,
669
+ campaignId: message.campaignId,
670
+ },
671
+ messages: this.bridge.messages,
672
+ });
673
+ break;
674
+ case "freeTrial_start":
675
+ this.scheduleConfiguredTrialReminder(message);
676
+ this.patch({ messages: this.bridge.messages });
677
+ break;
678
+ case "transaction_complete":
679
+ this.resolvePurchase(message);
680
+ break;
681
+ case "transaction_abandon":
682
+ this.resolvePurchase(message);
683
+ break;
684
+ case "permission_result":
685
+ this.resolvePermission(message);
686
+ break;
687
+ case "callback_result":
688
+ this.resolveCallback(message);
689
+ break;
690
+ default:
691
+ this.patch({ messages: this.bridge.messages });
692
+ break;
693
+ }
694
+ }
695
+
696
+ /**
697
+ * Auto-schedules the config's trial reminder when the SDK reports a trial
698
+ * started. Static configs run title/subtitle/body through `t()`; dynamic
699
+ * configs (functions) compute the notification from the trial context.
700
+ */
701
+ private scheduleConfiguredTrialReminder(
702
+ message: Extract<TIncomingMessage, { event_name: "freeTrial_start" }>,
703
+ ) {
704
+ const reminder = this.snapshot.config?.notifications?.trialReminder;
705
+ if (!reminder) return;
706
+ if (!message.trial_end_date) return;
707
+
708
+ const trialEndMs =
709
+ typeof message.trial_end_date === "number"
710
+ ? message.trial_end_date
711
+ : Date.parse(message.trial_end_date);
712
+ if (Number.isNaN(trialEndMs)) return;
713
+
714
+ let notification: { title: string; subtitle?: string; body: string; delayMs: number };
715
+
716
+ if (typeof reminder === "function") {
717
+ const product = message.product_identifier
718
+ ? this.rawProducts.find(
719
+ (candidate) =>
720
+ candidate.productIdentifier === message.product_identifier ||
721
+ candidate.productId === message.product_identifier,
722
+ )
723
+ : undefined;
724
+
725
+ const resolved = reminder({
726
+ trialEndDate: new Date(trialEndMs),
727
+ productIdentifier: message.product_identifier,
728
+ product,
729
+ t: this.t,
730
+ locale: this.snapshot.locale,
731
+ });
732
+
733
+ if (!resolved) return;
734
+ notification = resolved;
735
+ } else {
736
+ if (reminder.enabled === false) return;
737
+
738
+ const beforeTrialEndDays = reminder.beforeTrialEndDays ?? 1;
739
+ notification = {
740
+ title: this.t(reminder.title),
741
+ subtitle: reminder.subtitle ? this.t(reminder.subtitle) : undefined,
742
+ body: this.t(reminder.body),
743
+ delayMs: trialEndMs - beforeTrialEndDays * DAY_MS - Date.now(),
744
+ };
745
+ }
746
+
747
+ if (notification.delayMs <= 0) return;
748
+
749
+ this.postMessage({
750
+ event_name: "schedule_notification",
751
+ id: `${this.snapshot.paywall?.identifier ?? "paywall"}_TRIAL_STARTED`,
752
+ type: "TRIAL_STARTED",
753
+ title: notification.title,
754
+ subtitle: notification.subtitle,
755
+ body: notification.body,
756
+ delay: notification.delayMs,
757
+ });
758
+ }
759
+
760
+ private setProducts(products: readonly SuperwallProduct[]) {
761
+ this.rawProducts = products;
762
+ this.patch({ messages: this.bridge.messages });
763
+ }
764
+
765
+ /**
766
+ * The runtime's derived-variables layer — the headless equivalent of the
767
+ * schema editor's buildStateIndex computeds. Raw SDK values are kept
768
+ * internally; every snapshot derives from them so locale changes re-derive
769
+ * cleanly. Currently derives:
770
+ * - `period` / `periodly` localized with the shared translation table
771
+ * - `trialPeriodEndDate` from `trialPeriodDays` when the SDK omits it
772
+ */
773
+ private deriveProducts(
774
+ raw: readonly SuperwallProduct[],
775
+ languages: readonly string[],
776
+ ): readonly SuperwallProduct[] {
777
+ const cacheKey = languages.join(",");
778
+ if (
779
+ this.localizedProductsCache &&
780
+ this.localizedProductsCache.raw === raw &&
781
+ this.localizedProductsCache.languages === cacheKey
782
+ ) {
783
+ return this.localizedProductsCache.products;
784
+ }
785
+
786
+ const products = raw.map((product) => {
787
+ const { period, periodly, trialPeriodDays, trialPeriodEndDate } = product.variables;
788
+ const derivedEndDate =
789
+ trialPeriodEndDate === undefined
790
+ ? computeTrialPeriodEndDate(trialPeriodDays, languages[0])
791
+ : undefined;
792
+
793
+ if (
794
+ typeof period !== "string" &&
795
+ typeof periodly !== "string" &&
796
+ derivedEndDate === undefined
797
+ ) {
798
+ return product;
799
+ }
800
+
801
+ return {
802
+ ...product,
803
+ variables: {
804
+ ...product.variables,
805
+ ...(typeof period === "string"
806
+ ? { period: getLocalizedPeriod(period, [...languages]) }
807
+ : {}),
808
+ ...(typeof periodly === "string"
809
+ ? { periodly: getLocalizedPeriod(periodly, [...languages]) }
810
+ : {}),
811
+ ...(derivedEndDate !== undefined ? { trialPeriodEndDate: derivedEndDate } : {}),
812
+ },
813
+ };
814
+ });
815
+
816
+ this.localizedProductsCache = { raw, languages: cacheKey, products };
817
+ return products;
818
+ }
819
+
820
+ private resolveProduct(input: SuperwallProductInput): SuperwallProduct {
821
+ const reference = productReferenceFromInput(input);
822
+ const existing = this.snapshot.productsByReference[reference];
823
+
824
+ if (existing) {
825
+ return existing;
826
+ }
827
+
828
+ return createSuperwallProduct(input);
829
+ }
830
+
831
+ private resolveProductFromTransaction(
832
+ message: TIncomingMessageTransactionComplete | TIncomingMessageTransactionAbandon,
833
+ ): SuperwallProduct {
834
+ if (message.product) {
835
+ return this.resolveProduct(message.product);
836
+ }
837
+
838
+ if (message.product_identifier) {
839
+ const product = this.snapshot.products.find(
840
+ (candidate) =>
841
+ candidate.productIdentifier === message.product_identifier ||
842
+ candidate.productId === message.product_identifier ||
843
+ candidate.id === message.product_identifier,
844
+ );
845
+
846
+ if (product) {
847
+ return product;
848
+ }
849
+ }
850
+
851
+ return createSuperwallProduct(message.product_identifier ?? message.product ?? "unknown");
852
+ }
853
+
854
+ /**
855
+ * Attributes a transaction message to a pending purchase. Explicit product
856
+ * info on the message must match the pending purchase — an unrelated
857
+ * transaction (e.g. a restore completing another product) must not resolve
858
+ * it. Only a bare transaction with a single pending purchase falls back to
859
+ * that purchase, since some SDK versions omit product info.
860
+ */
861
+ private pendingPurchaseForTransaction(
862
+ message: TIncomingMessageTransactionComplete | TIncomingMessageTransactionAbandon,
863
+ ): PendingPurchase | undefined {
864
+ if (message.product) {
865
+ return this.pendingPurchases.get(message.product);
866
+ }
867
+
868
+ if (message.product_identifier) {
869
+ for (const pending of this.pendingPurchases.values()) {
870
+ if (
871
+ pending.product.productIdentifier === message.product_identifier ||
872
+ pending.product.productId === message.product_identifier ||
873
+ pending.product.id === message.product_identifier
874
+ ) {
875
+ return pending;
876
+ }
877
+ }
878
+ return undefined;
879
+ }
880
+
881
+ return this.pendingPurchases.size === 1 ? this.firstPendingPurchase() : undefined;
882
+ }
883
+
884
+ private resolvePurchase(
885
+ message: TIncomingMessageTransactionComplete | TIncomingMessageTransactionAbandon,
886
+ ) {
887
+ const pending = this.pendingPurchaseForTransaction(message);
888
+ const product = pending?.product ?? this.resolveProductFromTransaction(message);
889
+ const result: SuperwallTransaction =
890
+ message.event_name === "transaction_complete"
891
+ ? { status: "completed", product, message }
892
+ : { status: "abandoned", product, message };
893
+
894
+ if (pending) {
895
+ if (pending.timeoutId !== undefined) {
896
+ clearTimeout(pending.timeoutId);
897
+ }
898
+ this.pendingPurchases.delete(pending.product.reference);
899
+ pending.resolve(result);
900
+ }
901
+
902
+ const clearsSnapshotPending =
903
+ pending !== undefined &&
904
+ this.snapshot.pendingPurchase?.reference === pending.product.reference;
905
+
906
+ this.patch({
907
+ pendingPurchase: clearsSnapshotPending ? undefined : this.snapshot.pendingPurchase,
908
+ lastTransaction: result,
909
+ lastPurchaseFailure: undefined,
910
+ messages: this.bridge.messages,
911
+ });
912
+ }
913
+
914
+ private failPurchase(reference: string, reason: SuperwallPurchaseFailure["reason"]) {
915
+ const failure = this.cancelPendingPurchase(reference, reason);
916
+ if (!failure) return;
917
+
918
+ this.patch({
919
+ pendingPurchase:
920
+ this.snapshot.pendingPurchase?.reference === reference
921
+ ? undefined
922
+ : this.snapshot.pendingPurchase,
923
+ lastPurchaseFailure: failure,
924
+ });
925
+ }
926
+
927
+ /**
928
+ * Settles and removes a pending purchase as failed without touching the
929
+ * snapshot. Returns the failure, or undefined if nothing was pending.
930
+ */
931
+ private cancelPendingPurchase(
932
+ reference: string,
933
+ reason: SuperwallPurchaseFailure["reason"],
934
+ ): SuperwallPurchaseFailure | undefined {
935
+ const pending = this.pendingPurchases.get(reference);
936
+ if (!pending) return undefined;
937
+
938
+ if (pending.timeoutId !== undefined) {
939
+ clearTimeout(pending.timeoutId);
940
+ }
941
+ this.pendingPurchases.delete(reference);
942
+
943
+ const failure: SuperwallPurchaseFailure = {
944
+ status: "failed",
945
+ product: pending.product,
946
+ reason,
947
+ };
948
+
949
+ pending.resolve(failure);
950
+ return failure;
951
+ }
952
+
953
+ private firstPendingPurchase() {
954
+ for (const pending of this.pendingPurchases.values()) {
955
+ return pending;
956
+ }
957
+
958
+ return undefined;
959
+ }
960
+
961
+ private resolvePermission(message: TIncomingMessagePermissionResult) {
962
+ const pending = this.pendingPermissions.get(message.request_id);
963
+
964
+ if (pending) {
965
+ this.pendingPermissions.delete(message.request_id);
966
+ pending.resolve(message.status);
967
+ }
968
+
969
+ this.patch({
970
+ permissionStatuses: {
971
+ ...this.snapshot.permissionStatuses,
972
+ [permissionTypeToStateName(message.permission_type)]: message.status,
973
+ },
974
+ messages: this.bridge.messages,
975
+ });
976
+ }
977
+
978
+ private resolveCallback(message: TIncomingMessageCallbackResult) {
979
+ const pending = this.pendingCallbacks.get(message.request_id);
980
+ const callbackName = callbackNameToStateName(pending?.name ?? message.name);
981
+
982
+ if (pending) {
983
+ this.pendingCallbacks.delete(message.request_id);
984
+ pending.resolve({
985
+ status: message.status,
986
+ data: message.data,
987
+ message,
988
+ });
989
+ }
990
+
991
+ this.patch({
992
+ callbackStates: {
993
+ ...this.snapshot.callbackStates,
994
+ [callbackName]: {
995
+ result: message.status,
996
+ data: message.data,
997
+ },
998
+ },
999
+ messages: this.bridge.messages,
1000
+ });
1001
+ }
1002
+
1003
+ private patch(patch: Partial<SuperwallRuntimeSnapshot>) {
1004
+ const nextSnapshot = {
1005
+ ...this.snapshot,
1006
+ ...patch,
1007
+ };
1008
+
1009
+ // The bridge's log is one mutable array; snapshots must be immutable
1010
+ // views of it. Copy when it grew, keep the previous copy otherwise so
1011
+ // memoized consumers see a stable identity.
1012
+ nextSnapshot.messages =
1013
+ this.bridge.messages.length === this.snapshot.messages.length
1014
+ ? this.snapshot.messages
1015
+ : [...this.bridge.messages];
1016
+
1017
+ const deviceLocale = nextSnapshot.device.deviceLocale ?? nextSnapshot.device.deviceLanguageCode;
1018
+ const requestedLocale =
1019
+ this.localeOverride ?? (typeof deviceLocale === "string" ? deviceLocale : undefined);
1020
+ const locale = resolveLocale(requestedLocale, nextSnapshot.config?.localization);
1021
+
1022
+ if (locale !== this.translator.locale || nextSnapshot.config !== this.snapshot.config) {
1023
+ this.translator = createTranslator(nextSnapshot.config?.localization, locale);
1024
+ }
1025
+
1026
+ const products = this.deriveProducts(this.rawProducts, languageCandidates(requestedLocale));
1027
+ if (products !== nextSnapshot.products) {
1028
+ nextSnapshot.products = products;
1029
+ nextSnapshot.productsByReference = productsByReference(products);
1030
+ }
1031
+
1032
+ this.snapshot = {
1033
+ ...nextSnapshot,
1034
+ locale,
1035
+ state: buildSuperwallState({
1036
+ variables: nextSnapshot.variables,
1037
+ products: nextSnapshot.products,
1038
+ paywall: nextSnapshot.paywall,
1039
+ lastTransaction: nextSnapshot.lastTransaction,
1040
+ permissionStatuses: nextSnapshot.permissionStatuses,
1041
+ callbackStates: nextSnapshot.callbackStates,
1042
+ trial: nextSnapshot.trial,
1043
+ }),
1044
+ };
1045
+
1046
+ for (const listener of this.listeners) {
1047
+ listener();
1048
+ }
1049
+ }
1050
+ }
1051
+
1052
+ /**
1053
+ * Creates a runtime session.
1054
+ *
1055
+ * `TProduct` is the caller's declaration of what SDK-delivered products look
1056
+ * like (custom template variables layered over the known ones). The runtime
1057
+ * cannot verify it — the SDK owns the values — so this downcast is the single
1058
+ * seam where the claim is applied; every refined type downstream derives from
1059
+ * it.
1060
+ */
1061
+ export const createSuperwallSession = <TProduct extends SuperwallProduct = SuperwallProduct>(
1062
+ options: SuperwallSessionOptions<TProduct> = {},
1063
+ ): SuperwallSession<TProduct> => {
1064
+ const session: SuperwallSession = new SuperwallSessionImpl(options);
1065
+ return session as SuperwallSession<TProduct>;
1066
+ };