@superwall/runtime 1.1.1 → 1.3.0-beta.3

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