@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
@@ -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
+ };
@@ -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,10 @@ 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";
33
34
  };
34
35
  export type SuperwallPurchaseResult<TProduct extends SuperwallProduct = SuperwallProduct> = SuperwallTransaction<TProduct> | SuperwallPurchaseFailure<TProduct>;
35
36
  export type SuperwallCallbackResult<TData = Record<string, unknown>> = {
@@ -37,11 +38,7 @@ export type SuperwallCallbackResult<TData = Record<string, unknown>> = {
37
38
  data?: TData;
38
39
  message: TIncomingMessageCallbackResult;
39
40
  };
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
- */
41
+ export type SuperwallIntroductoryOfferState = {
45
42
  eligible?: boolean;
46
43
  };
47
44
  export type SuperwallRuntimeSnapshot<out TProduct extends SuperwallProduct = SuperwallProduct> = {
@@ -55,39 +52,62 @@ export type SuperwallRuntimeSnapshot<out TProduct extends SuperwallProduct = Sup
55
52
  user: SuperwallUserVariables;
56
53
  params: SuperwallPlacementParams;
57
54
  experiment?: SuperwallExperiment;
58
- trial: SuperwallTrialState;
55
+ introductoryOffer: SuperwallIntroductoryOfferState;
56
+ restore?: SuperwallRestoreState;
57
+ eventTrackingBehavior?: TEventTrackingBehavior;
59
58
  locale: string;
60
59
  state: SuperwallSdkState;
61
60
  permissionStatuses: SuperwallPermissionStatuses;
62
61
  callbackStates: SuperwallCallbackStates;
63
- messages: readonly SuperwallMessageLogEntry[];
64
62
  pendingPurchase?: SuperwallPendingPurchase<TProduct>;
65
63
  lastTransaction?: SuperwallTransaction<TProduct>;
66
64
  lastPurchaseFailure?: SuperwallPurchaseFailure<TProduct>;
67
65
  };
68
66
  export type SuperwallPurchaseOptions = {
69
67
  shouldDismiss?: boolean;
70
- /** Resolve as `{ status: "failed", reason: "timeout" }` if no transaction message arrives in time. */
71
- timeoutMs?: number;
72
68
  };
69
+ export type SuperwallCallbackOptions = {
70
+ behavior?: CallbackBehavior;
71
+ variables?: Record<string, unknown>;
72
+ };
73
+ export type SuperwallEventName = TIncomingMessage["event_name"] | "message";
73
74
  export type SuperwallEventMap = {
74
- [E in TIncomingMessage["event_name"]]: Extract<TIncomingMessage, {
75
+ [E in SuperwallEventName]: E extends "message" ? TIncomingMessage : Extract<TIncomingMessage, {
75
76
  event_name: E;
76
77
  }>;
77
- } & {
78
- /** Fires for every incoming message. */
79
- message: TIncomingMessage;
80
78
  };
81
- export type SuperwallEventName = keyof SuperwallEventMap & string;
82
79
  export type SuperwallSessionStartOptions = {
83
80
  sendPing?: boolean;
84
- ping?: Partial<Extract<TOutgoingMessage, {
85
- event_name: "ping";
86
- }>>;
87
81
  };
88
- export type SuperwallSessionOptions<TProduct extends SuperwallProduct = SuperwallProduct> = SuperwallBridgeOptions & {
89
- bridge?: SuperwallBridge;
82
+ export type SuperwallSessionOptions = {
90
83
  config?: SuperwallConfig;
91
- products?: readonly TProduct[];
92
- variables?: Record<string, unknown>;
84
+ transport?: ITransport;
85
+ transportKind?: TransportKind;
86
+ onDecodeError?: (error: unknown) => void;
93
87
  };
88
+ export interface SuperwallSession<out TProduct extends SuperwallProduct = SuperwallProduct> {
89
+ on: <E extends SuperwallEventName>(event: E, handler: (payload: SuperwallEventMap[E]) => void) => () => void;
90
+ subscribe: (listener: () => void) => () => void;
91
+ getSnapshot: () => SuperwallRuntimeSnapshot<TProduct>;
92
+ t: (key: string, values?: SuperwallTranslateValues) => string;
93
+ setLocale: (locale: string | undefined) => void;
94
+ configure: (config: SuperwallConfig) => void;
95
+ start: (options?: SuperwallSessionStartOptions) => void;
96
+ postMessage: (message: TOutgoingMessage) => void;
97
+ accept: (messages: TIncomingMessage[]) => void;
98
+ accept64: (message: string) => void;
99
+ close: () => void;
100
+ restore: () => void;
101
+ openUrl: (url: string, options?: {
102
+ browserType?: "payment_sheet";
103
+ }) => void;
104
+ openExternalUrl: (url: string) => void;
105
+ openDeepLink: (link: string) => void;
106
+ customPlacement: (name: string, params?: Record<string, unknown>) => void;
107
+ requestStoreReview: (reviewType: Outgoing<"request_store_review">["review_type"]) => void;
108
+ pageView: (input: PageViewInput) => void;
109
+ hapticFeedback: (hapticType: Outgoing<"haptic_feedback">["haptic_type"]) => void;
110
+ requestPermission: (permissionType: TPermissionTypeMessage) => Promise<TPermissionStatus>;
111
+ requestCallback: <TData extends Record<string, unknown> = Record<string, unknown>>(name: string, options?: SuperwallCallbackOptions) => Promise<SuperwallCallbackResult<TData>>;
112
+ purchase: (input: SuperwallProductInput, options?: SuperwallPurchaseOptions) => Promise<SuperwallPurchaseResult<TProduct>>;
113
+ }
@@ -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.1.1",
3
+ "version": "1.3.0-beta.3",
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.1.1"
42
+ "@superwall/protocol": "1.3.0-beta.3"
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",
@@ -1,56 +1,20 @@
1
1
  import type { TIncomingMessage } from "@superwall/protocol";
2
2
 
3
- type BufferLike = {
4
- from(
5
- input: string,
6
- encoding: "base64",
7
- ): {
8
- toString(encoding: "utf8"): string;
9
- };
10
- };
11
-
12
- type GlobalWithBuffer = typeof globalThis & {
13
- Buffer?: BufferLike;
14
- };
15
-
16
- /**
17
- * Host SDKs may encode with URL-safe alphabets and without padding (e.g.
18
- * Android's Base64.URL_SAFE). atob is strict, so normalize first.
19
- */
20
- const normalizeBase64 = (input: string) => {
3
+ const normalizeBase64 = (input: string): string => {
21
4
  const standard = input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
22
5
  const remainder = standard.length % 4;
23
- return remainder === 0 ? standard : standard + "=".repeat((4 - remainder) % 4);
6
+ return remainder === 0 ? standard : standard + "=".repeat(4 - remainder);
24
7
  };
25
8
 
26
- export const decodeBase64Utf8 = (message: string) => {
27
- if (typeof globalThis.atob === "function") {
28
- const binary = globalThis.atob(normalizeBase64(message));
29
- const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
30
- return new TextDecoder().decode(bytes);
31
- }
32
-
33
- const buffer = (globalThis as GlobalWithBuffer).Buffer;
34
- if (buffer) {
35
- return buffer.from(normalizeBase64(message), "base64").toString("utf8");
36
- }
37
-
38
- throw new Error("No base64 decoder is available in this runtime");
9
+ export const decodeBase64Utf8 = (message: string): string => {
10
+ const binary = atob(normalizeBase64(message));
11
+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
39
12
  };
40
13
 
41
- /**
42
- * Deliberately lenient, matching the original runtime: every object in the
43
- * batch is delivered, including messages this build doesn't recognize (newer
44
- * event types, or legacy quirks like the miscased `eventName: "experiment"`).
45
- * Strictly validating here would let one unknown message drop the whole batch.
46
- */
47
- export const decodeIncomingMessages = (message: string): TIncomingMessage[] => {
48
- const parsed = JSON.parse(decodeBase64Utf8(message));
49
- if (!Array.isArray(parsed)) {
50
- return [];
51
- }
14
+ const isMessageLike = (entry: unknown): entry is TIncomingMessage =>
15
+ typeof entry === "object" && entry !== null;
52
16
 
53
- return parsed.filter(
54
- (entry): entry is TIncomingMessage => typeof entry === "object" && entry !== null,
55
- );
17
+ export const decodeIncomingMessages = (message: string): TIncomingMessage[] => {
18
+ const parsed: unknown = JSON.parse(decodeBase64Utf8(message));
19
+ return Array.isArray(parsed) ? parsed.filter(isMessageLike) : [];
56
20
  };