@superwall/runtime 1.1.1 → 1.3.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +65 -49
  2. package/dist/bridge/base64.d.ts +0 -6
  3. package/dist/bridge/base64.js +5 -25
  4. package/dist/bridge/index.d.ts +2 -30
  5. package/dist/bridge/index.js +2 -49
  6. package/dist/bridge/transport.d.ts +2 -9
  7. package/dist/bridge/transport.js +9 -30
  8. package/dist/config/background.d.ts +16 -0
  9. package/dist/config/background.js +13 -0
  10. package/dist/config/checkout.d.ts +26 -0
  11. package/dist/config/checkout.js +2 -0
  12. package/dist/config/index.d.ts +66 -0
  13. package/dist/config/index.js +4 -0
  14. package/dist/config/localization.d.ts +13 -0
  15. package/dist/config/localization.js +1 -0
  16. package/dist/config/notifications.d.ts +40 -0
  17. package/dist/config/notifications.js +1 -0
  18. package/dist/config/platforms.d.ts +3 -0
  19. package/dist/config/platforms.js +5 -0
  20. package/dist/config/presentation.d.ts +22 -0
  21. package/dist/config/presentation.js +1 -0
  22. package/dist/config/products.d.ts +23 -0
  23. package/dist/config/products.js +10 -0
  24. package/dist/index.d.ts +2 -7
  25. package/dist/index.js +1 -6
  26. package/dist/localization/catalog.d.ts +8 -0
  27. package/dist/localization/catalog.js +21 -0
  28. package/dist/localization/index.d.ts +3 -24
  29. package/dist/localization/index.js +3 -71
  30. package/dist/localization/locale.d.ts +2 -0
  31. package/dist/localization/locale.js +22 -0
  32. package/dist/localization/periods.d.ts +1 -0
  33. package/dist/localization/periods.js +13 -5
  34. package/dist/products/derive.d.ts +4 -0
  35. package/dist/products/derive.js +45 -0
  36. package/dist/{products.d.ts → products/index.d.ts} +6 -14
  37. package/dist/products/index.js +15 -0
  38. package/dist/products/merge.d.ts +5 -0
  39. package/dist/products/merge.js +51 -0
  40. package/dist/session/incoming.d.ts +3 -0
  41. package/dist/session/incoming.js +47 -0
  42. package/dist/session/index.d.ts +7 -102
  43. package/dist/session/index.js +232 -695
  44. package/dist/session/outgoing.d.ts +42 -0
  45. package/dist/session/outgoing.js +70 -0
  46. package/dist/session/purchases.d.ts +18 -0
  47. package/dist/session/purchases.js +44 -0
  48. package/dist/session/reminders.d.ts +11 -0
  49. package/dist/session/reminders.js +41 -0
  50. package/dist/session/requests.d.ts +19 -0
  51. package/dist/session/requests.js +56 -0
  52. package/dist/session/state.d.ts +3 -3
  53. package/dist/session/state.js +14 -39
  54. package/dist/session/types.d.ts +49 -29
  55. package/dist/session/variables.d.ts +3 -7
  56. package/package.json +3 -2
  57. package/src/bridge/base64.ts +10 -46
  58. package/src/bridge/index.ts +7 -77
  59. package/src/bridge/transport.ts +11 -46
  60. package/src/config/background.ts +24 -0
  61. package/src/config/checkout.ts +32 -0
  62. package/src/config/index.ts +102 -0
  63. package/src/config/localization.ts +12 -0
  64. package/src/config/notifications.ts +49 -0
  65. package/src/config/platforms.ts +8 -0
  66. package/src/config/presentation.ts +22 -0
  67. package/src/config/products.ts +39 -0
  68. package/src/index.ts +2 -43
  69. package/src/localization/catalog.ts +45 -0
  70. package/src/localization/index.ts +7 -110
  71. package/src/localization/locale.ts +25 -0
  72. package/src/localization/periods.ts +23 -8
  73. package/src/products/derive.ts +65 -0
  74. package/src/products/index.ts +87 -0
  75. package/src/products/merge.ts +78 -0
  76. package/src/session/incoming.ts +53 -0
  77. package/src/session/index.ts +275 -986
  78. package/src/session/outgoing.ts +132 -0
  79. package/src/session/purchases.ts +66 -0
  80. package/src/session/reminders.ts +56 -0
  81. package/src/session/requests.ts +87 -0
  82. package/src/session/state.ts +19 -59
  83. package/src/session/types.ts +68 -30
  84. package/src/session/variables.ts +3 -7
  85. package/dist/config.d.ts +0 -237
  86. package/dist/config.js +0 -138
  87. package/dist/mock.d.ts +0 -74
  88. package/dist/mock.js +0 -206
  89. package/dist/products.js +0 -105
  90. package/src/config.ts +0 -408
  91. package/src/mock.ts +0 -333
  92. package/src/products.ts +0 -221
@@ -1,77 +1,7 @@
1
- import type {
2
- ITransport,
3
- TIncomingHandler,
4
- TIncomingMessage,
5
- TOutgoingMessage,
6
- TransportKind,
7
- } from "@superwall/protocol";
8
- import { decodeIncomingMessages } from "./base64";
9
- import { createRuntimeTransport, detectRuntimeTransportKind } from "./transport";
10
-
11
- export type SuperwallMessageLogEntry =
12
- | { ts: Date; msg: TIncomingMessage; type: "incoming" }
13
- | { ts: Date; msg: TOutgoingMessage; type: "outgoing" };
14
-
15
- export type SuperwallBridgeOptions = {
16
- transport?: ITransport;
17
- transportKind?: TransportKind;
18
- now?: () => Date;
19
- onDecodeError?: (error: unknown) => void;
20
- };
21
-
22
- export class SuperwallBridge {
23
- private transport: ITransport;
24
- private incomingHandlers: TIncomingHandler[] = [];
25
- private now: () => Date;
26
- private onDecodeError?: (error: unknown) => void;
27
-
28
- public messages: SuperwallMessageLogEntry[] = [];
29
-
30
- constructor(options: SuperwallBridgeOptions = {}) {
31
- this.transport =
32
- options.transport ??
33
- createRuntimeTransport(options.transportKind ?? detectRuntimeTransportKind());
34
- this.now = options.now ?? (() => new Date());
35
- this.onDecodeError = options.onDecodeError;
36
-
37
- this.transport.addListener((message) => {
38
- this.messages.push({ ts: this.now(), msg: message, type: "incoming" });
39
- this.incomingHandlers.forEach((handler) => {
40
- handler(message);
41
- });
42
- });
43
- }
44
-
45
- public start() {
46
- this.transport.startListening();
47
- }
48
-
49
- public addListener(handler: TIncomingHandler) {
50
- this.incomingHandlers.push(handler);
51
- return () => {
52
- this.incomingHandlers = this.incomingHandlers.filter((candidate) => candidate !== handler);
53
- };
54
- }
55
-
56
- public postMessage(message: TOutgoingMessage) {
57
- this.messages.push({ ts: this.now(), msg: message, type: "outgoing" });
58
- this.transport.postMessage(message);
59
- }
60
-
61
- public accept(messages: TIncomingMessage[]) {
62
- messages.forEach((message) => {
63
- this.transport.accept(message);
64
- });
65
- }
66
-
67
- public accept64(message: string) {
68
- try {
69
- this.accept(decodeIncomingMessages(message));
70
- } catch (error) {
71
- this.onDecodeError?.(error);
72
- }
73
- }
74
- }
75
-
76
- export const createSuperwallBridge = (options: SuperwallBridgeOptions = {}) =>
77
- new SuperwallBridge(options);
1
+ export { decodeBase64Utf8, decodeIncomingMessages } from "./base64";
2
+ export {
3
+ createRuntimeTransport,
4
+ detectRuntimeTransportKind,
5
+ detectSuperwallHost,
6
+ type RuntimeTransportDetectionOptions,
7
+ } from "./transport";
@@ -1,7 +1,5 @@
1
1
  import { buildTransport, TransportKind, type ITransport } from "@superwall/protocol";
2
2
 
3
- export { pendingHostMessages } from "@superwall/protocol";
4
-
5
3
  export type RuntimeTransportDetectionOptions = {
6
4
  search?: string;
7
5
  };
@@ -12,52 +10,19 @@ export const detectRuntimeTransportKind = (
12
10
  if (typeof window === "undefined" && options.search === undefined) {
13
11
  return TransportKind.WebKitPostMessage;
14
12
  }
15
-
16
- const search = options.search ?? window.location.search;
17
- const urlParams = new URLSearchParams(search);
18
-
19
- if (urlParams.get("platform") === "android") {
20
- return TransportKind.Android;
21
- }
22
-
23
- if (urlParams.get("transport") === "editor") {
24
- return TransportKind.EditorIframe;
25
- }
26
-
13
+ const params = new URLSearchParams(options.search ?? window.location.search);
14
+ if (params.get("platform") === "android") return TransportKind.Android;
15
+ if (params.get("transport") === "editor") return TransportKind.EditorIframe;
27
16
  return TransportKind.WebKitPostMessage;
28
17
  };
29
18
 
30
19
  export const createRuntimeTransport = (
31
- transportKind: TransportKind = detectRuntimeTransportKind(),
32
- ): ITransport => buildTransport(transportKind);
33
-
34
- /**
35
- * Detects the explicit `?sw_preview` opt-in that lets a page simulate the SDK
36
- * without a native host present. "auto" mock mode requires it, so a built
37
- * snapshot can never downgrade itself to placeholder products by accident.
38
- */
39
- export const detectPreviewOptIn = (): boolean => {
40
- if (typeof window === "undefined") {
41
- return false;
42
- }
43
- return new URLSearchParams(window.location.search).has("sw_preview");
44
- };
45
-
46
- export const detectNativeSuperwallHost = (): boolean => {
47
- if (typeof window === "undefined") {
48
- return false;
49
- }
50
-
51
- // window.webkit and SWAndroid are declared globally by @superwall/protocol's
52
- // transports — the SDK-injected host contract.
53
- if (window.webkit?.messageHandlers?.paywallMessageHandler) {
54
- return true;
55
- }
56
-
57
- if (typeof SWAndroid !== "undefined" && SWAndroid) {
58
- return true;
59
- }
60
-
61
- const urlParams = new URLSearchParams(window.location.search);
62
- return urlParams.get("platform") === "android" || urlParams.get("transport") === "editor";
20
+ kind: TransportKind = detectRuntimeTransportKind(),
21
+ ): ITransport => buildTransport(kind);
22
+
23
+ export const detectSuperwallHost = (): boolean => {
24
+ if (typeof window === "undefined") return false;
25
+ if (window.webkit?.messageHandlers?.paywallMessageHandler) return true;
26
+ if (typeof SWAndroid !== "undefined" && SWAndroid) return true;
27
+ return detectRuntimeTransportKind() !== TransportKind.WebKitPostMessage;
63
28
  };
@@ -0,0 +1,24 @@
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 | { light: string; dark?: string };
9
+
10
+ export type ResolvedBackground = { light: string; dark?: string };
11
+
12
+ export const backgroundOf = (
13
+ background: SuperwallBackgroundConfig | undefined,
14
+ ): ResolvedBackground | undefined => {
15
+ if (background === undefined) return undefined;
16
+ if (typeof background === "string") {
17
+ const light = background.trim();
18
+ return light === "" ? undefined : { light };
19
+ }
20
+ const light = background.light?.trim();
21
+ if (!light) return undefined;
22
+ const dark = background.dark?.trim();
23
+ return dark ? { light, dark } : { light };
24
+ };
@@ -0,0 +1,32 @@
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
+ /**
18
+ * The mode alone, or the object form to steer prefetching: `prefetch` names
19
+ * the Stripe product warmed on paywall open (default: the first Stripe
20
+ * product), `false` disables automatic prefetch.
21
+ */
22
+ export type SuperwallCheckoutConfig<TReference extends string = string> =
23
+ | SuperwallCheckoutMode
24
+ | { mode: SuperwallCheckoutMode; prefetch?: TReference | false };
25
+
26
+ export const checkoutModeOf = (
27
+ checkout: SuperwallCheckoutConfig | undefined,
28
+ ): SuperwallCheckoutMode | undefined => (typeof checkout === "string" ? checkout : checkout?.mode);
29
+
30
+ export const checkoutPrefetchOf = (
31
+ checkout: SuperwallCheckoutConfig | undefined,
32
+ ): string | false | undefined => (typeof checkout === "object" ? checkout.prefetch : undefined);
@@ -0,0 +1,102 @@
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
+ /**
9
+ * A paywall's contract: product slots, presentation, gating, notifications,
10
+ * and localization. The session reads it at render time and the build reads
11
+ * it at push time.
12
+ */
13
+ export type SuperwallConfig<
14
+ TLocale extends string = string,
15
+ TStripeReference extends string = string,
16
+ > = {
17
+ /** Product slots this paywall renders, keyed by reference. Default: none. */
18
+ products?: Record<string, SuperwallProductSlotInput>;
19
+
20
+ /**
21
+ * How a purchase completes on the web. Default: omitted, native-only —
22
+ * nothing about checkout is bundled unless this asks for it.
23
+ */
24
+ checkout?: SuperwallCheckoutConfig<TStripeReference>;
25
+
26
+ /**
27
+ * How the native SDK presents the paywall: style and drawer/popup
28
+ * geometry. Default: `{ style: "fullscreen" }`.
29
+ */
30
+ presentation?: SuperwallPresentationConfig;
31
+
32
+ /**
33
+ * Background color painted behind the paywall while it loads and as the web
34
+ * document background. String shorthand = light mode; `{ light, dark }` adds
35
+ * a dark-mode color. Default: the platform default.
36
+ */
37
+ background?: SuperwallBackgroundConfig;
38
+
39
+ /**
40
+ * Whether the feature behind the placement is gated on a purchase.
41
+ * Default: `"nonGated"`.
42
+ */
43
+ featureGating?: "gated" | "nonGated";
44
+
45
+ /** Forward game controller input to the paywall. Default: `false`. */
46
+ gameControllerEnabled?: boolean;
47
+
48
+ /** Whether the webview scrolls. Default: `true`. */
49
+ scrollEnabled?: boolean;
50
+
51
+ /** Cache the paywall on device for instant presentation. Default: `true`. */
52
+ onDeviceCacheEnabled?: boolean;
53
+
54
+ /**
55
+ * Whether this paywall asks the SDK to dismiss it after a completed
56
+ * purchase (`should_dismiss` on the purchase message). Default: `true`.
57
+ * The app can still veto it with
58
+ * `SuperwallOptions.paywalls.automaticallyDismiss = false`.
59
+ */
60
+ dismissOnPurchase?: boolean;
61
+
62
+ /**
63
+ * Local notifications the paywall schedules (e.g. trial reminders).
64
+ * Default: none.
65
+ */
66
+ notifications?: SuperwallNotificationsConfig;
67
+
68
+ /**
69
+ * Message catalogs and the fallback locale for `t()`. Default:
70
+ * `{ defaultLocale: "en" }`; file-based catalogs need no config.
71
+ */
72
+ localization?: SuperwallLocalizationConfig<TLocale>;
73
+ };
74
+
75
+ export {
76
+ backgroundOf,
77
+ type ResolvedBackground,
78
+ type SuperwallBackgroundConfig,
79
+ } from "./background";
80
+ export {
81
+ checkoutModeOf,
82
+ checkoutPrefetchOf,
83
+ type SuperwallCheckoutConfig,
84
+ type SuperwallCheckoutMode,
85
+ } from "./checkout";
86
+ export type { SuperwallLocalizationConfig, SuperwallMessages } from "./localization";
87
+ export type {
88
+ SuperwallNotificationsConfig,
89
+ SuperwallTrialReminderConfig,
90
+ SuperwallTrialReminderContext,
91
+ SuperwallTrialReminderNotification,
92
+ SuperwallTrialReminderStaticConfig,
93
+ } from "./notifications";
94
+ export { normalizePlatform, SUPERWALL_PLATFORMS, type SuperwallPlatform } from "./platforms";
95
+ export type { SuperwallPresentationConfig, SuperwallPresentationStyle } from "./presentation";
96
+ export {
97
+ isPlatformProductIds,
98
+ productIdFor,
99
+ type SuperwallPlatformProductIds,
100
+ type SuperwallProductSlot,
101
+ type SuperwallProductSlotInput,
102
+ } from "./products";
@@ -0,0 +1,12 @@
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 = { [key: string]: string | SuperwallMessages };
6
+
7
+ export type SuperwallLocalizationConfig<TLocale extends string = string> = {
8
+ /** Locale used when the device locale has no catalog. */
9
+ defaultLocale: TLocale;
10
+ /** Message catalogs by locale (e.g. `{ en, de, "pt-BR": ptBR }`). */
11
+ messages?: Record<TLocale, SuperwallMessages> & Record<string, SuperwallMessages>;
12
+ };
@@ -0,0 +1,49 @@
1
+ import type { SuperwallProduct } from "../products";
2
+
3
+ export type SuperwallTrialReminderStaticConfig = {
4
+ /** Default: `true`. */
5
+ enabled?: boolean;
6
+ /** Notification title. A message key resolves through `t()`; literal copy passes through. */
7
+ title: string;
8
+ /** Default: none. */
9
+ subtitle?: string;
10
+ /** Notification body. A message key resolves through `t()`; literal copy passes through. */
11
+ body: string;
12
+ /** How many days before the trial ends the reminder fires. Default: `1`. */
13
+ beforeTrialEndDays?: number;
14
+ };
15
+
16
+ export type SuperwallTrialReminderContext = {
17
+ /** When the trial ends, per the SDK. */
18
+ trialEndDate: Date;
19
+ /** Store identifier of the purchased product, when the SDK provides it. */
20
+ productIdentifier?: string;
21
+ /** The matching product, when it's one of this paywall's slots. */
22
+ product?: SuperwallProduct;
23
+ /** Translator for the active locale. */
24
+ t: (key: string, values?: Record<string, string | number>) => string;
25
+ locale: string;
26
+ };
27
+
28
+ export type SuperwallTrialReminderNotification = {
29
+ title: string;
30
+ subtitle?: string;
31
+ body: string;
32
+ /** Milliseconds from now until the notification fires; `0` or less skips it. */
33
+ delayMs: number;
34
+ };
35
+
36
+ /**
37
+ * Static config, or a function computing the notification from the trial
38
+ * context. Return `null` from the function to skip scheduling.
39
+ */
40
+ export type SuperwallTrialReminderConfig =
41
+ | SuperwallTrialReminderStaticConfig
42
+ | ((
43
+ context: SuperwallTrialReminderContext,
44
+ ) => SuperwallTrialReminderNotification | null | undefined);
45
+
46
+ export type SuperwallNotificationsConfig = {
47
+ /** Scheduled when the SDK reports a trial started (`freeTrial_start`). Default: none. */
48
+ trialReminder?: SuperwallTrialReminderConfig;
49
+ };
@@ -0,0 +1,8 @@
1
+ export const SUPERWALL_PLATFORMS = ["ios", "android", "web"] as const;
2
+
3
+ export type SuperwallPlatform = (typeof SUPERWALL_PLATFORMS)[number];
4
+
5
+ export const normalizePlatform = (value: string | undefined): SuperwallPlatform | undefined => {
6
+ const normalized = (value ?? "").toLowerCase();
7
+ return SUPERWALL_PLATFORMS.find((platform) => platform === normalized);
8
+ };
@@ -0,0 +1,22 @@
1
+ export type SuperwallPresentationStyle =
2
+ | "fullscreen"
3
+ | "modal"
4
+ | "push"
5
+ | "drawer"
6
+ | "popup"
7
+ | "noAnimation";
8
+
9
+ export type SuperwallPresentationConfig = {
10
+ /** How the native SDK presents the paywall. Default: `"fullscreen"`. */
11
+ style?: SuperwallPresentationStyle;
12
+ /**
13
+ * Drawer geometry, as percentages of the screen and points. Only read when
14
+ * style is "drawer". Default: `{ height: 70, cornerRadius: 15 }`.
15
+ */
16
+ drawer?: { height?: number; cornerRadius?: number };
17
+ /**
18
+ * Popup geometry, as percentages of the screen and points. Only read when
19
+ * style is "popup". Default: `{ width: 80, height: 60, cornerRadius: 15 }`.
20
+ */
21
+ popup?: { width?: number; height?: number; cornerRadius?: number };
22
+ };
@@ -0,0 +1,39 @@
1
+ import type { SuperwallPlatform } from "./platforms";
2
+
3
+ /**
4
+ * A product slot the paywall renders, keyed by reference in
5
+ * `SuperwallConfig["products"]`. Product data (price, period, trial…) is
6
+ * host-owned and arrives at runtime.
7
+ */
8
+ export type SuperwallProductSlot = {
9
+ /** Store product identifier this slot maps to (e.g. "pro_3999_year"). */
10
+ productId?: string;
11
+ };
12
+
13
+ /**
14
+ * One store identifier per platform the paywall ships to, for a slot whose
15
+ * underlying product differs by store — the same `purchase("annual")` buys
16
+ * the App Store product on iOS and the Play product on Android.
17
+ */
18
+ export type SuperwallPlatformProductIds = Partial<Record<SuperwallPlatform, string>>;
19
+
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
+
26
+ export const isPlatformProductIds = (
27
+ input: SuperwallProductSlotInput,
28
+ ): input is SuperwallPlatformProductIds =>
29
+ typeof input === "object" && input !== null && !("productId" in input);
30
+
31
+ export const productIdFor = (
32
+ input: SuperwallProductSlotInput,
33
+ platform?: SuperwallPlatform,
34
+ ): string | undefined => {
35
+ if (typeof input === "string") return input;
36
+ if (!isPlatformProductIds(input)) return input.productId;
37
+ if (platform !== undefined) return input[platform];
38
+ return Object.values(input).find((id) => typeof id === "string");
39
+ };
package/src/index.ts CHANGED
@@ -1,57 +1,16 @@
1
1
  export * from "./bridge";
2
- export * from "./bridge/base64";
3
- export * from "./bridge/transport";
4
2
  export * from "./config";
5
3
  export * from "./localization";
6
- export * from "./mock";
7
4
  export * from "./products";
8
5
  export * from "./session";
9
- export * from "./session/state";
10
- export * from "./session/variables";
11
6
 
12
- export {
13
- buildTransport,
14
- buildWebKitTransport,
15
- createTransportLogger,
16
- EditorTransport,
17
- EnabledProductSchema,
18
- IncomingMessageSchema,
19
- InitializationParamsSchema,
20
- MessageDirection,
21
- OutgoingMessagePingSchema,
22
- OutgoingMessageSchema,
23
- PageStyles,
24
- PermissionStatusSchema,
25
- PermissionTypeSchema,
26
- Platform,
27
- ProductIdentifierAndTypeSchema,
28
- SubsSchema,
29
- TransportKind,
30
- unwrap,
31
- wrap,
32
- } from "@superwall/protocol";
7
+ export { pendingHostMessages, TransportKind } from "@superwall/protocol";
33
8
 
34
9
  export type {
35
10
  ITransport,
36
- ProductIdentifierAndType,
37
- TIncomingHandler,
11
+ TEventTrackingBehavior,
38
12
  TIncomingMessage,
39
- TIncomingMessageCallbackResult,
40
- TIncomingMessageExperiment,
41
- TIncomingMessageFreeTrialStart,
42
- TIncomingMessagePaywallOpen,
43
- TIncomingMessagePermissionResult,
44
- TIncomingMessageProducts,
45
- TIncomingMessageTemplateVariables,
46
- TIncomingMessageTransactionAbandon,
47
- TIncomingMessageTransactionComplete,
48
- TInitializationParams,
49
- TMessage,
50
13
  TOutgoingMessage,
51
- TPageStyles,
52
- TPaywallControllerOptions,
53
14
  TPermissionStatus,
54
15
  TPermissionTypeMessage,
55
- WrappedMessage,
56
- WrappedMessagePayload,
57
16
  } from "@superwall/protocol";
@@ -0,0 +1,45 @@
1
+ import type { SuperwallLocalizationConfig, SuperwallMessages } from "../config/localization";
2
+
3
+ export type SuperwallTranslateValues = Record<string, string | number>;
4
+
5
+ export type SuperwallTranslator = {
6
+ t: (key: string, values?: SuperwallTranslateValues) => string;
7
+ locale: string;
8
+ locales: readonly string[];
9
+ };
10
+
11
+ const lookupMessage = (
12
+ messages: SuperwallMessages | undefined,
13
+ key: string,
14
+ ): string | undefined => {
15
+ let current: SuperwallMessages | string | undefined = messages;
16
+ for (const segment of key.split(".")) {
17
+ if (typeof current !== "object" || current === null) return undefined;
18
+ current = current[segment];
19
+ }
20
+ return typeof current === "string" ? current : undefined;
21
+ };
22
+
23
+ const interpolate = (template: string, values: SuperwallTranslateValues = {}): string =>
24
+ template.replace(/\{(\w+)\}/g, (match, name: string) =>
25
+ name in values ? String(values[name]) : match,
26
+ );
27
+
28
+ export const createTranslator = (
29
+ localization: SuperwallLocalizationConfig | undefined,
30
+ locale: string,
31
+ ): SuperwallTranslator => {
32
+ const messages = localization?.messages;
33
+ const defaultLocale = localization?.defaultLocale ?? "en";
34
+ return {
35
+ t: (key, values) =>
36
+ interpolate(
37
+ lookupMessage(messages?.[locale], key) ??
38
+ lookupMessage(messages?.[defaultLocale], key) ??
39
+ key,
40
+ values,
41
+ ),
42
+ locale,
43
+ locales: messages ? Object.keys(messages) : [defaultLocale],
44
+ };
45
+ };
@@ -1,110 +1,7 @@
1
- import type { SuperwallLocalizationConfig, SuperwallMessages } from "../config";
2
-
3
- export type SuperwallTranslateValues = Record<string, string | number>;
4
-
5
- export type SuperwallTranslator = {
6
- /**
7
- * Resolves a message key ("paywall.title") for the active locale,
8
- * interpolating `{name}` params. Unknown keys return the key itself, so
9
- * passing literal copy through `t()` is always safe.
10
- */
11
- t: (key: string, values?: SuperwallTranslateValues) => string;
12
- locale: string;
13
- /** Locales with a message catalog. */
14
- locales: readonly string[];
15
- };
16
-
17
- const lookupMessage = (messages: SuperwallMessages | undefined, key: string) => {
18
- if (!messages) return undefined;
19
-
20
- let current: SuperwallMessages | string | undefined = messages;
21
- for (const segment of key.split(".")) {
22
- if (typeof current !== "object" || current === null) return undefined;
23
- current = current[segment];
24
- }
25
-
26
- return typeof current === "string" ? current : undefined;
27
- };
28
-
29
- const interpolate = (template: string, values: SuperwallTranslateValues = {}) =>
30
- template.replace(/\{(\w+)\}/g, (match, name: string) =>
31
- name in values ? String(values[name]) : match,
32
- );
33
-
34
- /**
35
- * Language candidates for the shared period-translation table
36
- * ("de-DE" / "de_DE" → ["de_DE", "de"]), matching its underscore keys.
37
- */
38
- export const languageCandidates = (locale: string | undefined): string[] => {
39
- if (!locale) return ["en"];
40
-
41
- const normalized = locale.replace(/-/g, "_");
42
- const [language] = normalized.split("_");
43
- const candidates = [normalized];
44
-
45
- if (language && language !== normalized) {
46
- candidates.push(language.toLowerCase());
47
- }
48
-
49
- return candidates;
50
- };
51
-
52
- /** Normalizes "en_US" / "en-us" → "en-US"; returns [exact, language] candidates. */
53
- const localeCandidates = (locale: string): string[] => {
54
- const normalized = locale.replace(/_/g, "-");
55
- const [language, region] = normalized.split("-");
56
- const candidates: string[] = [];
57
-
58
- if (language && region) {
59
- candidates.push(`${language.toLowerCase()}-${region.toUpperCase()}`);
60
- }
61
- if (language) {
62
- candidates.push(language.toLowerCase());
63
- }
64
-
65
- return candidates;
66
- };
67
-
68
- /**
69
- * Picks the best available locale: exact match ("pt-BR"), then language
70
- * ("pt"), then the default locale.
71
- */
72
- export const resolveLocale = (
73
- requested: string | undefined,
74
- localization: SuperwallLocalizationConfig | undefined,
75
- ): string => {
76
- const defaultLocale = localization?.defaultLocale ?? "en";
77
- const messages = localization?.messages;
78
- if (!requested || !messages) return defaultLocale;
79
-
80
- const available = Object.keys(messages);
81
- const availableLower = new Map(available.map((locale) => [locale.toLowerCase(), locale]));
82
-
83
- for (const candidate of localeCandidates(requested)) {
84
- const match = availableLower.get(candidate.toLowerCase());
85
- if (match) return match;
86
- }
87
-
88
- return defaultLocale;
89
- };
90
-
91
- export const createTranslator = (
92
- localization: SuperwallLocalizationConfig | undefined,
93
- locale: string,
94
- ): SuperwallTranslator => {
95
- const messages = localization?.messages;
96
- const defaultLocale = localization?.defaultLocale ?? "en";
97
-
98
- const t = (key: string, values?: SuperwallTranslateValues) => {
99
- const resolved =
100
- lookupMessage(messages?.[locale], key) ?? lookupMessage(messages?.[defaultLocale], key);
101
-
102
- return interpolate(resolved ?? key, values);
103
- };
104
-
105
- return {
106
- t,
107
- locale,
108
- locales: messages ? Object.keys(messages) : [defaultLocale],
109
- };
110
- };
1
+ export {
2
+ createTranslator,
3
+ type SuperwallTranslateValues,
4
+ type SuperwallTranslator,
5
+ } from "./catalog";
6
+ export { resolveLocale } from "./locale";
7
+ export { getLocalizedPeriod, languageCandidates } from "./periods";