@superwall/runtime 1.2.0 → 1.3.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 (95) hide show
  1. package/README.md +65 -49
  2. package/dist/bridge/base64.d.ts +0 -6
  3. package/dist/bridge/base64.js +5 -25
  4. package/dist/bridge/index.d.ts +2 -30
  5. package/dist/bridge/index.js +2 -49
  6. package/dist/bridge/transport.d.ts +2 -9
  7. package/dist/bridge/transport.js +9 -30
  8. package/dist/config/background.d.ts +16 -0
  9. package/dist/config/background.js +13 -0
  10. package/dist/config/checkout.d.ts +26 -0
  11. package/dist/config/checkout.js +2 -0
  12. package/dist/config/index.d.ts +66 -0
  13. package/dist/config/index.js +4 -0
  14. package/dist/config/localization.d.ts +13 -0
  15. package/dist/config/localization.js +1 -0
  16. package/dist/config/notifications.d.ts +40 -0
  17. package/dist/config/notifications.js +1 -0
  18. package/dist/config/platforms.d.ts +3 -0
  19. package/dist/config/platforms.js +5 -0
  20. package/dist/config/presentation.d.ts +22 -0
  21. package/dist/config/presentation.js +1 -0
  22. package/dist/config/products.d.ts +23 -0
  23. package/dist/config/products.js +10 -0
  24. package/dist/index.d.ts +2 -7
  25. package/dist/index.js +1 -6
  26. package/dist/localization/catalog.d.ts +8 -0
  27. package/dist/localization/catalog.js +21 -0
  28. package/dist/localization/index.d.ts +3 -24
  29. package/dist/localization/index.js +3 -71
  30. package/dist/localization/locale.d.ts +2 -0
  31. package/dist/localization/locale.js +22 -0
  32. package/dist/localization/periods.d.ts +1 -0
  33. package/dist/localization/periods.js +13 -5
  34. package/dist/products/derive.d.ts +4 -0
  35. package/dist/products/derive.js +45 -0
  36. package/dist/{products.d.ts → products/index.d.ts} +6 -14
  37. package/dist/products/index.js +15 -0
  38. package/dist/products/merge.d.ts +5 -0
  39. package/dist/products/merge.js +51 -0
  40. package/dist/session/incoming.d.ts +3 -0
  41. package/dist/session/incoming.js +47 -0
  42. package/dist/session/index.d.ts +7 -102
  43. package/dist/session/index.js +243 -694
  44. package/dist/session/outgoing.d.ts +42 -0
  45. package/dist/session/outgoing.js +70 -0
  46. package/dist/session/purchases.d.ts +18 -0
  47. package/dist/session/purchases.js +44 -0
  48. package/dist/session/reminders.d.ts +11 -0
  49. package/dist/session/reminders.js +41 -0
  50. package/dist/session/requests.d.ts +19 -0
  51. package/dist/session/requests.js +56 -0
  52. package/dist/session/restores.d.ts +6 -0
  53. package/dist/session/restores.js +20 -0
  54. package/dist/session/state.d.ts +3 -3
  55. package/dist/session/state.js +14 -39
  56. package/dist/session/types.d.ts +60 -29
  57. package/dist/session/variables.d.ts +3 -7
  58. package/package.json +3 -2
  59. package/src/bridge/base64.ts +10 -46
  60. package/src/bridge/index.ts +7 -77
  61. package/src/bridge/transport.ts +11 -46
  62. package/src/config/background.ts +24 -0
  63. package/src/config/checkout.ts +32 -0
  64. package/src/config/index.ts +102 -0
  65. package/src/config/localization.ts +12 -0
  66. package/src/config/notifications.ts +49 -0
  67. package/src/config/platforms.ts +8 -0
  68. package/src/config/presentation.ts +22 -0
  69. package/src/config/products.ts +39 -0
  70. package/src/index.ts +2 -43
  71. package/src/localization/catalog.ts +45 -0
  72. package/src/localization/index.ts +7 -110
  73. package/src/localization/locale.ts +25 -0
  74. package/src/localization/periods.ts +23 -8
  75. package/src/products/derive.ts +65 -0
  76. package/src/products/index.ts +87 -0
  77. package/src/products/merge.ts +78 -0
  78. package/src/session/incoming.ts +53 -0
  79. package/src/session/index.ts +286 -985
  80. package/src/session/outgoing.ts +132 -0
  81. package/src/session/purchases.ts +66 -0
  82. package/src/session/reminders.ts +56 -0
  83. package/src/session/requests.ts +87 -0
  84. package/src/session/restores.ts +27 -0
  85. package/src/session/state.ts +19 -59
  86. package/src/session/types.ts +78 -30
  87. package/src/session/variables.ts +3 -7
  88. package/dist/config.d.ts +0 -237
  89. package/dist/config.js +0 -138
  90. package/dist/mock.d.ts +0 -74
  91. package/dist/mock.js +0 -206
  92. package/dist/products.js +0 -105
  93. package/src/config.ts +0 -408
  94. package/src/mock.ts +0 -333
  95. package/src/products.ts +0 -221
@@ -1,26 +1,17 @@
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,
1
+ import type {
2
+ TIncomingMessage,
3
+ TIncomingMessageTransactionAbandon,
4
+ TIncomingMessageTransactionComplete,
5
+ TOutgoingMessage,
10
6
  } 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";
7
+ import { decodeIncomingMessages } from "../bridge/base64";
8
+ import { createRuntimeTransport } from "../bridge/transport";
9
+ import { normalizePlatform, productIdFor } from "../config";
10
+ import { createTranslator, languageCandidates, resolveLocale } from "../localization";
22
11
  import {
12
+ createProductDeriver,
23
13
  createSuperwallProduct,
14
+ findProductByStoreId,
24
15
  mergeIncomingProducts,
25
16
  mergeProductVariables,
26
17
  productReferenceFromInput,
@@ -29,1038 +20,348 @@ import {
29
20
  type SuperwallProduct,
30
21
  type SuperwallProductInput,
31
22
  } from "../products";
23
+ import { snapshotPatchFor } from "./incoming";
24
+ import * as outgoing from "./outgoing";
25
+ import { createPurchaseTracker } from "./purchases";
26
+ import { createRestoreTracker } from "./restores";
27
+ import { callbackStateName, createRequestTracker } from "./requests";
28
+ import { trialReminderFor } from "./reminders";
32
29
  import { buildSuperwallState } from "./state";
33
-
34
30
  import type {
31
+ SuperwallCallbackOptions,
35
32
  SuperwallCallbackResult,
36
33
  SuperwallEventMap,
37
34
  SuperwallEventName,
38
35
  SuperwallPurchaseFailure,
39
- SuperwallPurchaseOptions,
40
- SuperwallPurchaseResult,
41
36
  SuperwallRuntimeSnapshot,
37
+ SuperwallSession,
42
38
  SuperwallSessionOptions,
43
- SuperwallSessionStartOptions,
44
39
  SuperwallTransaction,
45
- SuperwallTrialState,
46
40
  } from "./types";
47
41
 
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;
42
+ type HandlerSets = {
43
+ [E in SuperwallEventName]?: Set<(payload: SuperwallEventMap[E]) => void>;
75
44
  };
76
45
 
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[];
46
+ type TransactionMessage = TIncomingMessageTransactionComplete | TIncomingMessageTransactionAbandon;
47
+
48
+ const createSession = (options: SuperwallSessionOptions): SuperwallSession => {
49
+ const transport = options.transport ?? createRuntimeTransport(options.transportKind);
50
+ const listeners = new Set<() => void>();
51
+ const handlers: HandlerSets = {};
52
+ const purchases = createPurchaseTracker();
53
+ const restores = createRestoreTracker();
54
+ const requests = createRequestTracker();
55
+ const derive = createProductDeriver();
56
+
57
+ let raw: readonly SuperwallProduct[] = [];
58
+ let localeOverride: string | undefined;
59
+ let translator = createTranslator(
60
+ options.config?.localization,
61
+ resolveLocale(undefined, options.config?.localization),
62
+ );
63
+
64
+ let snapshot: SuperwallRuntimeSnapshot = {
65
+ status: "idle",
66
+ config: options.config,
67
+ products: [],
68
+ productsByReference: {},
69
+ variables: {},
70
+ device: {},
71
+ user: {},
72
+ params: {},
73
+ introductoryOffer: {},
74
+ locale: translator.locale,
75
+ permissionStatuses: {},
76
+ callbackStates: {},
77
+ state: buildSuperwallState({ variables: {}, products: [] }),
246
78
  };
247
79
 
248
- constructor(options: SuperwallSessionOptions = {}) {
249
- this.bridge = options.bridge ?? createSuperwallBridge(options);
250
- const products = options.products ?? productsFromConfig(options.config);
251
- this.rawProducts = products;
80
+ const commit = (patch: Partial<SuperwallRuntimeSnapshot>) => {
81
+ const next = { ...snapshot, ...patch };
82
+ const deviceLocale = next.device.deviceLocale ?? next.device.deviceLanguageCode;
83
+ const requested =
84
+ localeOverride ?? (typeof deviceLocale === "string" ? deviceLocale : undefined);
85
+ const locale = resolveLocale(requested, next.config?.localization);
86
+ if (locale !== translator.locale || next.config !== snapshot.config) {
87
+ translator = createTranslator(next.config?.localization, locale);
88
+ }
252
89
 
253
- const variables = options.variables ?? {};
254
- const locale = resolveLocale(undefined, options.config?.localization);
255
- this.translator = createTranslator(options.config?.localization, locale);
90
+ const products = derive(raw, languageCandidates(requested));
91
+ if (products !== next.products) {
92
+ next.products = products;
93
+ next.productsByReference = productsByReference(products);
94
+ }
256
95
 
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),
96
+ snapshot = {
97
+ ...next,
267
98
  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);
99
+ state: buildSuperwallState({
100
+ variables: next.variables,
101
+ products: next.products,
102
+ paywall: next.paywall,
103
+ lastTransaction: next.lastTransaction,
104
+ permissionStatuses: next.permissionStatuses,
105
+ callbackStates: next.callbackStates,
106
+ introductoryOffer: next.introductoryOffer,
107
+ }),
295
108
  };
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
109
 
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
- };
110
+ for (const listener of listeners) listener();
326
111
  };
327
112
 
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
- });
113
+ const post = (message: TOutgoingMessage) => {
114
+ transport.postMessage(message);
115
+ };
538
116
 
539
- return result;
540
- }
117
+ const t: SuperwallSession["t"] = (key, values) => translator.t(key, values);
541
118
 
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";
119
+ const emit = <E extends SuperwallEventName>(event: E, payload: SuperwallEventMap[E]) => {
120
+ handlers[event]?.forEach((handler) => handler(payload));
121
+ };
551
122
 
552
- const result = new Promise<SuperwallCallbackResult>((resolve) => {
553
- this.pendingCallbacks.set(requestId, { name, resolve });
554
- });
123
+ const devicePlatform = () =>
124
+ normalizePlatform(
125
+ typeof snapshot.device.platform === "string" ? snapshot.device.platform : undefined,
126
+ );
555
127
 
556
- this.postMessage({
557
- event_name: "request_callback",
558
- request_id: requestId,
559
- name,
560
- behavior,
561
- variables: options.variables,
128
+ const resolveProduct = (input: SuperwallProductInput): SuperwallProduct => {
129
+ const reference = productReferenceFromInput(input);
130
+ const existing = snapshot.productsByReference[reference];
131
+ if (existing) return existing;
132
+
133
+ const slot = snapshot.config?.products?.[reference];
134
+ if (slot === undefined || typeof input !== "string") return createSuperwallProduct(input);
135
+ return createSuperwallProduct({
136
+ reference,
137
+ productId: productIdFor(slot, devicePlatform()),
138
+ source: "inline",
562
139
  });
140
+ };
563
141
 
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 };
142
+ const productOfTransaction = (message: TransactionMessage): SuperwallProduct => {
143
+ if (message.product !== undefined) return resolveProduct(message.product);
144
+ return (
145
+ findProductByStoreId(snapshot.products, message.product_identifier) ??
146
+ createSuperwallProduct(message.product_identifier ?? "unknown")
147
+ );
148
+ };
582
149
 
583
- if (timeoutMs !== undefined) {
584
- pending.timeoutId = setTimeout(() => {
585
- this.failPurchase(product.reference, "timeout");
586
- }, timeoutMs);
587
- }
150
+ const withoutPending = (reference: string) =>
151
+ snapshot.pendingPurchase?.reference === reference ? undefined : snapshot.pendingPurchase;
588
152
 
589
- this.pendingPurchases.set(product.reference, pending);
153
+ const recordFailure = (failure: SuperwallPurchaseFailure) => {
154
+ commit({
155
+ pendingPurchase: withoutPending(failure.product.reference),
156
+ lastPurchaseFailure: failure,
590
157
  });
158
+ };
591
159
 
592
- this.patch({
593
- pendingPurchase: {
594
- reference: product.reference,
595
- product,
596
- },
160
+ const settleTransaction = (message: TransactionMessage) => {
161
+ const pending = purchases.take(message);
162
+ const product = pending?.product ?? productOfTransaction(message);
163
+ const result: SuperwallTransaction =
164
+ message.event_name === "transaction_complete"
165
+ ? { status: "completed", product, message }
166
+ : { status: "abandoned", product, message };
167
+ pending?.resolve(result);
168
+ commit({
169
+ pendingPurchase: pending
170
+ ? withoutPending(pending.product.reference)
171
+ : snapshot.pendingPurchase,
172
+ lastTransaction: result,
597
173
  lastPurchaseFailure: undefined,
598
174
  });
175
+ };
599
176
 
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) {
177
+ const handleIncoming = (message: TIncomingMessage) => {
615
178
  switch (message.event_name) {
616
179
  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
- });
180
+ purchases.failAll("superseded");
633
181
  break;
634
182
  case "products":
635
- this.setProducts(mergeIncomingProducts(this.rawProducts, message.products));
183
+ raw = mergeIncomingProducts(raw, message.products);
636
184
  break;
637
185
  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
- }
186
+ const variables = productVariablesFromTemplateVariables(message.variables);
187
+ if (variables.size > 0) raw = mergeProductVariables(raw, variables);
650
188
  break;
651
189
  }
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,
190
+ case "freeTrial_start": {
191
+ const reminder = trialReminderFor(snapshot.config, message, {
192
+ products: raw,
193
+ t,
194
+ locale: snapshot.locale,
195
+ paywallIdentifier: snapshot.paywall?.identifier,
661
196
  });
197
+ if (reminder) post(reminder);
662
198
  break;
663
199
  }
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
- });
200
+ case "transaction_complete":
201
+ case "transaction_abandon":
202
+ settleTransaction(message);
673
203
  break;
674
- case "freeTrial_start":
675
- this.scheduleConfiguredTrialReminder(message);
676
- this.patch({ messages: this.bridge.messages });
204
+ case "transaction_fail":
205
+ case "transaction_timeout": {
206
+ const pending = purchases.find(message);
207
+ const failure = pending && purchases.fail(pending.product.reference, "sdk");
208
+ if (failure) recordFailure(failure);
677
209
  break;
678
- case "transaction_complete":
679
- this.resolvePurchase(message);
210
+ }
211
+ case "restore_complete":
212
+ restores.settle("restored");
680
213
  break;
681
- case "transaction_abandon":
682
- this.resolvePurchase(message);
214
+ case "restore_fail":
215
+ restores.settle("failed");
683
216
  break;
684
217
  case "permission_result":
685
- this.resolvePermission(message);
218
+ requests.resolvePermission(message);
686
219
  break;
687
- case "callback_result":
688
- this.resolveCallback(message);
220
+ case "callback_result": {
221
+ const name = callbackStateName(requests.resolveCallback(message) ?? message.name);
222
+ commit({
223
+ callbackStates: {
224
+ ...snapshot.callbackStates,
225
+ [name]: { result: message.status, data: message.data },
226
+ },
227
+ });
689
228
  break;
229
+ }
690
230
  default:
691
- this.patch({ messages: this.bridge.messages });
692
231
  break;
693
232
  }
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
233
 
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;
234
+ commit(snapshotPatchFor(snapshot, message) ?? {});
235
+ emit(message.event_name, message);
236
+ emit("message", message);
237
+ };
724
238
 
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
- });
239
+ transport.addListener(handleIncoming);
732
240
 
733
- if (!resolved) return;
734
- notification = resolved;
735
- } else {
736
- if (reminder.enabled === false) return;
241
+ const requestCallback = <TData extends Record<string, unknown>>(
242
+ name: string,
243
+ callbackOptions: SuperwallCallbackOptions = {},
244
+ ): Promise<SuperwallCallbackResult<TData>> => {
245
+ const behavior = callbackOptions.behavior ?? "blocking";
246
+ const { requestId, result } = requests.callback(name, behavior);
247
+ post(
248
+ outgoing.requestCallback({ requestId, name, behavior, variables: callbackOptions.variables }),
249
+ );
250
+ // TData is the caller's claim about the SDK-owned payload — the same
251
+ // unverifiable-claim seam as `createSuperwallSession`.
252
+ return result as Promise<SuperwallCallbackResult<TData>>;
253
+ };
737
254
 
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(),
255
+ return {
256
+ on: (event, handler) => {
257
+ const set = handlers[event] ?? new Set<typeof handler>();
258
+ if (!handlers[event]) Object.assign(handlers, { [event]: set });
259
+ set.add(handler);
260
+ return () => {
261
+ set.delete(handler);
744
262
  };
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
- },
263
+ },
264
+ subscribe: (listener) => {
265
+ listeners.add(listener);
266
+ return () => {
267
+ listeners.delete(listener);
813
268
  };
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
- }
269
+ },
270
+ getSnapshot: () => snapshot,
271
+ t,
272
+ setLocale: (locale) => {
273
+ localeOverride = locale;
274
+ commit({});
275
+ },
276
+ configure: (config) => {
277
+ if (config !== snapshot.config) commit({ config });
278
+ },
279
+ start: (startOptions = {}) => {
280
+ if (snapshot.status !== "listening") {
281
+ transport.startListening();
282
+ commit({ status: "listening" });
877
283
  }
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);
284
+ if (startOptions.sendPing) post(outgoing.ping());
285
+ },
286
+ postMessage: post,
287
+ accept: (messages) => {
288
+ for (const message of messages) transport.accept(message);
289
+ },
290
+ accept64: (message) => {
291
+ let decoded: TIncomingMessage[];
292
+ try {
293
+ decoded = decodeIncomingMessages(message);
294
+ } catch (error) {
295
+ options.onDecodeError?.(error);
296
+ return;
897
297
  }
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,
298
+ for (const entry of decoded) transport.accept(entry);
299
+ },
300
+ close: () => post(outgoing.close()),
301
+ restore: () => {
302
+ const result = restores.begin();
303
+ post(outgoing.restore());
304
+ return result;
305
+ },
306
+ openUrl: (url, urlOptions = {}) => post(outgoing.openUrl(url, urlOptions.browserType)),
307
+ openExternalUrl: (url) => post(outgoing.openExternalUrl(url)),
308
+ openDeepLink: (link) => post(outgoing.openDeepLink(link)),
309
+ customPlacement: (name, params = {}) => post(outgoing.customPlacement(name, params)),
310
+ requestStoreReview: (reviewType) => post(outgoing.requestStoreReview(reviewType)),
311
+ pageView: (input) => post(outgoing.pageView(input)),
312
+ hapticFeedback: (hapticType) => post(outgoing.hapticFeedback(hapticType)),
313
+ requestPermission: (permissionType) => {
314
+ const { requestId, result } = requests.permission(permissionType);
315
+ post(outgoing.requestPermission(permissionType, requestId));
316
+ return result;
317
+ },
318
+ requestCallback,
319
+ purchase: (input, purchaseOptions = {}) => {
320
+ const product = resolveProduct(input);
321
+ const result = purchases.begin(product);
322
+ commit({
323
+ pendingPurchase: { reference: product.reference, product },
324
+ lastPurchaseFailure: undefined,
988
325
  });
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
- }
326
+ post(
327
+ outgoing.purchase(
328
+ product,
329
+ purchaseOptions.shouldDismiss ?? snapshot.config?.dismissOnPurchase,
330
+ ),
331
+ );
332
+ return result;
333
+ },
334
+ };
335
+ };
1051
336
 
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
- */
337
+ // TProduct is the caller's claim about what host-delivered products look like;
338
+ // the host owns the values, so the claim is applied here, once.
1061
339
  export const createSuperwallSession = <TProduct extends SuperwallProduct = SuperwallProduct>(
1062
- options: SuperwallSessionOptions<TProduct> = {},
340
+ options: SuperwallSessionOptions = {},
1063
341
  ): SuperwallSession<TProduct> => {
1064
- const session: SuperwallSession = new SuperwallSessionImpl(options);
342
+ const session: SuperwallSession = createSession(options);
1065
343
  return session as SuperwallSession<TProduct>;
1066
344
  };
345
+
346
+ export { PING_VERSION, type PageViewInput } from "./outgoing";
347
+ export type { CallbackBehavior } from "./requests";
348
+ export {
349
+ buildSuperwallState,
350
+ type BuildSuperwallStateOptions,
351
+ type SuperwallCallbackState,
352
+ type SuperwallCallbackStates,
353
+ type SuperwallPermissionStatuses,
354
+ type SuperwallSdkState,
355
+ } from "./state";
356
+ export * from "./types";
357
+ export {
358
+ recordFromVariables,
359
+ type SuperwallCapability,
360
+ type SuperwallCustomerInfo,
361
+ type SuperwallDeviceEntitlement,
362
+ type SuperwallDeviceTransaction,
363
+ type SuperwallDeviceVariables,
364
+ type SuperwallExperiment,
365
+ type SuperwallPlacementParams,
366
+ type SuperwallUserVariables,
367
+ } from "./variables";