@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
@@ -0,0 +1,42 @@
1
+ import type { TOutgoingMessage, TPermissionTypeMessage } from "@superwall/protocol";
2
+ import type { SuperwallProduct } from "../products";
3
+ export type Outgoing<E extends TOutgoingMessage["event_name"]> = Extract<TOutgoingMessage, {
4
+ event_name: E;
5
+ }>;
6
+ export declare const PING_VERSION = "4.0.0";
7
+ export declare const ping: () => Outgoing<"ping">;
8
+ export declare const close: () => Outgoing<"close">;
9
+ export declare const restore: () => Outgoing<"restore">;
10
+ export declare const openUrl: (url: string, browserType?: "payment_sheet") => Outgoing<"open_url">;
11
+ export declare const openExternalUrl: (url: string) => Outgoing<"open_url_external">;
12
+ export declare const openDeepLink: (link: string) => Outgoing<"open_deep_link">;
13
+ export declare const customPlacement: (name: string, params: Record<string, unknown>) => Outgoing<"custom_placement">;
14
+ export declare const requestStoreReview: (reviewType: Outgoing<"request_store_review">["review_type"]) => Outgoing<"request_store_review">;
15
+ export declare const hapticFeedback: (hapticType: Outgoing<"haptic_feedback">["haptic_type"]) => Outgoing<"haptic_feedback">;
16
+ export type PageViewInput = {
17
+ type: Outgoing<"page_view">["type"];
18
+ name: string;
19
+ navigationId: string;
20
+ position: number;
21
+ previousName?: string;
22
+ previousPosition?: number;
23
+ timeOnPreviousMs?: number;
24
+ };
25
+ export declare const pageView: (input: PageViewInput) => Outgoing<"page_view">;
26
+ export type NotificationInput = {
27
+ id: string;
28
+ title: string;
29
+ subtitle?: string;
30
+ body: string;
31
+ delayMs: number;
32
+ };
33
+ export declare const scheduleNotification: (input: NotificationInput) => Outgoing<"schedule_notification">;
34
+ export declare const requestPermission: (permissionType: TPermissionTypeMessage, requestId: string) => Outgoing<"request_permission">;
35
+ export type CallbackRequestInput = {
36
+ requestId: string;
37
+ name: string;
38
+ behavior: "blocking" | "non-blocking";
39
+ variables?: Record<string, unknown>;
40
+ };
41
+ export declare const requestCallback: (input: CallbackRequestInput) => Outgoing<"request_callback">;
42
+ export declare const purchase: (product: SuperwallProduct, shouldDismiss: boolean | undefined) => Outgoing<"purchase">;
@@ -0,0 +1,70 @@
1
+ export const PING_VERSION = "4.0.0";
2
+ export const ping = () => ({
3
+ event_name: "ping",
4
+ substitutions: [],
5
+ page_styles: [],
6
+ version: PING_VERSION,
7
+ });
8
+ export const close = () => ({ event_name: "close" });
9
+ export const restore = () => ({ event_name: "restore" });
10
+ export const openUrl = (url, browserType) => ({
11
+ event_name: "open_url",
12
+ url,
13
+ ...(browserType === undefined ? {} : { browser_type: browserType }),
14
+ });
15
+ export const openExternalUrl = (url) => ({
16
+ event_name: "open_url_external",
17
+ url,
18
+ });
19
+ export const openDeepLink = (link) => ({
20
+ event_name: "open_deep_link",
21
+ link,
22
+ });
23
+ export const customPlacement = (name, params) => ({ event_name: "custom_placement", name, params });
24
+ export const requestStoreReview = (reviewType) => ({
25
+ event_name: "request_store_review",
26
+ review_type: reviewType,
27
+ });
28
+ export const hapticFeedback = (hapticType) => ({ event_name: "haptic_feedback", haptic_type: hapticType });
29
+ export const pageView = (input) => ({
30
+ event_name: "page_view",
31
+ type: input.type,
32
+ page_name: input.name,
33
+ page_node_id: input.name,
34
+ navigation_node_id: input.navigationId,
35
+ flow_position: input.position,
36
+ ...(input.previousName === undefined ? {} : { previous_page_node_id: input.previousName }),
37
+ ...(input.previousPosition === undefined
38
+ ? {}
39
+ : { previous_flow_position: input.previousPosition }),
40
+ ...(input.timeOnPreviousMs === undefined
41
+ ? {}
42
+ : { time_on_previous_page_ms: input.timeOnPreviousMs }),
43
+ });
44
+ export const scheduleNotification = (input) => ({
45
+ event_name: "schedule_notification",
46
+ id: input.id,
47
+ type: "TRIAL_STARTED",
48
+ title: input.title,
49
+ ...(input.subtitle === undefined ? {} : { subtitle: input.subtitle }),
50
+ body: input.body,
51
+ delay: input.delayMs,
52
+ });
53
+ export const requestPermission = (permissionType, requestId) => ({
54
+ event_name: "request_permission",
55
+ permission_type: permissionType,
56
+ request_id: requestId,
57
+ });
58
+ export const requestCallback = (input) => ({
59
+ event_name: "request_callback",
60
+ request_id: input.requestId,
61
+ name: input.name,
62
+ behavior: input.behavior,
63
+ ...(input.variables === undefined ? {} : { variables: input.variables }),
64
+ });
65
+ export const purchase = (product, shouldDismiss) => ({
66
+ event_name: "purchase",
67
+ product: product.reference,
68
+ ...(product.productId === undefined ? {} : { product_identifier: product.productId }),
69
+ ...(shouldDismiss === undefined ? {} : { should_dismiss: shouldDismiss }),
70
+ });
@@ -0,0 +1,18 @@
1
+ import type { SuperwallProduct } from "../products";
2
+ import type { SuperwallPurchaseFailure, SuperwallPurchaseResult } from "./types";
3
+ export type PendingPurchase = {
4
+ product: SuperwallProduct;
5
+ resolve: (result: SuperwallPurchaseResult) => void;
6
+ };
7
+ export type TransactionReference = {
8
+ product?: string;
9
+ product_identifier?: string;
10
+ };
11
+ export type PurchaseTracker = {
12
+ begin: (product: SuperwallProduct) => Promise<SuperwallPurchaseResult>;
13
+ fail: (reference: string, reason: SuperwallPurchaseFailure["reason"]) => SuperwallPurchaseFailure | undefined;
14
+ failAll: (reason: SuperwallPurchaseFailure["reason"]) => void;
15
+ find: (message: TransactionReference) => PendingPurchase | undefined;
16
+ take: (message: TransactionReference) => PendingPurchase | undefined;
17
+ };
18
+ export declare const createPurchaseTracker: () => PurchaseTracker;
@@ -0,0 +1,44 @@
1
+ export const createPurchaseTracker = () => {
2
+ const pending = new Map();
3
+ const fail = (reference, reason) => {
4
+ const entry = pending.get(reference);
5
+ if (!entry)
6
+ return undefined;
7
+ pending.delete(reference);
8
+ const failure = { status: "failed", product: entry.product, reason };
9
+ entry.resolve(failure);
10
+ return failure;
11
+ };
12
+ const find = (message) => {
13
+ if (message.product !== undefined)
14
+ return pending.get(message.product);
15
+ if (message.product_identifier !== undefined) {
16
+ for (const entry of pending.values()) {
17
+ if (entry.product.productId === message.product_identifier)
18
+ return entry;
19
+ }
20
+ return undefined;
21
+ }
22
+ return pending.size === 1 ? pending.values().next().value : undefined;
23
+ };
24
+ return {
25
+ begin: (product) => {
26
+ fail(product.reference, "superseded");
27
+ return new Promise((resolve) => {
28
+ pending.set(product.reference, { product, resolve });
29
+ });
30
+ },
31
+ fail,
32
+ failAll: (reason) => {
33
+ for (const reference of Array.from(pending.keys()))
34
+ fail(reference, reason);
35
+ },
36
+ find,
37
+ take: (message) => {
38
+ const entry = find(message);
39
+ if (entry)
40
+ pending.delete(entry.product.reference);
41
+ return entry;
42
+ },
43
+ };
44
+ };
@@ -0,0 +1,11 @@
1
+ import type { TIncomingMessageFreeTrialStart } from "@superwall/protocol";
2
+ import type { SuperwallConfig } from "../config";
3
+ import { type SuperwallProduct } from "../products";
4
+ import { type Outgoing } from "./outgoing";
5
+ export type TrialReminderContext = {
6
+ products: readonly SuperwallProduct[];
7
+ t: (key: string, values?: Record<string, string | number>) => string;
8
+ locale: string;
9
+ paywallIdentifier: string | undefined;
10
+ };
11
+ export declare const trialReminderFor: (config: SuperwallConfig | undefined, message: TIncomingMessageFreeTrialStart, context: TrialReminderContext) => Outgoing<"schedule_notification"> | undefined;
@@ -0,0 +1,41 @@
1
+ import { findProductByStoreId } from "../products";
2
+ import { scheduleNotification } from "./outgoing";
3
+ const DAY_MS = 24 * 60 * 60 * 1000;
4
+ const trialEndOf = (message) => {
5
+ if (message.trial_end_date === undefined)
6
+ return undefined;
7
+ const ms = typeof message.trial_end_date === "number"
8
+ ? message.trial_end_date
9
+ : Date.parse(message.trial_end_date);
10
+ return Number.isNaN(ms) ? undefined : ms;
11
+ };
12
+ export const trialReminderFor = (config, message, context) => {
13
+ const reminder = config?.notifications?.trialReminder;
14
+ const trialEndMs = trialEndOf(message);
15
+ if (!reminder || trialEndMs === undefined)
16
+ return undefined;
17
+ let notification;
18
+ if (typeof reminder === "function") {
19
+ notification = reminder({
20
+ trialEndDate: new Date(trialEndMs),
21
+ productIdentifier: message.product_identifier,
22
+ product: findProductByStoreId(context.products, message.product_identifier),
23
+ t: context.t,
24
+ locale: context.locale,
25
+ });
26
+ }
27
+ else if (reminder.enabled !== false) {
28
+ notification = {
29
+ title: context.t(reminder.title),
30
+ ...(reminder.subtitle === undefined ? {} : { subtitle: context.t(reminder.subtitle) }),
31
+ body: context.t(reminder.body),
32
+ delayMs: trialEndMs - (reminder.beforeTrialEndDays ?? 1) * DAY_MS - Date.now(),
33
+ };
34
+ }
35
+ if (!notification || notification.delayMs <= 0)
36
+ return undefined;
37
+ return scheduleNotification({
38
+ id: `${context.paywallIdentifier ?? "paywall"}_TRIAL_STARTED`,
39
+ ...notification,
40
+ });
41
+ };
@@ -0,0 +1,19 @@
1
+ import type { TIncomingMessageCallbackResult, TIncomingMessagePermissionResult, TPermissionStatus, TPermissionTypeMessage } from "@superwall/protocol";
2
+ import type { SuperwallCallbackResult } from "./types";
3
+ export declare const createRequestId: (prefix: string) => string;
4
+ export declare const permissionStateName: (permissionType: TPermissionTypeMessage) => string;
5
+ export declare const callbackStateName: (name: string) => string;
6
+ export type CallbackBehavior = "blocking" | "non-blocking";
7
+ export type RequestTracker = {
8
+ permission: (permissionType: TPermissionTypeMessage) => {
9
+ requestId: string;
10
+ result: Promise<TPermissionStatus>;
11
+ };
12
+ callback: (name: string, behavior: CallbackBehavior) => {
13
+ requestId: string;
14
+ result: Promise<SuperwallCallbackResult>;
15
+ };
16
+ resolvePermission: (message: TIncomingMessagePermissionResult) => void;
17
+ resolveCallback: (message: TIncomingMessageCallbackResult) => string | undefined;
18
+ };
19
+ export declare const createRequestTracker: () => RequestTracker;
@@ -0,0 +1,56 @@
1
+ export const createRequestId = (prefix) => {
2
+ const unique = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
3
+ ? crypto.randomUUID()
4
+ : Math.random().toString(36).slice(2);
5
+ return `${prefix}-${unique}`;
6
+ };
7
+ export const permissionStateName = (permissionType) => permissionType.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
8
+ export const callbackStateName = (name) => {
9
+ const segments = name
10
+ .replace(/[^a-zA-Z0-9]/g, " ")
11
+ .trim()
12
+ .split(/\s+/)
13
+ .filter(Boolean);
14
+ if (segments.length === 0)
15
+ return "callback";
16
+ return segments
17
+ .map((segment, index) => index === 0
18
+ ? segment.charAt(0).toLowerCase() + segment.slice(1)
19
+ : segment.charAt(0).toUpperCase() + segment.slice(1))
20
+ .join("");
21
+ };
22
+ export const createRequestTracker = () => {
23
+ const permissions = new Map();
24
+ const callbacks = new Map();
25
+ return {
26
+ permission: (permissionType) => {
27
+ const requestId = createRequestId(`permission-${permissionType}`);
28
+ const result = new Promise((resolve) => {
29
+ permissions.set(requestId, resolve);
30
+ });
31
+ return { requestId, result };
32
+ },
33
+ callback: (name, behavior) => {
34
+ const requestId = createRequestId(`${callbackStateName(name)}-${behavior}`);
35
+ const result = new Promise((resolve) => {
36
+ callbacks.set(requestId, { name, resolve });
37
+ });
38
+ return { requestId, result };
39
+ },
40
+ resolvePermission: (message) => {
41
+ const resolve = permissions.get(message.request_id);
42
+ if (!resolve)
43
+ return;
44
+ permissions.delete(message.request_id);
45
+ resolve(message.status);
46
+ },
47
+ resolveCallback: (message) => {
48
+ const entry = callbacks.get(message.request_id);
49
+ if (!entry)
50
+ return undefined;
51
+ callbacks.delete(message.request_id);
52
+ entry.resolve({ status: message.status, data: message.data, message });
53
+ return entry.name;
54
+ },
55
+ };
56
+ };
@@ -0,0 +1,6 @@
1
+ import type { SuperwallRestoreResult } from "./types";
2
+ export type RestoreTracker = {
3
+ begin: () => Promise<SuperwallRestoreResult>;
4
+ settle: (status: SuperwallRestoreResult["status"]) => void;
5
+ };
6
+ export declare const createRestoreTracker: () => RestoreTracker;
@@ -0,0 +1,20 @@
1
+ export const createRestoreTracker = () => {
2
+ let resolve;
3
+ let pending;
4
+ return {
5
+ begin: () => {
6
+ if (pending)
7
+ return pending;
8
+ pending = new Promise((settle) => {
9
+ resolve = settle;
10
+ });
11
+ return pending;
12
+ },
13
+ settle: (status) => {
14
+ const settled = resolve;
15
+ resolve = undefined;
16
+ pending = undefined;
17
+ settled?.({ status });
18
+ },
19
+ };
20
+ };
@@ -1,5 +1,5 @@
1
1
  import type { TIncomingMessageCallbackResult, TPermissionStatus } from "@superwall/protocol";
2
- import type { SuperwallProduct } from "../products";
2
+ import { type SuperwallProduct } from "../products";
3
3
  export type SuperwallSdkState = Readonly<Record<string, unknown>>;
4
4
  export type SuperwallPermissionStatuses = Readonly<Record<string, TPermissionStatus>>;
5
5
  export type SuperwallCallbackState = Readonly<{
@@ -20,8 +20,8 @@ export type BuildSuperwallStateOptions<TProduct extends SuperwallProduct = Super
20
20
  };
21
21
  permissionStatuses?: SuperwallPermissionStatuses;
22
22
  callbackStates?: SuperwallCallbackStates;
23
- trial?: {
23
+ introductoryOffer?: {
24
24
  eligible?: boolean;
25
25
  };
26
26
  };
27
- export declare const buildSuperwallState: <TProduct extends SuperwallProduct = SuperwallProduct>({ variables, products, paywall, lastTransaction, permissionStatuses, callbackStates, trial, }: BuildSuperwallStateOptions<TProduct>) => SuperwallSdkState;
27
+ export declare const buildSuperwallState: <TProduct extends SuperwallProduct = SuperwallProduct>({ variables, products, paywall, lastTransaction, permissionStatuses, callbackStates, introductoryOffer, }: BuildSuperwallStateOptions<TProduct>) => SuperwallSdkState;
@@ -1,60 +1,35 @@
1
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
- const productStateFromVariables = (variables) => {
3
- const products = {};
4
- if (Array.isArray(variables.products)) {
5
- for (const entry of variables.products) {
6
- if (!isRecord(entry))
7
- continue;
8
- for (const [reference, productVariables] of Object.entries(entry)) {
9
- products[reference] = productVariables;
10
- }
11
- }
12
- }
13
- for (const reference of ["primary", "secondary", "tertiary"]) {
14
- const productVariables = variables[reference];
15
- if (isRecord(productVariables) && !products[reference]) {
16
- products[reference] = productVariables;
17
- }
18
- }
19
- return products;
20
- };
21
- export const buildSuperwallState = ({ variables, products, paywall, lastTransaction, permissionStatuses = {}, callbackStates = {}, trial, }) => {
22
- const productState = productStateFromVariables(variables);
23
- if (trial?.eligible !== undefined) {
24
- productState.hasIntroductoryOffer = trial.eligible;
1
+ import { productVariablesFromTemplateVariables } from "../products";
2
+ export const buildSuperwallState = ({ variables, products, paywall, lastTransaction, permissionStatuses = {}, callbackStates = {}, introductoryOffer, }) => {
3
+ const productState = Object.fromEntries(productVariablesFromTemplateVariables(variables));
4
+ if (introductoryOffer?.eligible !== undefined) {
5
+ productState.hasIntroductoryOffer = introductoryOffer.eligible;
25
6
  }
26
7
  for (const product of products) {
27
- const existingProductState = productState[product.reference];
8
+ const existing = productState[product.reference];
28
9
  productState[product.reference] = {
29
- ...(isRecord(existingProductState) ? existingProductState : {}),
10
+ ...(typeof existing === "object" && existing !== null ? existing : {}),
30
11
  ...product.variables,
31
12
  productId: product.productId,
32
- productIdentifier: product.productIdentifier,
33
13
  source: product.source,
34
14
  };
35
15
  }
36
- const transactionState = {
37
- didAbandonTransaction: lastTransaction?.status === "abandoned",
38
- didCompleteTransaction: lastTransaction?.status === "completed",
39
- };
40
16
  productState.abandonedProductId =
41
17
  lastTransaction?.status === "abandoned" ? lastTransaction.product.reference : "";
42
18
  productState.purchasedProductId =
43
19
  lastTransaction?.status === "completed" ? lastTransaction.product.reference : "";
44
20
  if (lastTransaction) {
45
- const transactionProduct = lastTransaction.product;
46
21
  productState[lastTransaction.status === "completed" ? "purchased" : "abandoned"] =
47
- transactionProduct.variables;
22
+ lastTransaction.product.variables;
48
23
  }
49
- const state = {
24
+ return {
50
25
  ...variables,
51
- state: transactionState,
26
+ state: {
27
+ didAbandonTransaction: lastTransaction?.status === "abandoned",
28
+ didCompleteTransaction: lastTransaction?.status === "completed",
29
+ },
52
30
  products: productState,
53
31
  permissions: permissionStatuses,
54
32
  callbacks: callbackStates,
33
+ ...(paywall ? { paywall } : {}),
55
34
  };
56
- if (paywall) {
57
- state.paywall = paywall;
58
- }
59
- return state;
60
35
  };
@@ -1,7 +1,9 @@
1
- import type { TIncomingMessage, TIncomingMessageCallbackResult, TIncomingMessageTransactionAbandon, TIncomingMessageTransactionComplete, TOutgoingMessage } from "@superwall/protocol";
2
- import type { SuperwallBridge, SuperwallBridgeOptions, SuperwallMessageLogEntry } from "../bridge";
1
+ import type { ITransport, TEventTrackingBehavior, TIncomingMessage, TIncomingMessageCallbackResult, TIncomingMessageTransactionAbandon, TIncomingMessageTransactionComplete, TOutgoingMessage, TPermissionStatus, TPermissionTypeMessage, TransportKind } from "@superwall/protocol";
3
2
  import type { SuperwallConfig } from "../config";
4
- import type { SuperwallProduct } from "../products";
3
+ import type { SuperwallTranslateValues } from "../localization";
4
+ import type { SuperwallProduct, SuperwallProductInput } from "../products";
5
+ import type { Outgoing, PageViewInput } from "./outgoing";
6
+ import type { CallbackBehavior } from "./requests";
5
7
  import type { SuperwallCallbackStates, SuperwallPermissionStatuses, SuperwallSdkState } from "./state";
6
8
  import type { SuperwallDeviceVariables, SuperwallExperiment, SuperwallPlacementParams, SuperwallUserVariables } from "./variables";
7
9
  export type SuperwallRuntimeStatus = "idle" | "listening";
@@ -25,11 +27,21 @@ export type SuperwallTransaction<TProduct extends SuperwallProduct = SuperwallPr
25
27
  export type SuperwallPurchaseFailure<out TProduct extends SuperwallProduct = SuperwallProduct> = {
26
28
  status: "failed";
27
29
  product: TProduct;
28
- /**
29
- * "timeout": no transaction message arrived in time. "superseded": a newer
30
- * purchase for the same product, or a paywall re-open, replaced this one.
31
- */
32
- reason: "timeout" | "superseded";
30
+ reason: "sdk" | "superseded";
31
+ };
32
+ export type SuperwallRestoreState = {
33
+ status: "started" | "completed" | "failed";
34
+ };
35
+ /**
36
+ * How a restore ended.
37
+ *
38
+ * Deliberately no product list and no reason. The SDK announces a restored
39
+ * transaction with `transaction_restore`, which carries no payload, and reports
40
+ * "nothing to restore" as `restore_fail` like any other failure — the message it
41
+ * logs for that case never reaches the paywall.
42
+ */
43
+ export type SuperwallRestoreResult = {
44
+ status: "restored" | "failed";
33
45
  };
34
46
  export type SuperwallPurchaseResult<TProduct extends SuperwallProduct = SuperwallProduct> = SuperwallTransaction<TProduct> | SuperwallPurchaseFailure<TProduct>;
35
47
  export type SuperwallCallbackResult<TData = Record<string, unknown>> = {
@@ -37,11 +49,7 @@ export type SuperwallCallbackResult<TData = Record<string, unknown>> = {
37
49
  data?: TData;
38
50
  message: TIncomingMessageCallbackResult;
39
51
  };
40
- export type SuperwallTrialState = {
41
- /**
42
- * Whether the user is eligible for an introductory offer. `undefined` until
43
- * the SDK signals eligibility (or the config forces it).
44
- */
52
+ export type SuperwallIntroductoryOfferState = {
45
53
  eligible?: boolean;
46
54
  };
47
55
  export type SuperwallRuntimeSnapshot<out TProduct extends SuperwallProduct = SuperwallProduct> = {
@@ -55,39 +63,62 @@ export type SuperwallRuntimeSnapshot<out TProduct extends SuperwallProduct = Sup
55
63
  user: SuperwallUserVariables;
56
64
  params: SuperwallPlacementParams;
57
65
  experiment?: SuperwallExperiment;
58
- trial: SuperwallTrialState;
66
+ introductoryOffer: SuperwallIntroductoryOfferState;
67
+ restore?: SuperwallRestoreState;
68
+ eventTrackingBehavior?: TEventTrackingBehavior;
59
69
  locale: string;
60
70
  state: SuperwallSdkState;
61
71
  permissionStatuses: SuperwallPermissionStatuses;
62
72
  callbackStates: SuperwallCallbackStates;
63
- messages: readonly SuperwallMessageLogEntry[];
64
73
  pendingPurchase?: SuperwallPendingPurchase<TProduct>;
65
74
  lastTransaction?: SuperwallTransaction<TProduct>;
66
75
  lastPurchaseFailure?: SuperwallPurchaseFailure<TProduct>;
67
76
  };
68
77
  export type SuperwallPurchaseOptions = {
69
78
  shouldDismiss?: boolean;
70
- /** Resolve as `{ status: "failed", reason: "timeout" }` if no transaction message arrives in time. */
71
- timeoutMs?: number;
72
79
  };
80
+ export type SuperwallCallbackOptions = {
81
+ behavior?: CallbackBehavior;
82
+ variables?: Record<string, unknown>;
83
+ };
84
+ export type SuperwallEventName = TIncomingMessage["event_name"] | "message";
73
85
  export type SuperwallEventMap = {
74
- [E in TIncomingMessage["event_name"]]: Extract<TIncomingMessage, {
86
+ [E in SuperwallEventName]: E extends "message" ? TIncomingMessage : Extract<TIncomingMessage, {
75
87
  event_name: E;
76
88
  }>;
77
- } & {
78
- /** Fires for every incoming message. */
79
- message: TIncomingMessage;
80
89
  };
81
- export type SuperwallEventName = keyof SuperwallEventMap & string;
82
90
  export type SuperwallSessionStartOptions = {
83
91
  sendPing?: boolean;
84
- ping?: Partial<Extract<TOutgoingMessage, {
85
- event_name: "ping";
86
- }>>;
87
92
  };
88
- export type SuperwallSessionOptions<TProduct extends SuperwallProduct = SuperwallProduct> = SuperwallBridgeOptions & {
89
- bridge?: SuperwallBridge;
93
+ export type SuperwallSessionOptions = {
90
94
  config?: SuperwallConfig;
91
- products?: readonly TProduct[];
92
- variables?: Record<string, unknown>;
95
+ transport?: ITransport;
96
+ transportKind?: TransportKind;
97
+ onDecodeError?: (error: unknown) => void;
93
98
  };
99
+ export interface SuperwallSession<out TProduct extends SuperwallProduct = SuperwallProduct> {
100
+ on: <E extends SuperwallEventName>(event: E, handler: (payload: SuperwallEventMap[E]) => void) => () => void;
101
+ subscribe: (listener: () => void) => () => void;
102
+ getSnapshot: () => SuperwallRuntimeSnapshot<TProduct>;
103
+ t: (key: string, values?: SuperwallTranslateValues) => string;
104
+ setLocale: (locale: string | undefined) => void;
105
+ configure: (config: SuperwallConfig) => void;
106
+ start: (options?: SuperwallSessionStartOptions) => void;
107
+ postMessage: (message: TOutgoingMessage) => void;
108
+ accept: (messages: TIncomingMessage[]) => void;
109
+ accept64: (message: string) => void;
110
+ close: () => void;
111
+ restore: () => Promise<SuperwallRestoreResult>;
112
+ openUrl: (url: string, options?: {
113
+ browserType?: "payment_sheet";
114
+ }) => void;
115
+ openExternalUrl: (url: string) => void;
116
+ openDeepLink: (link: string) => void;
117
+ customPlacement: (name: string, params?: Record<string, unknown>) => void;
118
+ requestStoreReview: (reviewType: Outgoing<"request_store_review">["review_type"]) => void;
119
+ pageView: (input: PageViewInput) => void;
120
+ hapticFeedback: (hapticType: Outgoing<"haptic_feedback">["haptic_type"]) => void;
121
+ requestPermission: (permissionType: TPermissionTypeMessage) => Promise<TPermissionStatus>;
122
+ requestCallback: <TData extends Record<string, unknown> = Record<string, unknown>>(name: string, options?: SuperwallCallbackOptions) => Promise<SuperwallCallbackResult<TData>>;
123
+ purchase: (input: SuperwallProductInput, options?: SuperwallPurchaseOptions) => Promise<SuperwallPurchaseResult<TProduct>>;
124
+ }
@@ -36,13 +36,6 @@ export type SuperwallCapability = {
36
36
  name: string;
37
37
  eventNames?: readonly string[];
38
38
  };
39
- /**
40
- * Device variables the native SDK delivers via `template_variables`. The names
41
- * mirror the SDK's device template exactly — there is no index signature, so a
42
- * key the SDK does not send is a compile error rather than `undefined` on a
43
- * device. Every field is optional: availability varies by platform and SDK
44
- * version, and a paywall must render without any of them.
45
- */
46
39
  export type SuperwallDeviceVariables = {
47
40
  publicApiKey?: string;
48
41
  platform?: string;
@@ -70,6 +63,9 @@ export type SuperwallDeviceVariables = {
70
63
  interfaceStyleMode?: string;
71
64
  timezoneOffset?: number;
72
65
  radioType?: string;
66
+ fontSize?: number;
67
+ fontScale?: number;
68
+ preferredContentSizeCategory?: string;
73
69
  isLowPowerModeEnabled?: boolean;
74
70
  isApplePayAvailable?: boolean;
75
71
  isMac?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superwall/runtime",
3
- "version": "1.2.0",
3
+ "version": "1.3.0-beta.4",
4
4
  "description": "Framework-agnostic runtime for headless Superwall paywalls: bridge, session, products, localization, mock host.",
5
5
  "keywords": [
6
6
  "paywall",
@@ -39,9 +39,10 @@
39
39
  "clean": "rm -rf dist coverage"
40
40
  },
41
41
  "dependencies": {
42
- "@superwall/protocol": "1.2.0"
42
+ "@superwall/protocol": "1.3.0-beta.4"
43
43
  },
44
44
  "devDependencies": {
45
+ "@superwall/host": "workspace:*",
45
46
  "@types/node": "^22.0.0",
46
47
  "@vitest/coverage-v8": "^3.2.0",
47
48
  "typescript": "5.8.3",