@superwall/runtime 1.1.0
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.
- package/LICENSE +105 -0
- package/README.md +93 -0
- package/dist/bridge/base64.d.ts +9 -0
- package/dist/bridge/base64.js +34 -0
- package/dist/bridge/index.d.ts +30 -0
- package/dist/bridge/index.js +49 -0
- package/dist/bridge/transport.d.ts +14 -0
- package/dist/bridge/transport.js +43 -0
- package/dist/config.d.ts +237 -0
- package/dist/config.js +138 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +11 -0
- package/dist/localization/index.d.ts +24 -0
- package/dist/localization/index.js +71 -0
- package/dist/localization/periods.d.ts +1 -0
- package/dist/localization/periods.js +753 -0
- package/dist/mock.d.ts +74 -0
- package/dist/mock.js +206 -0
- package/dist/products.d.ts +62 -0
- package/dist/products.js +105 -0
- package/dist/session/index.d.ts +103 -0
- package/dist/session/index.js +732 -0
- package/dist/session/state.d.ts +27 -0
- package/dist/session/state.js +60 -0
- package/dist/session/types.d.ts +93 -0
- package/dist/session/types.js +1 -0
- package/dist/session/variables.d.ts +121 -0
- package/dist/session/variables.js +5 -0
- package/package.json +51 -0
- package/src/bridge/base64.ts +56 -0
- package/src/bridge/index.ts +77 -0
- package/src/bridge/transport.ts +63 -0
- package/src/config.ts +408 -0
- package/src/index.ts +57 -0
- package/src/localization/index.ts +110 -0
- package/src/localization/periods.ts +790 -0
- package/src/mock.ts +333 -0
- package/src/products.ts +221 -0
- package/src/session/index.ts +1066 -0
- package/src/session/state.ts +112 -0
- package/src/session/types.ts +123 -0
- package/src/session/variables.ts +139 -0
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
import { getLocalizedPeriod } from "../localization/periods";
|
|
2
|
+
import { createSuperwallBridge } from "../bridge";
|
|
3
|
+
import { productsFromConfig } from "../config";
|
|
4
|
+
import { createTranslator, languageCandidates, resolveLocale, } from "../localization";
|
|
5
|
+
import { recordFromVariables } from "./variables";
|
|
6
|
+
import { createSuperwallProduct, mergeIncomingProducts, mergeProductVariables, productReferenceFromInput, productVariablesFromTemplateVariables, productsByReference, } from "../products";
|
|
7
|
+
import { buildSuperwallState } from "./state";
|
|
8
|
+
export * from "./types";
|
|
9
|
+
const permissionTypeToStateName = (permissionType) => permissionType.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
10
|
+
const callbackNameToStateName = (name) => {
|
|
11
|
+
const segments = name
|
|
12
|
+
.replace(/[^a-zA-Z0-9]/g, " ")
|
|
13
|
+
.trim()
|
|
14
|
+
.replace(/\s+/g, " ")
|
|
15
|
+
.split(" ")
|
|
16
|
+
.filter(Boolean);
|
|
17
|
+
if (segments.length === 0) {
|
|
18
|
+
return "callback";
|
|
19
|
+
}
|
|
20
|
+
return segments
|
|
21
|
+
.map((segment, index) => index === 0
|
|
22
|
+
? segment.charAt(0).toLowerCase() + segment.slice(1)
|
|
23
|
+
: segment.charAt(0).toUpperCase() + segment.slice(1))
|
|
24
|
+
.join("");
|
|
25
|
+
};
|
|
26
|
+
const initialTrialState = (config) => {
|
|
27
|
+
switch (config?.introductoryOfferEligibility) {
|
|
28
|
+
case "alwaysEligible":
|
|
29
|
+
return { eligible: true };
|
|
30
|
+
case "alwaysIneligible":
|
|
31
|
+
return { eligible: false };
|
|
32
|
+
default:
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
37
|
+
/**
|
|
38
|
+
* Mirrors the schema editor's computeTrialPeriodEndDate: "Jul 23, 2026",
|
|
39
|
+
* month name localized to the active locale where the runtime supports it.
|
|
40
|
+
*/
|
|
41
|
+
const computeTrialPeriodEndDate = (trialPeriodDays, language) => {
|
|
42
|
+
const parsedDays = typeof trialPeriodDays === "number" ? trialPeriodDays : Number(trialPeriodDays);
|
|
43
|
+
if (!Number.isFinite(parsedDays) || parsedDays <= 0) {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
const endDate = new Date();
|
|
47
|
+
endDate.setDate(endDate.getDate() + Math.trunc(parsedDays));
|
|
48
|
+
let month;
|
|
49
|
+
try {
|
|
50
|
+
month = endDate.toLocaleString(language?.replace(/_/g, "-") ?? "default", { month: "short" });
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
month = endDate.toLocaleString("default", { month: "short" });
|
|
54
|
+
}
|
|
55
|
+
return `${month} ${endDate.getDate()}, ${endDate.getFullYear()}`;
|
|
56
|
+
};
|
|
57
|
+
const createRequestId = (prefix) => {
|
|
58
|
+
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
|
59
|
+
return `${prefix}-${crypto.randomUUID()}`;
|
|
60
|
+
}
|
|
61
|
+
return `${prefix}-${Math.random().toString(36).slice(2)}`;
|
|
62
|
+
};
|
|
63
|
+
class SuperwallSessionImpl {
|
|
64
|
+
bridge;
|
|
65
|
+
listeners = new Set();
|
|
66
|
+
pendingPurchases = new Map();
|
|
67
|
+
pendingPermissions = new Map();
|
|
68
|
+
pendingCallbacks = new Map();
|
|
69
|
+
eventHandlers = new Map();
|
|
70
|
+
snapshot;
|
|
71
|
+
translator;
|
|
72
|
+
localeOverride;
|
|
73
|
+
rawProducts;
|
|
74
|
+
localizedProductsCache;
|
|
75
|
+
constructor(options = {}) {
|
|
76
|
+
this.bridge = options.bridge ?? createSuperwallBridge(options);
|
|
77
|
+
const products = options.products ?? productsFromConfig(options.config);
|
|
78
|
+
this.rawProducts = products;
|
|
79
|
+
const variables = options.variables ?? {};
|
|
80
|
+
const locale = resolveLocale(undefined, options.config?.localization);
|
|
81
|
+
this.translator = createTranslator(options.config?.localization, locale);
|
|
82
|
+
this.snapshot = {
|
|
83
|
+
status: "idle",
|
|
84
|
+
config: options.config,
|
|
85
|
+
products,
|
|
86
|
+
productsByReference: productsByReference(products),
|
|
87
|
+
variables,
|
|
88
|
+
device: {},
|
|
89
|
+
user: {},
|
|
90
|
+
params: {},
|
|
91
|
+
trial: initialTrialState(options.config),
|
|
92
|
+
locale,
|
|
93
|
+
permissionStatuses: {},
|
|
94
|
+
callbackStates: {},
|
|
95
|
+
state: buildSuperwallState({ variables, products }),
|
|
96
|
+
messages: [...this.bridge.messages],
|
|
97
|
+
};
|
|
98
|
+
this.bridge.addListener((message) => {
|
|
99
|
+
this.handleIncomingMessage(message);
|
|
100
|
+
this.emit(message.event_name, message);
|
|
101
|
+
this.emit("message", message);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Subscribes to a single incoming SDK event by name, or "message" for all
|
|
106
|
+
* incoming messages. Returns an unsubscribe function.
|
|
107
|
+
*/
|
|
108
|
+
on(event, handler) {
|
|
109
|
+
const handlers = this.handlersFor(event) ?? new Set();
|
|
110
|
+
this.eventHandlers.set(event, handlers);
|
|
111
|
+
handlers.add(handler);
|
|
112
|
+
return () => {
|
|
113
|
+
handlers.delete(handler);
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* `on`/`emit` enforce that handlers stored under an event name only ever
|
|
118
|
+
* receive that event's payload; TypeScript cannot carry that key↔value
|
|
119
|
+
* correlation through a heterogeneous store (microsoft/TypeScript#47109),
|
|
120
|
+
* so this accessor is the one place it is asserted.
|
|
121
|
+
*/
|
|
122
|
+
handlersFor(event) {
|
|
123
|
+
return this.eventHandlers.get(event);
|
|
124
|
+
}
|
|
125
|
+
emit(event, payload) {
|
|
126
|
+
const handlers = this.handlersFor(event);
|
|
127
|
+
if (!handlers)
|
|
128
|
+
return;
|
|
129
|
+
for (const handler of handlers) {
|
|
130
|
+
handler(payload);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
subscribe = (listener) => {
|
|
134
|
+
this.listeners.add(listener);
|
|
135
|
+
return () => {
|
|
136
|
+
this.listeners.delete(listener);
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
getSnapshot = () => this.snapshot;
|
|
140
|
+
get products() {
|
|
141
|
+
return this.snapshot.products;
|
|
142
|
+
}
|
|
143
|
+
get config() {
|
|
144
|
+
return this.snapshot.config;
|
|
145
|
+
}
|
|
146
|
+
get locale() {
|
|
147
|
+
return this.snapshot.locale;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Resolves a message key for the active locale, interpolating `{name}`
|
|
151
|
+
* params. Unknown keys return the key itself, so literal copy is safe.
|
|
152
|
+
*/
|
|
153
|
+
t = (key, values) => this.translator.t(key, values);
|
|
154
|
+
/** Overrides the locale (normally auto-detected from the device). */
|
|
155
|
+
setLocale(locale) {
|
|
156
|
+
this.localeOverride = locale;
|
|
157
|
+
this.patch({});
|
|
158
|
+
}
|
|
159
|
+
configure(config) {
|
|
160
|
+
if (config === this.snapshot.config) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const patch = { config };
|
|
164
|
+
// Reseed product slots from the new config unless the SDK has already
|
|
165
|
+
// delivered real products (the SDK always wins over config seeds).
|
|
166
|
+
const hasSdkProducts = this.rawProducts.some((product) => product.source === "sdk");
|
|
167
|
+
if (!hasSdkProducts) {
|
|
168
|
+
this.rawProducts = productsFromConfig(config);
|
|
169
|
+
}
|
|
170
|
+
// Re-derive forced trial eligibility; "automatic" keeps whatever the SDK
|
|
171
|
+
// has signaled so far.
|
|
172
|
+
if (config.introductoryOfferEligibility === "alwaysEligible" ||
|
|
173
|
+
config.introductoryOfferEligibility === "alwaysIneligible") {
|
|
174
|
+
patch.trial = initialTrialState(config);
|
|
175
|
+
}
|
|
176
|
+
this.patch(patch);
|
|
177
|
+
}
|
|
178
|
+
start(options = {}) {
|
|
179
|
+
if (this.snapshot.status !== "listening") {
|
|
180
|
+
this.bridge.start();
|
|
181
|
+
this.patch({ status: "listening" });
|
|
182
|
+
}
|
|
183
|
+
if (options.sendPing) {
|
|
184
|
+
this.ping(options.ping);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
postMessage(message) {
|
|
188
|
+
this.bridge.postMessage(message);
|
|
189
|
+
this.patch({ messages: this.bridge.messages });
|
|
190
|
+
}
|
|
191
|
+
accept(messages) {
|
|
192
|
+
this.bridge.accept(messages);
|
|
193
|
+
}
|
|
194
|
+
accept64(message) {
|
|
195
|
+
this.bridge.accept64(message);
|
|
196
|
+
}
|
|
197
|
+
ping(message = {}) {
|
|
198
|
+
this.postMessage({
|
|
199
|
+
event_name: "ping",
|
|
200
|
+
substitutions: [],
|
|
201
|
+
page_styles: [],
|
|
202
|
+
version: "4.0.0",
|
|
203
|
+
...message,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
close() {
|
|
207
|
+
this.postMessage({ event_name: "close" });
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Asks the SDK to restore purchases. The message protocol has no restore
|
|
211
|
+
* result event, so this cannot resolve with an outcome; a successful restore
|
|
212
|
+
* typically dismisses the paywall or arrives as `transaction_complete`
|
|
213
|
+
* (observable via `on("transaction_complete", ...)`).
|
|
214
|
+
*/
|
|
215
|
+
restore() {
|
|
216
|
+
this.postMessage({ event_name: "restore" });
|
|
217
|
+
}
|
|
218
|
+
openUrl(url, options = {}) {
|
|
219
|
+
this.postMessage({
|
|
220
|
+
event_name: "open_url",
|
|
221
|
+
url,
|
|
222
|
+
browser_type: options.browserType,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
openExternalUrl(url) {
|
|
226
|
+
this.postMessage({
|
|
227
|
+
event_name: "open_url_external",
|
|
228
|
+
url,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
openDeepLink(link) {
|
|
232
|
+
this.postMessage({
|
|
233
|
+
event_name: "open_deep_link",
|
|
234
|
+
link,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
custom(data) {
|
|
238
|
+
this.postMessage({
|
|
239
|
+
event_name: "custom",
|
|
240
|
+
data,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
customPlacement(name, params = {}) {
|
|
244
|
+
this.postMessage({
|
|
245
|
+
event_name: "custom_placement",
|
|
246
|
+
name,
|
|
247
|
+
params,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
requestStoreReview(reviewType) {
|
|
251
|
+
this.postMessage({
|
|
252
|
+
event_name: "request_store_review",
|
|
253
|
+
review_type: reviewType,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
setUserAttributes(attributes) {
|
|
257
|
+
this.postMessage({
|
|
258
|
+
event_name: "user_attribute_updated",
|
|
259
|
+
attributes: Object.entries(attributes).map(([key, value]) => ({
|
|
260
|
+
key,
|
|
261
|
+
value,
|
|
262
|
+
})),
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
pageView(input) {
|
|
266
|
+
this.postMessage({
|
|
267
|
+
event_name: "page_view",
|
|
268
|
+
type: input.type,
|
|
269
|
+
page_name: input.name,
|
|
270
|
+
page_node_id: input.name,
|
|
271
|
+
navigation_node_id: input.navigationId,
|
|
272
|
+
flow_position: input.position,
|
|
273
|
+
previous_page_node_id: input.previousName,
|
|
274
|
+
previous_flow_position: input.previousPosition,
|
|
275
|
+
time_on_previous_page_ms: input.timeOnPreviousMs,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
scheduleTrialReminder(input) {
|
|
279
|
+
this.postMessage({
|
|
280
|
+
event_name: "schedule_notification",
|
|
281
|
+
id: input.id,
|
|
282
|
+
type: "TRIAL_STARTED",
|
|
283
|
+
title: input.title,
|
|
284
|
+
subtitle: input.subtitle,
|
|
285
|
+
body: input.body,
|
|
286
|
+
delay: input.delayMs,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
hapticFeedback(hapticType) {
|
|
290
|
+
this.postMessage({
|
|
291
|
+
event_name: "haptic_feedback",
|
|
292
|
+
haptic_type: hapticType,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
requestPermission(permissionType) {
|
|
296
|
+
const requestId = createRequestId(`permission-${permissionType}`);
|
|
297
|
+
const result = new Promise((resolve) => {
|
|
298
|
+
this.pendingPermissions.set(requestId, { resolve });
|
|
299
|
+
});
|
|
300
|
+
this.postMessage({
|
|
301
|
+
event_name: "request_permission",
|
|
302
|
+
permission_type: permissionType,
|
|
303
|
+
request_id: requestId,
|
|
304
|
+
});
|
|
305
|
+
return result;
|
|
306
|
+
}
|
|
307
|
+
requestCallback(name, options = {}) {
|
|
308
|
+
const requestId = createRequestId(`callback-${name}`);
|
|
309
|
+
const behavior = options.behavior ?? "blocking";
|
|
310
|
+
const result = new Promise((resolve) => {
|
|
311
|
+
this.pendingCallbacks.set(requestId, { name, resolve });
|
|
312
|
+
});
|
|
313
|
+
this.postMessage({
|
|
314
|
+
event_name: "request_callback",
|
|
315
|
+
request_id: requestId,
|
|
316
|
+
name,
|
|
317
|
+
behavior,
|
|
318
|
+
variables: options.variables,
|
|
319
|
+
});
|
|
320
|
+
// TData is the caller's claim about the SDK-owned payload — the same
|
|
321
|
+
// unverifiable-claim seam as `createSuperwallSession`.
|
|
322
|
+
return result;
|
|
323
|
+
}
|
|
324
|
+
purchase(input, options = {}) {
|
|
325
|
+
const product = this.resolveProduct(input);
|
|
326
|
+
const timeoutMs = options.timeoutMs ?? this.snapshot.config?.purchaseTimeoutMs;
|
|
327
|
+
// A retry for the same product replaces the previous attempt: settle the
|
|
328
|
+
// old promise and disarm its timer so it can't fire against the new one.
|
|
329
|
+
this.cancelPendingPurchase(product.reference, "superseded");
|
|
330
|
+
const result = new Promise((resolve) => {
|
|
331
|
+
const pending = { product, resolve };
|
|
332
|
+
if (timeoutMs !== undefined) {
|
|
333
|
+
pending.timeoutId = setTimeout(() => {
|
|
334
|
+
this.failPurchase(product.reference, "timeout");
|
|
335
|
+
}, timeoutMs);
|
|
336
|
+
}
|
|
337
|
+
this.pendingPurchases.set(product.reference, pending);
|
|
338
|
+
});
|
|
339
|
+
this.patch({
|
|
340
|
+
pendingPurchase: {
|
|
341
|
+
reference: product.reference,
|
|
342
|
+
product,
|
|
343
|
+
},
|
|
344
|
+
lastPurchaseFailure: undefined,
|
|
345
|
+
});
|
|
346
|
+
this.postMessage({
|
|
347
|
+
event_name: "purchase",
|
|
348
|
+
product: product.reference,
|
|
349
|
+
product_identifier: product.productIdentifier ?? product.productId ?? product.id,
|
|
350
|
+
should_dismiss: options.shouldDismiss ?? this.snapshot.config?.dismissOnPurchase,
|
|
351
|
+
});
|
|
352
|
+
return result;
|
|
353
|
+
}
|
|
354
|
+
getProduct(reference) {
|
|
355
|
+
return this.snapshot.productsByReference[reference];
|
|
356
|
+
}
|
|
357
|
+
handleIncomingMessage(message) {
|
|
358
|
+
switch (message.event_name) {
|
|
359
|
+
case "paywall_open":
|
|
360
|
+
// A (re)presentation resets transaction state: settle any in-flight
|
|
361
|
+
// purchases so their timers and promises can't leak into the new view.
|
|
362
|
+
for (const reference of Array.from(this.pendingPurchases.keys())) {
|
|
363
|
+
this.cancelPendingPurchase(reference, "superseded");
|
|
364
|
+
}
|
|
365
|
+
this.patch({
|
|
366
|
+
paywall: {
|
|
367
|
+
id: message.paywall_id,
|
|
368
|
+
identifier: message.paywall_identifier,
|
|
369
|
+
},
|
|
370
|
+
pendingPurchase: undefined,
|
|
371
|
+
lastTransaction: undefined,
|
|
372
|
+
lastPurchaseFailure: undefined,
|
|
373
|
+
messages: this.bridge.messages,
|
|
374
|
+
});
|
|
375
|
+
break;
|
|
376
|
+
case "products":
|
|
377
|
+
this.setProducts(mergeIncomingProducts(this.rawProducts, message.products));
|
|
378
|
+
break;
|
|
379
|
+
case "template_variables": {
|
|
380
|
+
const productVariables = productVariablesFromTemplateVariables(message.variables);
|
|
381
|
+
this.patch({
|
|
382
|
+
variables: message.variables,
|
|
383
|
+
device: recordFromVariables(message.variables, "device"),
|
|
384
|
+
user: recordFromVariables(message.variables, "user"),
|
|
385
|
+
params: recordFromVariables(message.variables, "params"),
|
|
386
|
+
messages: this.bridge.messages,
|
|
387
|
+
});
|
|
388
|
+
if (productVariables.size > 0) {
|
|
389
|
+
this.setProducts(mergeProductVariables(this.rawProducts, productVariables));
|
|
390
|
+
}
|
|
391
|
+
break;
|
|
392
|
+
}
|
|
393
|
+
case "template_substitutions_prefix": {
|
|
394
|
+
// The SDK signals introductory-offer eligibility by switching the
|
|
395
|
+
// substitutions prefix to "freeTrial". Config overrides win.
|
|
396
|
+
if (this.snapshot.config?.introductoryOfferEligibility === "alwaysEligible")
|
|
397
|
+
break;
|
|
398
|
+
if (this.snapshot.config?.introductoryOfferEligibility === "alwaysIneligible")
|
|
399
|
+
break;
|
|
400
|
+
this.patch({
|
|
401
|
+
trial: { eligible: message.prefix === "freeTrial" },
|
|
402
|
+
messages: this.bridge.messages,
|
|
403
|
+
});
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
case "experiment":
|
|
407
|
+
this.patch({
|
|
408
|
+
experiment: {
|
|
409
|
+
experimentId: message.experimentId,
|
|
410
|
+
variantId: message.variantId,
|
|
411
|
+
campaignId: message.campaignId,
|
|
412
|
+
},
|
|
413
|
+
messages: this.bridge.messages,
|
|
414
|
+
});
|
|
415
|
+
break;
|
|
416
|
+
case "freeTrial_start":
|
|
417
|
+
this.scheduleConfiguredTrialReminder(message);
|
|
418
|
+
this.patch({ messages: this.bridge.messages });
|
|
419
|
+
break;
|
|
420
|
+
case "transaction_complete":
|
|
421
|
+
this.resolvePurchase(message);
|
|
422
|
+
break;
|
|
423
|
+
case "transaction_abandon":
|
|
424
|
+
this.resolvePurchase(message);
|
|
425
|
+
break;
|
|
426
|
+
case "permission_result":
|
|
427
|
+
this.resolvePermission(message);
|
|
428
|
+
break;
|
|
429
|
+
case "callback_result":
|
|
430
|
+
this.resolveCallback(message);
|
|
431
|
+
break;
|
|
432
|
+
default:
|
|
433
|
+
this.patch({ messages: this.bridge.messages });
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Auto-schedules the config's trial reminder when the SDK reports a trial
|
|
439
|
+
* started. Static configs run title/subtitle/body through `t()`; dynamic
|
|
440
|
+
* configs (functions) compute the notification from the trial context.
|
|
441
|
+
*/
|
|
442
|
+
scheduleConfiguredTrialReminder(message) {
|
|
443
|
+
const reminder = this.snapshot.config?.notifications?.trialReminder;
|
|
444
|
+
if (!reminder)
|
|
445
|
+
return;
|
|
446
|
+
if (!message.trial_end_date)
|
|
447
|
+
return;
|
|
448
|
+
const trialEndMs = typeof message.trial_end_date === "number"
|
|
449
|
+
? message.trial_end_date
|
|
450
|
+
: Date.parse(message.trial_end_date);
|
|
451
|
+
if (Number.isNaN(trialEndMs))
|
|
452
|
+
return;
|
|
453
|
+
let notification;
|
|
454
|
+
if (typeof reminder === "function") {
|
|
455
|
+
const product = message.product_identifier
|
|
456
|
+
? this.rawProducts.find((candidate) => candidate.productIdentifier === message.product_identifier ||
|
|
457
|
+
candidate.productId === message.product_identifier)
|
|
458
|
+
: undefined;
|
|
459
|
+
const resolved = reminder({
|
|
460
|
+
trialEndDate: new Date(trialEndMs),
|
|
461
|
+
productIdentifier: message.product_identifier,
|
|
462
|
+
product,
|
|
463
|
+
t: this.t,
|
|
464
|
+
locale: this.snapshot.locale,
|
|
465
|
+
});
|
|
466
|
+
if (!resolved)
|
|
467
|
+
return;
|
|
468
|
+
notification = resolved;
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
if (reminder.enabled === false)
|
|
472
|
+
return;
|
|
473
|
+
const beforeTrialEndDays = reminder.beforeTrialEndDays ?? 1;
|
|
474
|
+
notification = {
|
|
475
|
+
title: this.t(reminder.title),
|
|
476
|
+
subtitle: reminder.subtitle ? this.t(reminder.subtitle) : undefined,
|
|
477
|
+
body: this.t(reminder.body),
|
|
478
|
+
delayMs: trialEndMs - beforeTrialEndDays * DAY_MS - Date.now(),
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
if (notification.delayMs <= 0)
|
|
482
|
+
return;
|
|
483
|
+
this.postMessage({
|
|
484
|
+
event_name: "schedule_notification",
|
|
485
|
+
id: `${this.snapshot.paywall?.identifier ?? "paywall"}_TRIAL_STARTED`,
|
|
486
|
+
type: "TRIAL_STARTED",
|
|
487
|
+
title: notification.title,
|
|
488
|
+
subtitle: notification.subtitle,
|
|
489
|
+
body: notification.body,
|
|
490
|
+
delay: notification.delayMs,
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
setProducts(products) {
|
|
494
|
+
this.rawProducts = products;
|
|
495
|
+
this.patch({ messages: this.bridge.messages });
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* The runtime's derived-variables layer — the headless equivalent of the
|
|
499
|
+
* schema editor's buildStateIndex computeds. Raw SDK values are kept
|
|
500
|
+
* internally; every snapshot derives from them so locale changes re-derive
|
|
501
|
+
* cleanly. Currently derives:
|
|
502
|
+
* - `period` / `periodly` localized with the shared translation table
|
|
503
|
+
* - `trialPeriodEndDate` from `trialPeriodDays` when the SDK omits it
|
|
504
|
+
*/
|
|
505
|
+
deriveProducts(raw, languages) {
|
|
506
|
+
const cacheKey = languages.join(",");
|
|
507
|
+
if (this.localizedProductsCache &&
|
|
508
|
+
this.localizedProductsCache.raw === raw &&
|
|
509
|
+
this.localizedProductsCache.languages === cacheKey) {
|
|
510
|
+
return this.localizedProductsCache.products;
|
|
511
|
+
}
|
|
512
|
+
const products = raw.map((product) => {
|
|
513
|
+
const { period, periodly, trialPeriodDays, trialPeriodEndDate } = product.variables;
|
|
514
|
+
const derivedEndDate = trialPeriodEndDate === undefined
|
|
515
|
+
? computeTrialPeriodEndDate(trialPeriodDays, languages[0])
|
|
516
|
+
: undefined;
|
|
517
|
+
if (typeof period !== "string" &&
|
|
518
|
+
typeof periodly !== "string" &&
|
|
519
|
+
derivedEndDate === undefined) {
|
|
520
|
+
return product;
|
|
521
|
+
}
|
|
522
|
+
return {
|
|
523
|
+
...product,
|
|
524
|
+
variables: {
|
|
525
|
+
...product.variables,
|
|
526
|
+
...(typeof period === "string"
|
|
527
|
+
? { period: getLocalizedPeriod(period, [...languages]) }
|
|
528
|
+
: {}),
|
|
529
|
+
...(typeof periodly === "string"
|
|
530
|
+
? { periodly: getLocalizedPeriod(periodly, [...languages]) }
|
|
531
|
+
: {}),
|
|
532
|
+
...(derivedEndDate !== undefined ? { trialPeriodEndDate: derivedEndDate } : {}),
|
|
533
|
+
},
|
|
534
|
+
};
|
|
535
|
+
});
|
|
536
|
+
this.localizedProductsCache = { raw, languages: cacheKey, products };
|
|
537
|
+
return products;
|
|
538
|
+
}
|
|
539
|
+
resolveProduct(input) {
|
|
540
|
+
const reference = productReferenceFromInput(input);
|
|
541
|
+
const existing = this.snapshot.productsByReference[reference];
|
|
542
|
+
if (existing) {
|
|
543
|
+
return existing;
|
|
544
|
+
}
|
|
545
|
+
return createSuperwallProduct(input);
|
|
546
|
+
}
|
|
547
|
+
resolveProductFromTransaction(message) {
|
|
548
|
+
if (message.product) {
|
|
549
|
+
return this.resolveProduct(message.product);
|
|
550
|
+
}
|
|
551
|
+
if (message.product_identifier) {
|
|
552
|
+
const product = this.snapshot.products.find((candidate) => candidate.productIdentifier === message.product_identifier ||
|
|
553
|
+
candidate.productId === message.product_identifier ||
|
|
554
|
+
candidate.id === message.product_identifier);
|
|
555
|
+
if (product) {
|
|
556
|
+
return product;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return createSuperwallProduct(message.product_identifier ?? message.product ?? "unknown");
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Attributes a transaction message to a pending purchase. Explicit product
|
|
563
|
+
* info on the message must match the pending purchase — an unrelated
|
|
564
|
+
* transaction (e.g. a restore completing another product) must not resolve
|
|
565
|
+
* it. Only a bare transaction with a single pending purchase falls back to
|
|
566
|
+
* that purchase, since some SDK versions omit product info.
|
|
567
|
+
*/
|
|
568
|
+
pendingPurchaseForTransaction(message) {
|
|
569
|
+
if (message.product) {
|
|
570
|
+
return this.pendingPurchases.get(message.product);
|
|
571
|
+
}
|
|
572
|
+
if (message.product_identifier) {
|
|
573
|
+
for (const pending of this.pendingPurchases.values()) {
|
|
574
|
+
if (pending.product.productIdentifier === message.product_identifier ||
|
|
575
|
+
pending.product.productId === message.product_identifier ||
|
|
576
|
+
pending.product.id === message.product_identifier) {
|
|
577
|
+
return pending;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return undefined;
|
|
581
|
+
}
|
|
582
|
+
return this.pendingPurchases.size === 1 ? this.firstPendingPurchase() : undefined;
|
|
583
|
+
}
|
|
584
|
+
resolvePurchase(message) {
|
|
585
|
+
const pending = this.pendingPurchaseForTransaction(message);
|
|
586
|
+
const product = pending?.product ?? this.resolveProductFromTransaction(message);
|
|
587
|
+
const result = message.event_name === "transaction_complete"
|
|
588
|
+
? { status: "completed", product, message }
|
|
589
|
+
: { status: "abandoned", product, message };
|
|
590
|
+
if (pending) {
|
|
591
|
+
if (pending.timeoutId !== undefined) {
|
|
592
|
+
clearTimeout(pending.timeoutId);
|
|
593
|
+
}
|
|
594
|
+
this.pendingPurchases.delete(pending.product.reference);
|
|
595
|
+
pending.resolve(result);
|
|
596
|
+
}
|
|
597
|
+
const clearsSnapshotPending = pending !== undefined &&
|
|
598
|
+
this.snapshot.pendingPurchase?.reference === pending.product.reference;
|
|
599
|
+
this.patch({
|
|
600
|
+
pendingPurchase: clearsSnapshotPending ? undefined : this.snapshot.pendingPurchase,
|
|
601
|
+
lastTransaction: result,
|
|
602
|
+
lastPurchaseFailure: undefined,
|
|
603
|
+
messages: this.bridge.messages,
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
failPurchase(reference, reason) {
|
|
607
|
+
const failure = this.cancelPendingPurchase(reference, reason);
|
|
608
|
+
if (!failure)
|
|
609
|
+
return;
|
|
610
|
+
this.patch({
|
|
611
|
+
pendingPurchase: this.snapshot.pendingPurchase?.reference === reference
|
|
612
|
+
? undefined
|
|
613
|
+
: this.snapshot.pendingPurchase,
|
|
614
|
+
lastPurchaseFailure: failure,
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Settles and removes a pending purchase as failed without touching the
|
|
619
|
+
* snapshot. Returns the failure, or undefined if nothing was pending.
|
|
620
|
+
*/
|
|
621
|
+
cancelPendingPurchase(reference, reason) {
|
|
622
|
+
const pending = this.pendingPurchases.get(reference);
|
|
623
|
+
if (!pending)
|
|
624
|
+
return undefined;
|
|
625
|
+
if (pending.timeoutId !== undefined) {
|
|
626
|
+
clearTimeout(pending.timeoutId);
|
|
627
|
+
}
|
|
628
|
+
this.pendingPurchases.delete(reference);
|
|
629
|
+
const failure = {
|
|
630
|
+
status: "failed",
|
|
631
|
+
product: pending.product,
|
|
632
|
+
reason,
|
|
633
|
+
};
|
|
634
|
+
pending.resolve(failure);
|
|
635
|
+
return failure;
|
|
636
|
+
}
|
|
637
|
+
firstPendingPurchase() {
|
|
638
|
+
for (const pending of this.pendingPurchases.values()) {
|
|
639
|
+
return pending;
|
|
640
|
+
}
|
|
641
|
+
return undefined;
|
|
642
|
+
}
|
|
643
|
+
resolvePermission(message) {
|
|
644
|
+
const pending = this.pendingPermissions.get(message.request_id);
|
|
645
|
+
if (pending) {
|
|
646
|
+
this.pendingPermissions.delete(message.request_id);
|
|
647
|
+
pending.resolve(message.status);
|
|
648
|
+
}
|
|
649
|
+
this.patch({
|
|
650
|
+
permissionStatuses: {
|
|
651
|
+
...this.snapshot.permissionStatuses,
|
|
652
|
+
[permissionTypeToStateName(message.permission_type)]: message.status,
|
|
653
|
+
},
|
|
654
|
+
messages: this.bridge.messages,
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
resolveCallback(message) {
|
|
658
|
+
const pending = this.pendingCallbacks.get(message.request_id);
|
|
659
|
+
const callbackName = callbackNameToStateName(pending?.name ?? message.name);
|
|
660
|
+
if (pending) {
|
|
661
|
+
this.pendingCallbacks.delete(message.request_id);
|
|
662
|
+
pending.resolve({
|
|
663
|
+
status: message.status,
|
|
664
|
+
data: message.data,
|
|
665
|
+
message,
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
this.patch({
|
|
669
|
+
callbackStates: {
|
|
670
|
+
...this.snapshot.callbackStates,
|
|
671
|
+
[callbackName]: {
|
|
672
|
+
result: message.status,
|
|
673
|
+
data: message.data,
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
messages: this.bridge.messages,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
patch(patch) {
|
|
680
|
+
const nextSnapshot = {
|
|
681
|
+
...this.snapshot,
|
|
682
|
+
...patch,
|
|
683
|
+
};
|
|
684
|
+
// The bridge's log is one mutable array; snapshots must be immutable
|
|
685
|
+
// views of it. Copy when it grew, keep the previous copy otherwise so
|
|
686
|
+
// memoized consumers see a stable identity.
|
|
687
|
+
nextSnapshot.messages =
|
|
688
|
+
this.bridge.messages.length === this.snapshot.messages.length
|
|
689
|
+
? this.snapshot.messages
|
|
690
|
+
: [...this.bridge.messages];
|
|
691
|
+
const deviceLocale = nextSnapshot.device.deviceLocale ?? nextSnapshot.device.deviceLanguageCode;
|
|
692
|
+
const requestedLocale = this.localeOverride ?? (typeof deviceLocale === "string" ? deviceLocale : undefined);
|
|
693
|
+
const locale = resolveLocale(requestedLocale, nextSnapshot.config?.localization);
|
|
694
|
+
if (locale !== this.translator.locale || nextSnapshot.config !== this.snapshot.config) {
|
|
695
|
+
this.translator = createTranslator(nextSnapshot.config?.localization, locale);
|
|
696
|
+
}
|
|
697
|
+
const products = this.deriveProducts(this.rawProducts, languageCandidates(requestedLocale));
|
|
698
|
+
if (products !== nextSnapshot.products) {
|
|
699
|
+
nextSnapshot.products = products;
|
|
700
|
+
nextSnapshot.productsByReference = productsByReference(products);
|
|
701
|
+
}
|
|
702
|
+
this.snapshot = {
|
|
703
|
+
...nextSnapshot,
|
|
704
|
+
locale,
|
|
705
|
+
state: buildSuperwallState({
|
|
706
|
+
variables: nextSnapshot.variables,
|
|
707
|
+
products: nextSnapshot.products,
|
|
708
|
+
paywall: nextSnapshot.paywall,
|
|
709
|
+
lastTransaction: nextSnapshot.lastTransaction,
|
|
710
|
+
permissionStatuses: nextSnapshot.permissionStatuses,
|
|
711
|
+
callbackStates: nextSnapshot.callbackStates,
|
|
712
|
+
trial: nextSnapshot.trial,
|
|
713
|
+
}),
|
|
714
|
+
};
|
|
715
|
+
for (const listener of this.listeners) {
|
|
716
|
+
listener();
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Creates a runtime session.
|
|
722
|
+
*
|
|
723
|
+
* `TProduct` is the caller's declaration of what SDK-delivered products look
|
|
724
|
+
* like (custom template variables layered over the known ones). The runtime
|
|
725
|
+
* cannot verify it — the SDK owns the values — so this downcast is the single
|
|
726
|
+
* seam where the claim is applied; every refined type downstream derives from
|
|
727
|
+
* it.
|
|
728
|
+
*/
|
|
729
|
+
export const createSuperwallSession = (options = {}) => {
|
|
730
|
+
const session = new SuperwallSessionImpl(options);
|
|
731
|
+
return session;
|
|
732
|
+
};
|