@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
package/dist/config.d.ts DELETED
@@ -1,237 +0,0 @@
1
- import type { SuperwallProduct } from "./products";
2
- export declare const SUPERWALL_PLATFORMS: readonly ["ios", "android", "web"];
3
- export type SuperwallPlatform = (typeof SUPERWALL_PLATFORMS)[number];
4
- export declare const normalizePlatform: (value: string | undefined) => SuperwallPlatform | undefined;
5
- /**
6
- * A product slot the paywall renders, keyed by reference in
7
- * `SuperwallConfig["products"]`. Product data (price, period, trial…) is
8
- * SDK-owned and arrives at runtime; the mock host synthesizes it in dev.
9
- */
10
- export type SuperwallProductSlot = {
11
- /** Store product identifier this slot maps to (e.g. "pro_3999_year"). */
12
- productId?: string;
13
- };
14
- /**
15
- * One store identifier per platform the paywall ships to, for a slot whose
16
- * underlying product differs by store — the same `purchase("annual")` buys
17
- * the App Store product on iOS and the Play product on Android.
18
- */
19
- export type SuperwallPlatformProductIds = Partial<Record<SuperwallPlatform, string>>;
20
- /**
21
- * A slot object, the store product identifier as shorthand, or one
22
- * identifier per platform.
23
- */
24
- export type SuperwallProductSlotInput = string | SuperwallProductSlot | SuperwallPlatformProductIds;
25
- export declare const isPlatformProductIds: (input: SuperwallProductSlotInput) => input is SuperwallPlatformProductIds;
26
- /**
27
- * The store identifier a slot resolves to on a platform. A per-platform slot
28
- * with no entry for the platform resolves to nothing; with no platform known
29
- * at all it falls back to its first entry.
30
- */
31
- export declare const productIdFor: (input: SuperwallProductSlotInput, platform?: SuperwallPlatform) => string | undefined;
32
- export type SuperwallPresentationStyle = "fullscreen" | "modal" | "push" | "drawer" | "popup" | "noAnimation";
33
- export type SuperwallPresentationConfig = {
34
- /** How the native SDK presents the paywall. Defaults to "fullscreen". */
35
- style?: SuperwallPresentationStyle;
36
- /**
37
- * Drawer geometry, as percentages of the screen and points. Only read when
38
- * style is "drawer"; defaults to 70% height with a 15pt corner radius.
39
- */
40
- drawer?: {
41
- height?: number;
42
- cornerRadius?: number;
43
- };
44
- /**
45
- * Popup geometry, as percentages of the screen and points. Only read when
46
- * style is "popup"; defaults to 80% × 60% with a 15pt corner radius.
47
- */
48
- popup?: {
49
- width?: number;
50
- height?: number;
51
- cornerRadius?: number;
52
- };
53
- };
54
- export type PaywallPresentationStyleWire = {
55
- type: "FULLSCREEN" | "MODAL" | "PUSH" | "NO_ANIMATION";
56
- } | {
57
- type: "DRAWER";
58
- height: number;
59
- corner_radius: number;
60
- } | {
61
- type: "POPUP";
62
- width: number;
63
- height: number;
64
- corner_radius: number;
65
- };
66
- export type WebCheckoutDestinationWire = "EXTERNAL" | "PAYWALL_EMBEDDED" | "PAYWALL_APPLE_PAY";
67
- export type PaywallSettings = {
68
- presentation_style: PaywallPresentationStyleWire;
69
- feature_gating: "gated" | "non_gated";
70
- on_device_cache: boolean;
71
- scroll_enabled: boolean;
72
- game_controller_enabled: boolean;
73
- introductory_offer_eligibility: "automatic" | "always_eligible" | "always_ineligible";
74
- web_checkout_destination?: WebCheckoutDestinationWire;
75
- background_color_hex?: string;
76
- dark_background_color_hex?: string;
77
- };
78
- export declare const presentationStyleWire: (presentation: SuperwallPresentationConfig | undefined) => PaywallPresentationStyleWire;
79
- export declare const webCheckoutDestinationOf: (checkout: SuperwallCheckoutConfig | undefined) => WebCheckoutDestinationWire | undefined;
80
- export declare const paywallSettingsOf: (config: SuperwallConfig | undefined) => PaywallSettings;
81
- export type SuperwallTrialReminderStaticConfig = {
82
- enabled?: boolean;
83
- /** Notification title. Localizable: message keys resolve through `t()`. */
84
- title: string;
85
- subtitle?: string;
86
- /** Notification body. Localizable: message keys resolve through `t()`. */
87
- body: string;
88
- /** How many days before the trial ends the reminder fires. Defaults to 1. */
89
- beforeTrialEndDays?: number;
90
- };
91
- /** Context passed to a dynamic trial reminder function. */
92
- export type SuperwallTrialReminderContext = {
93
- /** When the trial ends, per the SDK. */
94
- trialEndDate: Date;
95
- /** Store identifier of the purchased product, when the SDK provides it. */
96
- productIdentifier?: string;
97
- /** The matching product, when it's one of this paywall's slots. */
98
- product?: SuperwallProduct;
99
- /** Translator for the active locale. */
100
- t: (key: string, values?: Record<string, string | number>) => string;
101
- locale: string;
102
- };
103
- /** What a dynamic trial reminder resolves to. */
104
- export type SuperwallTrialReminderNotification = {
105
- title: string;
106
- subtitle?: string;
107
- body: string;
108
- /** Milliseconds from now until the notification fires. */
109
- delayMs: number;
110
- };
111
- /**
112
- * Static config, or a function computing the notification from the trial
113
- * context (schedule time, localized copy, per-product logic). Return null
114
- * from the function to skip scheduling.
115
- */
116
- export type SuperwallTrialReminderConfig = SuperwallTrialReminderStaticConfig | ((context: SuperwallTrialReminderContext) => SuperwallTrialReminderNotification | null | undefined);
117
- export type SuperwallNotificationsConfig = {
118
- /** Auto-scheduled when the SDK reports a trial started (`freeTrial_start`). */
119
- trialReminder?: SuperwallTrialReminderConfig;
120
- };
121
- /**
122
- * Nested message catalog for one locale. Values interpolate `{name}` params:
123
- * `{ paywall: { title: "Unlock {appName}" } }` → `t("paywall.title", { appName })`.
124
- */
125
- export type SuperwallMessages = {
126
- [key: string]: string | SuperwallMessages;
127
- };
128
- export type SuperwallLocalizationConfig<TLocale extends string = string> = {
129
- /** Locale used when the device locale has no catalog. */
130
- defaultLocale: TLocale;
131
- /** Message catalogs by locale (e.g. `{ en, de, "pt-BR": ptBR }`). */
132
- messages?: Record<TLocale, SuperwallMessages> & Record<string, SuperwallMessages>;
133
- };
134
- /**
135
- * How a purchase completes on the web. Native hosts ignore it — they always
136
- * buy through the store.
137
- *
138
- * - `external` — leave for Superwall's hosted checkout page and come back.
139
- * - `sheet` — take payment in the paywall, in a sheet Superwall renders.
140
- * - `applePay` — go straight to Apple Pay, falling back to the sheet where
141
- * Apple Pay is unavailable.
142
- *
143
- * The sheet's appearance is fixed and takes nothing from the paywall around
144
- * it. Payment UI that borrows a paywall's fonts and colors stops looking like
145
- * payment UI, which is the one place a shopper is entitled to see something
146
- * they recognize.
147
- *
148
- * `sheet` and `applePay` carry Stripe's payment UI into the bundle; `external`
149
- * costs nothing. Read this before shipping either:
150
- * https://superwall.com/docs/web-checkout
151
- */
152
- export type SuperwallCheckoutMode = "external" | "sheet" | "applePay";
153
- export type SuperwallCheckoutConfig = SuperwallCheckoutMode | {
154
- mode: SuperwallCheckoutMode;
155
- prefetch?: string | false;
156
- };
157
- export declare const checkoutModeOf: (checkout: SuperwallCheckoutConfig | undefined) => SuperwallCheckoutMode | undefined;
158
- export declare const checkoutPrefetchOf: (checkout: SuperwallCheckoutConfig | undefined) => string | false | undefined;
159
- /**
160
- * A paywall's background color. The string shorthand sets light mode; the
161
- * object form adds a dark-mode color. Native SDKs paint it behind the webview
162
- * (and derive the loading spinner from it), and the web document paints it as
163
- * the page background — so the color a shopper sees while the paywall loads
164
- * matches the color it settles on.
165
- */
166
- export type SuperwallBackgroundConfig = string | {
167
- light: string;
168
- dark?: string;
169
- };
170
- export type ResolvedBackground = {
171
- light: string;
172
- dark?: string;
173
- };
174
- export declare const backgroundOf: (background: SuperwallBackgroundConfig | undefined) => ResolvedBackground | undefined;
175
- export type SuperwallConfig<TLocale extends string = string> = {
176
- /** Product slots this paywall renders, keyed by reference. */
177
- products?: Record<string, SuperwallProductSlotInput>;
178
- /**
179
- * How a purchase completes on the web. Omit it for native-only paywalls —
180
- * nothing about checkout is bundled unless this asks for it.
181
- */
182
- checkout?: SuperwallCheckoutConfig;
183
- /** How the native SDK presents the paywall: style and drawer/popup geometry. */
184
- presentation?: SuperwallPresentationConfig;
185
- /**
186
- * Background color painted behind the paywall while it loads and as the web
187
- * document background. String shorthand = light mode; `{ light, dark }` adds
188
- * a dark-mode color.
189
- */
190
- background?: SuperwallBackgroundConfig;
191
- /**
192
- * Whether the feature behind the placement is gated on a purchase.
193
- * Defaults to "nonGated".
194
- */
195
- featureGating?: "gated" | "nonGated";
196
- /** Trial eligibility handling. Defaults to "automatic" (SDK decides). */
197
- introductoryOfferEligibility?: "automatic" | "alwaysEligible" | "alwaysIneligible";
198
- /** Forward game controller input to the paywall. Defaults to false. */
199
- gameControllerEnabled?: boolean;
200
- /** Whether the webview scrolls. Defaults to true. */
201
- scrollEnabled?: boolean;
202
- /** Cache the paywall on device for instant presentation. Defaults to true. */
203
- onDeviceCacheEnabled?: boolean;
204
- /** Dismiss the paywall automatically after a completed purchase. */
205
- dismissOnPurchase?: boolean;
206
- /** Resolve pending purchases as failed after this many ms without a transaction. */
207
- purchaseTimeoutMs?: number;
208
- /** Local notifications the paywall schedules (e.g. trial reminders). */
209
- notifications?: SuperwallNotificationsConfig;
210
- /** Message catalogs and default locale for `t()`. */
211
- localization?: SuperwallLocalizationConfig<TLocale>;
212
- };
213
- /**
214
- * Declares the paywall's contract: product slots, presentation, gating,
215
- * notifications, and localization. Consumed by the runtime session at render
216
- * time and by the Superwall build pipeline at push time.
217
- */
218
- export declare const defineSuperwallConfig: <TLocale extends string = string>(config: SuperwallConfig<TLocale>) => SuperwallConfig<TLocale>;
219
- export declare const normalizeProductSlot: (input: SuperwallProductSlotInput, platform?: SuperwallPlatform) => SuperwallProductSlot;
220
- export declare const checkoutNeedsPaymentUi: (checkout: SuperwallCheckoutConfig | undefined) => boolean;
221
- /**
222
- * Materializes the config's product slots as products so references exist
223
- * before the SDK (or mock host) delivers real product data.
224
- */
225
- export declare const productsFromConfig: (config: SuperwallConfig | undefined, platform?: SuperwallPlatform) => SuperwallProduct[];
226
- /** @deprecated Use `SuperwallConfig`. */
227
- export type SuperwallPaywallConfig<TLocale extends string = string> = SuperwallConfig<TLocale>;
228
- /** The framework's paywall generation — v4 is the visual editor, v5 is code. */
229
- export declare const SUPERWALL_GENERATION = 5;
230
- /**
231
- * Document semantics as `<html>` data attributes — the snapshot's half of the
232
- * two-layer contract. The build stamps these statically (no flash before
233
- * hydration) and `SuperwallProvider` reasserts them at runtime (dev has no
234
- * build step). The platform's serve-time stylesheet (live.css) owns what they
235
- * mean, so their interpretation can evolve fleet-wide without republishing.
236
- */
237
- export declare const documentAttributes: (config: SuperwallConfig | undefined) => Record<string, string>;
package/dist/config.js DELETED
@@ -1,138 +0,0 @@
1
- export const SUPERWALL_PLATFORMS = ["ios", "android", "web"];
2
- export const normalizePlatform = (value) => {
3
- const normalized = (value ?? "").toLowerCase();
4
- return SUPERWALL_PLATFORMS.find((platform) => platform === normalized);
5
- };
6
- export const isPlatformProductIds = (input) => typeof input === "object" && input !== null && !("productId" in input);
7
- /**
8
- * The store identifier a slot resolves to on a platform. A per-platform slot
9
- * with no entry for the platform resolves to nothing; with no platform known
10
- * at all it falls back to its first entry.
11
- */
12
- export const productIdFor = (input, platform) => {
13
- if (typeof input === "string")
14
- return input;
15
- if (!isPlatformProductIds(input))
16
- return input.productId;
17
- if (platform !== undefined)
18
- return input[platform];
19
- return Object.values(input).find((id) => typeof id === "string");
20
- };
21
- const DRAWER_DEFAULTS = { height: 70, cornerRadius: 15 };
22
- const POPUP_DEFAULTS = { width: 80, height: 60, cornerRadius: 15 };
23
- const dimension = (label, value, fallback) => {
24
- const resolved = value ?? fallback;
25
- if (!Number.isFinite(resolved) || resolved <= 0) {
26
- throw new Error(`presentation.${label} must be a positive number, got ${String(value)}`);
27
- }
28
- return resolved;
29
- };
30
- export const presentationStyleWire = (presentation) => {
31
- switch (presentation?.style ?? "fullscreen") {
32
- case "fullscreen":
33
- return { type: "FULLSCREEN" };
34
- case "modal":
35
- return { type: "MODAL" };
36
- case "push":
37
- return { type: "PUSH" };
38
- case "noAnimation":
39
- return { type: "NO_ANIMATION" };
40
- case "drawer":
41
- return {
42
- type: "DRAWER",
43
- height: dimension("drawer.height", presentation?.drawer?.height, DRAWER_DEFAULTS.height),
44
- corner_radius: dimension("drawer.cornerRadius", presentation?.drawer?.cornerRadius, DRAWER_DEFAULTS.cornerRadius),
45
- };
46
- case "popup":
47
- return {
48
- type: "POPUP",
49
- width: dimension("popup.width", presentation?.popup?.width, POPUP_DEFAULTS.width),
50
- height: dimension("popup.height", presentation?.popup?.height, POPUP_DEFAULTS.height),
51
- corner_radius: dimension("popup.cornerRadius", presentation?.popup?.cornerRadius, POPUP_DEFAULTS.cornerRadius),
52
- };
53
- }
54
- };
55
- const ELIGIBILITY_WIRE = {
56
- automatic: "automatic",
57
- alwaysEligible: "always_eligible",
58
- alwaysIneligible: "always_ineligible",
59
- };
60
- const CHECKOUT_WIRE = {
61
- external: "EXTERNAL",
62
- sheet: "PAYWALL_EMBEDDED",
63
- applePay: "PAYWALL_APPLE_PAY",
64
- };
65
- export const webCheckoutDestinationOf = (checkout) => {
66
- const mode = checkoutModeOf(checkout);
67
- return mode === undefined ? undefined : CHECKOUT_WIRE[mode];
68
- };
69
- export const paywallSettingsOf = (config) => {
70
- const background = backgroundOf(config?.background);
71
- const destination = webCheckoutDestinationOf(config?.checkout);
72
- return {
73
- presentation_style: presentationStyleWire(config?.presentation),
74
- feature_gating: config?.featureGating === "gated" ? "gated" : "non_gated",
75
- on_device_cache: config?.onDeviceCacheEnabled ?? true,
76
- scroll_enabled: config?.scrollEnabled ?? true,
77
- game_controller_enabled: config?.gameControllerEnabled ?? false,
78
- introductory_offer_eligibility: ELIGIBILITY_WIRE[config?.introductoryOfferEligibility ?? "automatic"],
79
- ...(destination === undefined ? {} : { web_checkout_destination: destination }),
80
- ...(background === undefined ? {} : { background_color_hex: background.light }),
81
- ...(background?.dark === undefined ? {} : { dark_background_color_hex: background.dark }),
82
- };
83
- };
84
- export const checkoutModeOf = (checkout) => (typeof checkout === "string" ? checkout : checkout?.mode);
85
- export const checkoutPrefetchOf = (checkout) => (typeof checkout === "object" ? checkout.prefetch : undefined);
86
- export const backgroundOf = (background) => {
87
- if (background === undefined)
88
- return undefined;
89
- if (typeof background === "string") {
90
- const light = background.trim();
91
- return light === "" ? undefined : { light };
92
- }
93
- const light = background.light?.trim();
94
- if (!light)
95
- return undefined;
96
- const dark = background.dark?.trim();
97
- return dark ? { light, dark } : { light };
98
- };
99
- /**
100
- * Declares the paywall's contract: product slots, presentation, gating,
101
- * notifications, and localization. Consumed by the runtime session at render
102
- * time and by the Superwall build pipeline at push time.
103
- */
104
- export const defineSuperwallConfig = (config) => config;
105
- export const normalizeProductSlot = (input, platform) => ({ productId: productIdFor(input, platform) });
106
- export const checkoutNeedsPaymentUi = (checkout) => {
107
- const mode = checkoutModeOf(checkout);
108
- return mode === "sheet" || mode === "applePay";
109
- };
110
- /**
111
- * Materializes the config's product slots as products so references exist
112
- * before the SDK (or mock host) delivers real product data.
113
- */
114
- export const productsFromConfig = (config, platform) => Object.entries(config?.products ?? {}).map(([reference, input]) => {
115
- const slot = normalizeProductSlot(input, platform);
116
- return {
117
- reference,
118
- product: reference,
119
- id: slot.productId,
120
- productId: slot.productId,
121
- productIdentifier: slot.productId,
122
- variables: {},
123
- source: "inline",
124
- };
125
- });
126
- /** The framework's paywall generation — v4 is the visual editor, v5 is code. */
127
- export const SUPERWALL_GENERATION = 5;
128
- /**
129
- * Document semantics as `<html>` data attributes — the snapshot's half of the
130
- * two-layer contract. The build stamps these statically (no flash before
131
- * hydration) and `SuperwallProvider` reasserts them at runtime (dev has no
132
- * build step). The platform's serve-time stylesheet (live.css) owns what they
133
- * mean, so their interpretation can evolve fleet-wide without republishing.
134
- */
135
- export const documentAttributes = (config) => ({
136
- "data-sw-generation": String(SUPERWALL_GENERATION),
137
- "data-sw-scroll": String(config?.scrollEnabled ?? true),
138
- });
package/dist/mock.d.ts DELETED
@@ -1,74 +0,0 @@
1
- import type { ITransport, TIncomingHandler, TIncomingMessage, TIncomingMessageCallbackResult, TOutgoingMessage, TPermissionStatus, TPermissionTypeMessage } from "@superwall/protocol";
2
- import { type SuperwallConfig } from "./config";
3
- import { type SuperwallProduct, type SuperwallProductInput } from "./products";
4
- import type { SuperwallDeviceVariables, SuperwallExperiment, SuperwallPlacementParams, SuperwallUserVariables } from "./session/variables";
5
- export type SuperwallMockPurchaseOutcome = "completed" | "abandoned";
6
- export type SuperwallMockPurchaseContext = {
7
- reference: string;
8
- productIdentifier?: string;
9
- };
10
- export type SuperwallMockCallbackResult = {
11
- status: TIncomingMessageCallbackResult["status"];
12
- data?: Record<string, unknown>;
13
- };
14
- export type SuperwallMockOptions = {
15
- /** Identity sent in `paywall_open`. */
16
- paywall?: {
17
- id?: string;
18
- identifier?: string;
19
- };
20
- /**
21
- * Products the mock SDK delivers. Defaults to the config's product slots,
22
- * carrying only the product identifier — real product data comes from
23
- * Superwall, never from the mock.
24
- */
25
- products?: readonly SuperwallProductInput[];
26
- /** Device variables merged over the mock defaults. */
27
- device?: SuperwallDeviceVariables;
28
- /** User attributes delivered with template variables. */
29
- user?: SuperwallUserVariables;
30
- /** Placement params delivered with template variables. */
31
- params?: SuperwallPlacementParams;
32
- /** Experiment assignment to report. Omitted by default. */
33
- experiment?: SuperwallExperiment;
34
- /** Extra top-level template variables. */
35
- variables?: Record<string, unknown>;
36
- /**
37
- * Introductory-offer eligibility the mock reports. Defaults to true when
38
- * any product has trial variables.
39
- */
40
- trialEligible?: boolean;
41
- purchaseOutcome?: SuperwallMockPurchaseOutcome | ((context: SuperwallMockPurchaseContext) => SuperwallMockPurchaseOutcome | Promise<SuperwallMockPurchaseOutcome>);
42
- /** Whether restore emits a `transaction_complete`. Defaults to "completed". */
43
- restoreOutcome?: "completed" | "none";
44
- /** Permission request responses. Defaults to "granted". */
45
- permissions?: Partial<Record<TPermissionTypeMessage, TPermissionStatus>>;
46
- /** Answers a permission request per call, for hosts that decide at runtime. */
47
- onPermission?: (permissionType: TPermissionTypeMessage) => TPermissionStatus | Promise<TPermissionStatus>;
48
- /** Answers a callback request per call, for hosts that decide at runtime. */
49
- onCallback?: (name: string, variables?: Record<string, unknown>) => SuperwallMockCallbackResult | Promise<SuperwallMockCallbackResult>;
50
- callbacks?: Record<string, SuperwallMockCallbackResult | ((variables?: Record<string, unknown>) => SuperwallMockCallbackResult | Promise<SuperwallMockCallbackResult>)>;
51
- /** Simulated SDK response delay. Defaults to 0. */
52
- latencyMs?: number;
53
- /** Observe every message the paywall sends to the mock host. */
54
- onOutgoing?: (message: TOutgoingMessage) => void;
55
- };
56
- export declare const MOCK_DEVICE_VARIABLES: SuperwallDeviceVariables;
57
- export declare const mockProductsFromConfig: (config: SuperwallConfig | undefined, devicePlatform?: string) => SuperwallProduct[];
58
- export declare const mockOptionsFromConfig: (config: SuperwallConfig | undefined, options?: SuperwallMockOptions) => SuperwallMockOptions;
59
- export declare class MockSuperwallTransport implements ITransport {
60
- private handlers;
61
- private listening;
62
- private options;
63
- private products;
64
- constructor(options?: SuperwallMockOptions);
65
- addListener(handler: TIncomingHandler): void;
66
- startListening(): void;
67
- accept(message: TIncomingMessage): void;
68
- postMessage(message: TOutgoingMessage): void;
69
- private get trialEligible();
70
- private respond;
71
- private handleOutgoing;
72
- private resolvePurchaseOutcome;
73
- }
74
- export declare const createMockSuperwallTransport: (options?: SuperwallMockOptions) => MockSuperwallTransport;
package/dist/mock.js DELETED
@@ -1,206 +0,0 @@
1
- import { normalizePlatform, normalizeProductSlot } from "./config";
2
- import { createSuperwallProduct, } from "./products";
3
- export const MOCK_DEVICE_VARIABLES = {
4
- platform: "iOS",
5
- deviceModel: "iPhone17,2",
6
- osVersion: "18.0",
7
- appVersion: "1.0.0",
8
- deviceLocale: "en_US",
9
- deviceLanguageCode: "en",
10
- regionCode: "US",
11
- preferredLocale: "en-US",
12
- preferredLanguageCode: "en",
13
- preferredRegionCode: "US",
14
- deviceCurrencyCode: "USD",
15
- deviceCurrencySymbol: "$",
16
- interfaceStyle: "Light",
17
- isSandbox: "true",
18
- sdkVersion: "4.0.0",
19
- daysSinceInstall: 0,
20
- totalPaywallViews: 1,
21
- };
22
- export const mockProductsFromConfig = (config, devicePlatform) => Object.entries(config?.products ?? {}).map(([reference, input]) => {
23
- const slot = normalizeProductSlot(input, normalizePlatform(devicePlatform));
24
- const productId = slot.productId ?? reference;
25
- return {
26
- reference,
27
- product: reference,
28
- id: productId,
29
- productId,
30
- productIdentifier: productId,
31
- variables: { identifier: productId },
32
- source: "placeholder",
33
- };
34
- });
35
- export const mockOptionsFromConfig = (config, options = {}) => ({
36
- ...options,
37
- products: options.products ??
38
- mockProductsFromConfig(config, typeof options.device?.platform === "string" ? options.device.platform : undefined),
39
- });
40
- const DAY_MS = 24 * 60 * 60 * 1000;
41
- const trialPeriodDaysOf = (product) => {
42
- // The SDK sends period counts as strings ("7"), so a `typeof === "number"`
43
- // check silently reports every product as trial-less on a device.
44
- const days = Number(product.variables.trialPeriodDays);
45
- return Number.isFinite(days) ? days : 0;
46
- };
47
- export class MockSuperwallTransport {
48
- handlers = [];
49
- listening = false;
50
- options;
51
- products;
52
- constructor(options = {}) {
53
- this.options = options;
54
- this.products = (options.products ?? []).map((input) => {
55
- const product = createSuperwallProduct(input);
56
- return product.source === "unknown" ? { ...product, source: "placeholder" } : product;
57
- });
58
- }
59
- addListener(handler) {
60
- this.handlers.push(handler);
61
- }
62
- startListening() {
63
- this.listening = true;
64
- }
65
- accept(message) {
66
- if (!this.listening)
67
- return;
68
- this.handlers.forEach((handler) => handler(message));
69
- }
70
- postMessage(message) {
71
- this.options.onOutgoing?.(message);
72
- this.handleOutgoing(message).catch((error) => {
73
- console.error("[MockSuperwallTransport] Failed to handle outgoing message", {
74
- event: message.event_name,
75
- error,
76
- });
77
- });
78
- }
79
- get trialEligible() {
80
- return (this.options.trialEligible ?? this.products.some((product) => trialPeriodDaysOf(product) > 0));
81
- }
82
- respond(messages) {
83
- const deliver = () => {
84
- messages.forEach((message) => this.accept(message));
85
- };
86
- const latency = this.options.latencyMs ?? 0;
87
- if (latency > 0) {
88
- setTimeout(deliver, latency);
89
- }
90
- else {
91
- queueMicrotask(deliver);
92
- }
93
- }
94
- async handleOutgoing(message) {
95
- switch (message.event_name) {
96
- case "ping": {
97
- const replies = [
98
- {
99
- event_name: "paywall_open",
100
- paywall_id: this.options.paywall?.id ?? "mock-paywall",
101
- paywall_identifier: this.options.paywall?.identifier ?? "mock-paywall-identifier",
102
- },
103
- {
104
- event_name: "products",
105
- products: this.products.map((product) => ({
106
- product: product.reference,
107
- productId: product.productIdentifier ?? product.productId ?? product.reference,
108
- })),
109
- },
110
- {
111
- event_name: "template_variables",
112
- variables: {
113
- ...this.options.variables,
114
- device: { ...MOCK_DEVICE_VARIABLES, ...this.options.device },
115
- user: this.options.user ?? {},
116
- params: this.options.params ?? {},
117
- products: [
118
- Object.fromEntries(this.products.map((product) => [product.reference, product.variables])),
119
- ],
120
- },
121
- },
122
- {
123
- event_name: "template_substitutions_prefix",
124
- prefix: this.trialEligible ? "freeTrial" : null,
125
- },
126
- ];
127
- if (this.options.experiment) {
128
- replies.push({ event_name: "experiment", ...this.options.experiment });
129
- }
130
- this.respond(replies);
131
- break;
132
- }
133
- case "purchase": {
134
- const outcome = await this.resolvePurchaseOutcome({
135
- reference: message.product,
136
- productIdentifier: message.product_identifier,
137
- });
138
- const replies = [
139
- {
140
- event_name: outcome === "completed" ? "transaction_complete" : "transaction_abandon",
141
- product: message.product,
142
- product_identifier: message.product_identifier,
143
- },
144
- ];
145
- const product = this.products.find((candidate) => candidate.reference === message.product);
146
- const trialDays = product ? trialPeriodDaysOf(product) : 0;
147
- if (outcome === "completed" && this.trialEligible && trialDays > 0) {
148
- replies.push({
149
- event_name: "freeTrial_start",
150
- product_identifier: message.product_identifier,
151
- trial_end_date: new Date(Date.now() + trialDays * DAY_MS).toISOString(),
152
- });
153
- }
154
- this.respond(replies);
155
- break;
156
- }
157
- case "restore": {
158
- if ((this.options.restoreOutcome ?? "completed") === "completed") {
159
- this.respond([{ event_name: "transaction_complete" }]);
160
- }
161
- break;
162
- }
163
- case "request_permission": {
164
- const status = this.options.permissions?.[message.permission_type] ??
165
- (this.options.onPermission
166
- ? await this.options.onPermission(message.permission_type)
167
- : "granted");
168
- this.respond([
169
- {
170
- event_name: "permission_result",
171
- permission_type: message.permission_type,
172
- request_id: message.request_id,
173
- status,
174
- },
175
- ]);
176
- break;
177
- }
178
- case "request_callback": {
179
- const callback = this.options.callbacks?.[message.name];
180
- const result = typeof callback === "function"
181
- ? await callback(message.variables)
182
- : (callback ??
183
- (this.options.onCallback
184
- ? await this.options.onCallback(message.name, message.variables)
185
- : { status: "success" }));
186
- this.respond([
187
- {
188
- event_name: "callback_result",
189
- request_id: message.request_id,
190
- name: message.name,
191
- status: result.status,
192
- data: result.data,
193
- },
194
- ]);
195
- break;
196
- }
197
- default:
198
- break;
199
- }
200
- }
201
- resolvePurchaseOutcome(context) {
202
- const outcome = this.options.purchaseOutcome ?? "completed";
203
- return typeof outcome === "function" ? outcome(context) : outcome;
204
- }
205
- }
206
- export const createMockSuperwallTransport = (options = {}) => new MockSuperwallTransport(options);