@superwall/runtime 1.2.0 → 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/README.md CHANGED
@@ -20,48 +20,44 @@ npm install @superwall/runtime
20
20
  You will not usually install this directly: the
21
21
  [`superwall`](https://www.npmjs.com/package/superwall) framework depends on
22
22
  it and exposes everything here through its hooks. Reach for it alone when a
23
- paywall is not React, or when a host (the studio, the dashboard, a test
24
- harness) needs the session model without a UI.
23
+ paywall is not React.
25
24
 
26
25
  ## What's here
27
26
 
28
- This package is the runtime boundary shared by every paywall Superwall
29
- serves — built with this framework or with the visual editor. It owns
30
- transport selection, message logging, base64 message ingestion, product
31
- state, localization, SDK action dispatch, and purchase promise resolution.
32
- It must not import React, or anything above it in the stack.
33
-
34
- - **`SuperwallBridge`** — transport auto-detection (WebKit / Android / editor
35
- iframe), message log, `accept` / `accept64` ingestion, `postMessage`.
36
- - **`SuperwallSession`** — the runtime model on top of the bridge:
37
- - product state merged from `products` + `template_variables`
38
- - `device` / `user` / `params` variables, `experiment` assignment
39
- - trial eligibility from `template_substitutions_prefix` ("freeTrial")
40
- - locale resolution + `t()` translation from the config's message catalogs
41
- - promise-based `purchase()` with timeout, resolved by transaction messages
42
- - auto-scheduled trial reminder notifications on `freeTrial_start`
43
- - typed events: `session.on("paywall_open", …)`, `"message"` for all
44
- - **`MockSuperwallTransport`** — a simulated native SDK host for local dev,
45
- dashboard previews, tests, and the build-time conformance harness.
27
+ This package is the paywall side of the SDK protocol. It owns transport
28
+ selection, base64 message ingestion, product state, localization, action
29
+ dispatch, and purchase promise resolution. It must not import React, or
30
+ anything above it in the stack. Hosts live elsewhere: the native SDKs, the
31
+ web host, and
32
+ [`@superwall/host`](https://github.com/superwall/superwall/tree/main/packages/host)
33
+ for the studio, the dashboard and tests. A session never invents a product or
34
+ a reply; everything in its snapshot arrived from a host.
35
+
36
+ | Directory | Owns |
37
+ | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
38
+ | `src/bridge/` | The wire: transport detection (`?platform=android`, `?transport=editor`, else WebKit), `detectSuperwallHost`, base64 batch decoding for `accept64` |
39
+ | `src/config/` | The `SuperwallConfig` contract a running paywall reads, one file per concern (products, checkout, presentation, background, notifications, localization) |
40
+ | `src/localization/` | Locale resolution, the `t()` catalog, and `periods.ts` — the editor's period translation table, copied verbatim, with its lookup code trimmed of unreachable branches |
41
+ | `src/products/` | The product model, merging of `products` + `template_variables`, and derived variables (localized `period`/`periodly`, `trialPeriodEndDate`) |
42
+ | `src/session/` | `createSuperwallSession`: outgoing message builders, purchase and request trackers, trial reminders, the incoming reducer, and the state `window.app.getAllState()` returns |
46
43
 
47
44
  ## Usage
48
45
 
49
46
  ```ts
50
- import { createSuperwallSession, defineSuperwallConfig } from "@superwall/runtime"
47
+ import { createSuperwallSession, type SuperwallConfig } from "@superwall/runtime"
51
48
 
52
- const config = defineSuperwallConfig({
49
+ const config: SuperwallConfig = {
53
50
  products: { primary: "pro_3999_year" },
54
- purchaseTimeoutMs: 5 * 60 * 1000,
55
51
  notifications: {
56
52
  trialReminder: { title: "notifications.trialTitle", body: "…", beforeTrialEndDays: 1 },
57
53
  },
58
54
  localization: { defaultLocale: "en", messages: { en: { notifications: { trialTitle: "…" } } } },
59
- })
55
+ }
60
56
 
61
57
  const superwall = createSuperwallSession({ config })
62
58
  superwall.start({ sendPing: true })
63
59
 
64
- const { products, device, trial, locale } = superwall.getSnapshot()
60
+ const { products, device, introductoryOffer, locale } = superwall.getSnapshot()
65
61
  superwall.t("paywall.title")
66
62
 
67
63
  const result = await superwall.purchase("primary")
@@ -70,43 +66,65 @@ const result = await superwall.purchase("primary")
70
66
  superwall.on("transaction_complete", (message) => {})
71
67
  ```
72
68
 
69
+ The session detects its host from the page. Pass `transport` to host it
70
+ yourself (tests, tools), or `transportKind` to force one.
71
+
73
72
  ### Purchase semantics
74
73
 
75
74
  - `{ status: "completed", product, message }` from `transaction_complete`
76
75
  - `{ status: "abandoned", product, message }` from `transaction_abandon`
77
- - `{ status: "failed", product, reason: "timeout" }` if `timeoutMs` (or
78
- `config.purchaseTimeoutMs`) elapses without a transaction message
76
+ - `{ status: "failed", product, reason: "sdk" }` from `transaction_fail` or
77
+ `transaction_timeout` (iOS reports these; Android does not, so there a
78
+ failed purchase stays pending until the user abandons or completes)
79
+ - `{ status: "failed", product, reason: "superseded" }` when a newer purchase
80
+ of the same reference starts, or the paywall re-opens
81
+
82
+ The paywall runs no timer of its own: the SDK owns purchase timing.
83
+
84
+ A transaction is attributed to a pending purchase by reference, then by store
85
+ identifier, then, for a bare transaction, to the only pending purchase.
79
86
 
80
- `restore()` is fire-and-forget: the protocol has no restore-result event.
87
+ ### Restore
81
88
 
82
- ### Trial flow
89
+ `restore()` has no result to await. What the SDK reports lands on
90
+ `snapshot.restore` (`started`, `completed`, `failed`) and the `restore_start`,
91
+ `restore_complete`, `restore_fail` events. iOS reports all three; Android
92
+ reports only `restore_fail`.
83
93
 
84
- The SDK signals introductory-offer eligibility via
85
- `template_substitutions_prefix` (`"freeTrial"`), exposed as `snapshot.trial`
86
- and `products.hasIntroductoryOffer` in conditional state.
87
- `config.introductoryOfferEligibility` can force either way. On
88
- `freeTrial_start` with a `trial_end_date`, the session schedules the config's
94
+ ### Introductory offers
95
+
96
+ The SDK signals eligibility via `template_substitutions_prefix`
97
+ (`"freeTrial"`), exposed as `snapshot.introductoryOffer.eligible` and
98
+ `products.hasIntroductoryOffer` in the SDK state. The store decides; a
99
+ paywall never overrides it. On `freeTrial_start` with a `trial_end_date`,
100
+ the session schedules the config's
89
101
  trial reminder (`schedule_notification`, id
90
102
  `{paywallIdentifier}_TRIAL_STARTED`) — title/body run through `t()`.
91
103
 
92
- ### Mock host
104
+ ### The window interface
105
+
106
+ The framework's provider publishes what the native SDKs call into:
107
+ `window.paywall.accept64(base64)` for message batches and
108
+ `window.app.getAllState()` for the state object. `buildSuperwallState` builds
109
+ that object in the shape paywall.js exposes for editor paywalls, so an SDK
110
+ reads the same keys from both generations.
111
+
112
+ ### Hosting a session in-process
93
113
 
94
114
  ```ts
95
- import { createMockSuperwallTransport, mockOptionsFromConfig } from "@superwall/runtime"
115
+ import { createHostTransport, recordingDelegate } from "@superwall/host"
96
116
 
97
- const transport = createMockSuperwallTransport(
98
- mockOptionsFromConfig(config, { purchaseOutcome: "abandoned", latencyMs: 500 })
99
- )
117
+ const { transport } = createHostTransport({
118
+ state: { products: [{ reference: "primary", productId: "pro_3999_year", variables: { price: "$39.99" } }] },
119
+ delegate: recordingDelegate({ purchase: "abandoned" }),
120
+ latencyMs: 500,
121
+ })
100
122
  const superwall = createSuperwallSession({ config, transport })
101
123
  ```
102
124
 
103
- The mock answers `ping` with `paywall_open`, `products` (one slot per config
104
- entry, carrying the product identifier and nothing else — real product data
105
- comes from Superwall, never from the mock), `template_variables` (products +
106
- device + user + params), and trial eligibility; resolves purchase/restore
107
- with transactions including `freeTrial_start`; grants permissions; answers
108
- callbacks. `detectNativeSuperwallHost()` reports whether a real host is
109
- present — used by `SuperwallProvider`'s `mock="auto"`.
125
+ The host answers `ping` with the web host's burst and replies to purchase,
126
+ restore, permission and callback requests with the iOS SDK's messages. The
127
+ runtime's own tests are hosted this way.
110
128
 
111
129
  ## Develop
112
130
 
@@ -116,9 +134,7 @@ first** - the conventions in it are decided, not suggested.
116
134
 
117
135
  ```bash
118
136
  bun install
119
- bun run test # fixture tests drive the session through recorded
120
- # message sequences and assert snapshot state — they
121
- # are the protocol contract
137
+ bun run test # tests mirror src/: fixture-driven session tests are the protocol contract
122
138
  bun run typecheck
123
139
  ```
124
140
 
@@ -1,9 +1,3 @@
1
1
  import type { TIncomingMessage } from "@superwall/protocol";
2
2
  export declare const decodeBase64Utf8: (message: string) => string;
3
- /**
4
- * Deliberately lenient, matching the original runtime: every object in the
5
- * batch is delivered, including messages this build doesn't recognize (newer
6
- * event types, or legacy quirks like the miscased `eventName: "experiment"`).
7
- * Strictly validating here would let one unknown message drop the whole batch.
8
- */
9
3
  export declare const decodeIncomingMessages: (message: string) => TIncomingMessage[];
@@ -1,34 +1,14 @@
1
- /**
2
- * Host SDKs may encode with URL-safe alphabets and without padding (e.g.
3
- * Android's Base64.URL_SAFE). atob is strict, so normalize first.
4
- */
5
1
  const normalizeBase64 = (input) => {
6
2
  const standard = input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
7
3
  const remainder = standard.length % 4;
8
- return remainder === 0 ? standard : standard + "=".repeat((4 - remainder) % 4);
4
+ return remainder === 0 ? standard : standard + "=".repeat(4 - remainder);
9
5
  };
10
6
  export const decodeBase64Utf8 = (message) => {
11
- if (typeof globalThis.atob === "function") {
12
- const binary = globalThis.atob(normalizeBase64(message));
13
- const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
14
- return new TextDecoder().decode(bytes);
15
- }
16
- const buffer = globalThis.Buffer;
17
- if (buffer) {
18
- return buffer.from(normalizeBase64(message), "base64").toString("utf8");
19
- }
20
- throw new Error("No base64 decoder is available in this runtime");
7
+ const binary = atob(normalizeBase64(message));
8
+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
21
9
  };
22
- /**
23
- * Deliberately lenient, matching the original runtime: every object in the
24
- * batch is delivered, including messages this build doesn't recognize (newer
25
- * event types, or legacy quirks like the miscased `eventName: "experiment"`).
26
- * Strictly validating here would let one unknown message drop the whole batch.
27
- */
10
+ const isMessageLike = (entry) => typeof entry === "object" && entry !== null;
28
11
  export const decodeIncomingMessages = (message) => {
29
12
  const parsed = JSON.parse(decodeBase64Utf8(message));
30
- if (!Array.isArray(parsed)) {
31
- return [];
32
- }
33
- return parsed.filter((entry) => typeof entry === "object" && entry !== null);
13
+ return Array.isArray(parsed) ? parsed.filter(isMessageLike) : [];
34
14
  };
@@ -1,30 +1,2 @@
1
- import type { ITransport, TIncomingHandler, TIncomingMessage, TOutgoingMessage, TransportKind } from "@superwall/protocol";
2
- export type SuperwallMessageLogEntry = {
3
- ts: Date;
4
- msg: TIncomingMessage;
5
- type: "incoming";
6
- } | {
7
- ts: Date;
8
- msg: TOutgoingMessage;
9
- type: "outgoing";
10
- };
11
- export type SuperwallBridgeOptions = {
12
- transport?: ITransport;
13
- transportKind?: TransportKind;
14
- now?: () => Date;
15
- onDecodeError?: (error: unknown) => void;
16
- };
17
- export declare class SuperwallBridge {
18
- private transport;
19
- private incomingHandlers;
20
- private now;
21
- private onDecodeError?;
22
- messages: SuperwallMessageLogEntry[];
23
- constructor(options?: SuperwallBridgeOptions);
24
- start(): void;
25
- addListener(handler: TIncomingHandler): () => void;
26
- postMessage(message: TOutgoingMessage): void;
27
- accept(messages: TIncomingMessage[]): void;
28
- accept64(message: string): void;
29
- }
30
- export declare const createSuperwallBridge: (options?: SuperwallBridgeOptions) => SuperwallBridge;
1
+ export { decodeBase64Utf8, decodeIncomingMessages } from "./base64";
2
+ export { createRuntimeTransport, detectRuntimeTransportKind, detectSuperwallHost, type RuntimeTransportDetectionOptions, } from "./transport";
@@ -1,49 +1,2 @@
1
- import { decodeIncomingMessages } from "./base64";
2
- import { createRuntimeTransport, detectRuntimeTransportKind } from "./transport";
3
- export class SuperwallBridge {
4
- transport;
5
- incomingHandlers = [];
6
- now;
7
- onDecodeError;
8
- messages = [];
9
- constructor(options = {}) {
10
- this.transport =
11
- options.transport ??
12
- createRuntimeTransport(options.transportKind ?? detectRuntimeTransportKind());
13
- this.now = options.now ?? (() => new Date());
14
- this.onDecodeError = options.onDecodeError;
15
- this.transport.addListener((message) => {
16
- this.messages.push({ ts: this.now(), msg: message, type: "incoming" });
17
- this.incomingHandlers.forEach((handler) => {
18
- handler(message);
19
- });
20
- });
21
- }
22
- start() {
23
- this.transport.startListening();
24
- }
25
- addListener(handler) {
26
- this.incomingHandlers.push(handler);
27
- return () => {
28
- this.incomingHandlers = this.incomingHandlers.filter((candidate) => candidate !== handler);
29
- };
30
- }
31
- postMessage(message) {
32
- this.messages.push({ ts: this.now(), msg: message, type: "outgoing" });
33
- this.transport.postMessage(message);
34
- }
35
- accept(messages) {
36
- messages.forEach((message) => {
37
- this.transport.accept(message);
38
- });
39
- }
40
- accept64(message) {
41
- try {
42
- this.accept(decodeIncomingMessages(message));
43
- }
44
- catch (error) {
45
- this.onDecodeError?.(error);
46
- }
47
- }
48
- }
49
- export const createSuperwallBridge = (options = {}) => new SuperwallBridge(options);
1
+ export { decodeBase64Utf8, decodeIncomingMessages } from "./base64";
2
+ export { createRuntimeTransport, detectRuntimeTransportKind, detectSuperwallHost, } from "./transport";
@@ -1,14 +1,7 @@
1
1
  import { TransportKind, type ITransport } from "@superwall/protocol";
2
- export { pendingHostMessages } from "@superwall/protocol";
3
2
  export type RuntimeTransportDetectionOptions = {
4
3
  search?: string;
5
4
  };
6
5
  export declare const detectRuntimeTransportKind: (options?: RuntimeTransportDetectionOptions) => TransportKind;
7
- export declare const createRuntimeTransport: (transportKind?: TransportKind) => ITransport;
8
- /**
9
- * Detects the explicit `?sw_preview` opt-in that lets a page simulate the SDK
10
- * without a native host present. "auto" mock mode requires it, so a built
11
- * snapshot can never downgrade itself to placeholder products by accident.
12
- */
13
- export declare const detectPreviewOptIn: () => boolean;
14
- export declare const detectNativeSuperwallHost: () => boolean;
6
+ export declare const createRuntimeTransport: (kind?: TransportKind) => ITransport;
7
+ export declare const detectSuperwallHost: () => boolean;
@@ -1,43 +1,22 @@
1
1
  import { buildTransport, TransportKind } from "@superwall/protocol";
2
- export { pendingHostMessages } from "@superwall/protocol";
3
2
  export const detectRuntimeTransportKind = (options = {}) => {
4
3
  if (typeof window === "undefined" && options.search === undefined) {
5
4
  return TransportKind.WebKitPostMessage;
6
5
  }
7
- const search = options.search ?? window.location.search;
8
- const urlParams = new URLSearchParams(search);
9
- if (urlParams.get("platform") === "android") {
6
+ const params = new URLSearchParams(options.search ?? window.location.search);
7
+ if (params.get("platform") === "android")
10
8
  return TransportKind.Android;
11
- }
12
- if (urlParams.get("transport") === "editor") {
9
+ if (params.get("transport") === "editor")
13
10
  return TransportKind.EditorIframe;
14
- }
15
11
  return TransportKind.WebKitPostMessage;
16
12
  };
17
- export const createRuntimeTransport = (transportKind = detectRuntimeTransportKind()) => buildTransport(transportKind);
18
- /**
19
- * Detects the explicit `?sw_preview` opt-in that lets a page simulate the SDK
20
- * without a native host present. "auto" mock mode requires it, so a built
21
- * snapshot can never downgrade itself to placeholder products by accident.
22
- */
23
- export const detectPreviewOptIn = () => {
24
- if (typeof window === "undefined") {
25
- return false;
26
- }
27
- return new URLSearchParams(window.location.search).has("sw_preview");
28
- };
29
- export const detectNativeSuperwallHost = () => {
30
- if (typeof window === "undefined") {
13
+ export const createRuntimeTransport = (kind = detectRuntimeTransportKind()) => buildTransport(kind);
14
+ export const detectSuperwallHost = () => {
15
+ if (typeof window === "undefined")
31
16
  return false;
32
- }
33
- // window.webkit and SWAndroid are declared globally by @superwall/protocol's
34
- // transports — the SDK-injected host contract.
35
- if (window.webkit?.messageHandlers?.paywallMessageHandler) {
17
+ if (window.webkit?.messageHandlers?.paywallMessageHandler)
36
18
  return true;
37
- }
38
- if (typeof SWAndroid !== "undefined" && SWAndroid) {
19
+ if (typeof SWAndroid !== "undefined" && SWAndroid)
39
20
  return true;
40
- }
41
- const urlParams = new URLSearchParams(window.location.search);
42
- return urlParams.get("platform") === "android" || urlParams.get("transport") === "editor";
21
+ return detectRuntimeTransportKind() !== TransportKind.WebKitPostMessage;
43
22
  };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A paywall's background color. The string shorthand sets light mode; the
3
+ * object form adds a dark-mode color. Native SDKs paint it behind the webview
4
+ * (and derive the loading spinner from it), and the web document paints it as
5
+ * the page background — so the color a shopper sees while the paywall loads
6
+ * matches the color it settles on.
7
+ */
8
+ export type SuperwallBackgroundConfig = string | {
9
+ light: string;
10
+ dark?: string;
11
+ };
12
+ export type ResolvedBackground = {
13
+ light: string;
14
+ dark?: string;
15
+ };
16
+ export declare const backgroundOf: (background: SuperwallBackgroundConfig | undefined) => ResolvedBackground | undefined;
@@ -0,0 +1,13 @@
1
+ export const backgroundOf = (background) => {
2
+ if (background === undefined)
3
+ return undefined;
4
+ if (typeof background === "string") {
5
+ const light = background.trim();
6
+ return light === "" ? undefined : { light };
7
+ }
8
+ const light = background.light?.trim();
9
+ if (!light)
10
+ return undefined;
11
+ const dark = background.dark?.trim();
12
+ return dark ? { light, dark } : { light };
13
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * How a purchase completes on the web. Native hosts ignore it — they always
3
+ * buy through the store.
4
+ *
5
+ * - `external` — leave for Superwall's hosted checkout page and come back.
6
+ * - `sheet` — take payment in the paywall, in a sheet Superwall renders.
7
+ * - `applePay` — go straight to Apple Pay, falling back to the sheet where
8
+ * Apple Pay is unavailable.
9
+ *
10
+ * The sheet's appearance is fixed and takes nothing from the paywall around
11
+ * it. `sheet` and `applePay` carry Stripe's payment UI into the bundle;
12
+ * `external` costs nothing. Read this before shipping either:
13
+ * https://superwall.com/docs/web-checkout
14
+ */
15
+ export type SuperwallCheckoutMode = "external" | "sheet" | "applePay";
16
+ /**
17
+ * The mode alone, or the object form to steer prefetching: `prefetch` names
18
+ * the Stripe product warmed on paywall open (default: the first Stripe
19
+ * product), `false` disables automatic prefetch.
20
+ */
21
+ export type SuperwallCheckoutConfig<TReference extends string = string> = SuperwallCheckoutMode | {
22
+ mode: SuperwallCheckoutMode;
23
+ prefetch?: TReference | false;
24
+ };
25
+ export declare const checkoutModeOf: (checkout: SuperwallCheckoutConfig | undefined) => SuperwallCheckoutMode | undefined;
26
+ export declare const checkoutPrefetchOf: (checkout: SuperwallCheckoutConfig | undefined) => string | false | undefined;
@@ -0,0 +1,2 @@
1
+ export const checkoutModeOf = (checkout) => (typeof checkout === "string" ? checkout : checkout?.mode);
2
+ export const checkoutPrefetchOf = (checkout) => (typeof checkout === "object" ? checkout.prefetch : undefined);
@@ -0,0 +1,66 @@
1
+ import type { SuperwallBackgroundConfig } from "./background";
2
+ import type { SuperwallCheckoutConfig } from "./checkout";
3
+ import type { SuperwallLocalizationConfig } from "./localization";
4
+ import type { SuperwallNotificationsConfig } from "./notifications";
5
+ import type { SuperwallPresentationConfig } from "./presentation";
6
+ import type { SuperwallProductSlotInput } from "./products";
7
+ /**
8
+ * A paywall's contract: product slots, presentation, gating, notifications,
9
+ * and localization. The session reads it at render time and the build reads
10
+ * it at push time.
11
+ */
12
+ export type SuperwallConfig<TLocale extends string = string, TStripeReference extends string = string> = {
13
+ /** Product slots this paywall renders, keyed by reference. Default: none. */
14
+ products?: Record<string, SuperwallProductSlotInput>;
15
+ /**
16
+ * How a purchase completes on the web. Default: omitted, native-only —
17
+ * nothing about checkout is bundled unless this asks for it.
18
+ */
19
+ checkout?: SuperwallCheckoutConfig<TStripeReference>;
20
+ /**
21
+ * How the native SDK presents the paywall: style and drawer/popup
22
+ * geometry. Default: `{ style: "fullscreen" }`.
23
+ */
24
+ presentation?: SuperwallPresentationConfig;
25
+ /**
26
+ * Background color painted behind the paywall while it loads and as the web
27
+ * document background. String shorthand = light mode; `{ light, dark }` adds
28
+ * a dark-mode color. Default: the platform default.
29
+ */
30
+ background?: SuperwallBackgroundConfig;
31
+ /**
32
+ * Whether the feature behind the placement is gated on a purchase.
33
+ * Default: `"nonGated"`.
34
+ */
35
+ featureGating?: "gated" | "nonGated";
36
+ /** Forward game controller input to the paywall. Default: `false`. */
37
+ gameControllerEnabled?: boolean;
38
+ /** Whether the webview scrolls. Default: `true`. */
39
+ scrollEnabled?: boolean;
40
+ /** Cache the paywall on device for instant presentation. Default: `true`. */
41
+ onDeviceCacheEnabled?: boolean;
42
+ /**
43
+ * Whether this paywall asks the SDK to dismiss it after a completed
44
+ * purchase (`should_dismiss` on the purchase message). Default: `true`.
45
+ * The app can still veto it with
46
+ * `SuperwallOptions.paywalls.automaticallyDismiss = false`.
47
+ */
48
+ dismissOnPurchase?: boolean;
49
+ /**
50
+ * Local notifications the paywall schedules (e.g. trial reminders).
51
+ * Default: none.
52
+ */
53
+ notifications?: SuperwallNotificationsConfig;
54
+ /**
55
+ * Message catalogs and the fallback locale for `t()`. Default:
56
+ * `{ defaultLocale: "en" }`; file-based catalogs need no config.
57
+ */
58
+ localization?: SuperwallLocalizationConfig<TLocale>;
59
+ };
60
+ export { backgroundOf, type ResolvedBackground, type SuperwallBackgroundConfig, } from "./background";
61
+ export { checkoutModeOf, checkoutPrefetchOf, type SuperwallCheckoutConfig, type SuperwallCheckoutMode, } from "./checkout";
62
+ export type { SuperwallLocalizationConfig, SuperwallMessages } from "./localization";
63
+ export type { SuperwallNotificationsConfig, SuperwallTrialReminderConfig, SuperwallTrialReminderContext, SuperwallTrialReminderNotification, SuperwallTrialReminderStaticConfig, } from "./notifications";
64
+ export { normalizePlatform, SUPERWALL_PLATFORMS, type SuperwallPlatform } from "./platforms";
65
+ export type { SuperwallPresentationConfig, SuperwallPresentationStyle } from "./presentation";
66
+ export { isPlatformProductIds, productIdFor, type SuperwallPlatformProductIds, type SuperwallProductSlot, type SuperwallProductSlotInput, } from "./products";
@@ -0,0 +1,4 @@
1
+ export { backgroundOf, } from "./background";
2
+ export { checkoutModeOf, checkoutPrefetchOf, } from "./checkout";
3
+ export { normalizePlatform, SUPERWALL_PLATFORMS } from "./platforms";
4
+ export { isPlatformProductIds, productIdFor, } from "./products";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Nested message catalog for one locale. Values interpolate `{name}` params:
3
+ * `{ paywall: { title: "Unlock {appName}" } }` → `t("paywall.title", { appName })`.
4
+ */
5
+ export type SuperwallMessages = {
6
+ [key: string]: string | SuperwallMessages;
7
+ };
8
+ export type SuperwallLocalizationConfig<TLocale extends string = string> = {
9
+ /** Locale used when the device locale has no catalog. */
10
+ defaultLocale: TLocale;
11
+ /** Message catalogs by locale (e.g. `{ en, de, "pt-BR": ptBR }`). */
12
+ messages?: Record<TLocale, SuperwallMessages> & Record<string, SuperwallMessages>;
13
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ import type { SuperwallProduct } from "../products";
2
+ export type SuperwallTrialReminderStaticConfig = {
3
+ /** Default: `true`. */
4
+ enabled?: boolean;
5
+ /** Notification title. A message key resolves through `t()`; literal copy passes through. */
6
+ title: string;
7
+ /** Default: none. */
8
+ subtitle?: string;
9
+ /** Notification body. A message key resolves through `t()`; literal copy passes through. */
10
+ body: string;
11
+ /** How many days before the trial ends the reminder fires. Default: `1`. */
12
+ beforeTrialEndDays?: number;
13
+ };
14
+ export type SuperwallTrialReminderContext = {
15
+ /** When the trial ends, per the SDK. */
16
+ trialEndDate: Date;
17
+ /** Store identifier of the purchased product, when the SDK provides it. */
18
+ productIdentifier?: string;
19
+ /** The matching product, when it's one of this paywall's slots. */
20
+ product?: SuperwallProduct;
21
+ /** Translator for the active locale. */
22
+ t: (key: string, values?: Record<string, string | number>) => string;
23
+ locale: string;
24
+ };
25
+ export type SuperwallTrialReminderNotification = {
26
+ title: string;
27
+ subtitle?: string;
28
+ body: string;
29
+ /** Milliseconds from now until the notification fires; `0` or less skips it. */
30
+ delayMs: number;
31
+ };
32
+ /**
33
+ * Static config, or a function computing the notification from the trial
34
+ * context. Return `null` from the function to skip scheduling.
35
+ */
36
+ export type SuperwallTrialReminderConfig = SuperwallTrialReminderStaticConfig | ((context: SuperwallTrialReminderContext) => SuperwallTrialReminderNotification | null | undefined);
37
+ export type SuperwallNotificationsConfig = {
38
+ /** Scheduled when the SDK reports a trial started (`freeTrial_start`). Default: none. */
39
+ trialReminder?: SuperwallTrialReminderConfig;
40
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export declare const SUPERWALL_PLATFORMS: readonly ["ios", "android", "web"];
2
+ export type SuperwallPlatform = (typeof SUPERWALL_PLATFORMS)[number];
3
+ export declare const normalizePlatform: (value: string | undefined) => SuperwallPlatform | undefined;
@@ -0,0 +1,5 @@
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
+ };
@@ -0,0 +1,22 @@
1
+ export type SuperwallPresentationStyle = "fullscreen" | "modal" | "push" | "drawer" | "popup" | "noAnimation";
2
+ export type SuperwallPresentationConfig = {
3
+ /** How the native SDK presents the paywall. Default: `"fullscreen"`. */
4
+ style?: SuperwallPresentationStyle;
5
+ /**
6
+ * Drawer geometry, as percentages of the screen and points. Only read when
7
+ * style is "drawer". Default: `{ height: 70, cornerRadius: 15 }`.
8
+ */
9
+ drawer?: {
10
+ height?: number;
11
+ cornerRadius?: number;
12
+ };
13
+ /**
14
+ * Popup geometry, as percentages of the screen and points. Only read when
15
+ * style is "popup". Default: `{ width: 80, height: 60, cornerRadius: 15 }`.
16
+ */
17
+ popup?: {
18
+ width?: number;
19
+ height?: number;
20
+ cornerRadius?: number;
21
+ };
22
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import type { SuperwallPlatform } from "./platforms";
2
+ /**
3
+ * A product slot the paywall renders, keyed by reference in
4
+ * `SuperwallConfig["products"]`. Product data (price, period, trial…) is
5
+ * host-owned and arrives at runtime.
6
+ */
7
+ export type SuperwallProductSlot = {
8
+ /** Store product identifier this slot maps to (e.g. "pro_3999_year"). */
9
+ productId?: string;
10
+ };
11
+ /**
12
+ * One store identifier per platform the paywall ships to, for a slot whose
13
+ * underlying product differs by store — the same `purchase("annual")` buys
14
+ * the App Store product on iOS and the Play product on Android.
15
+ */
16
+ export type SuperwallPlatformProductIds = Partial<Record<SuperwallPlatform, string>>;
17
+ /**
18
+ * A slot object, the store product identifier as shorthand, or one
19
+ * identifier per platform.
20
+ */
21
+ export type SuperwallProductSlotInput = string | SuperwallProductSlot | SuperwallPlatformProductIds;
22
+ export declare const isPlatformProductIds: (input: SuperwallProductSlotInput) => input is SuperwallPlatformProductIds;
23
+ export declare const productIdFor: (input: SuperwallProductSlotInput, platform?: SuperwallPlatform) => string | undefined;