@rocapine/react-native-onboarding 1.77.0 → 1.79.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/README.md +38 -10
- package/dist/OnboardingStudio.d.ts +14 -1
- package/dist/OnboardingStudio.d.ts.map +1 -1
- package/dist/OnboardingStudio.js +5 -1
- package/dist/OnboardingStudio.js.map +1 -1
- package/dist/OnboardingStudioClient.d.ts +31 -0
- package/dist/OnboardingStudioClient.d.ts.map +1 -1
- package/dist/OnboardingStudioClient.js +80 -19
- package/dist/OnboardingStudioClient.js.map +1 -1
- package/dist/assignmentId.d.ts +107 -0
- package/dist/assignmentId.d.ts.map +1 -0
- package/dist/assignmentId.js +215 -0
- package/dist/assignmentId.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -2
- package/dist/index.js.map +1 -1
- package/dist/paywalls/PaywallProvider.d.ts +8 -1
- package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
- package/dist/paywalls/PaywallProvider.js +5 -1
- package/dist/paywalls/PaywallProvider.js.map +1 -1
- package/dist/paywalls/customScreens.d.ts +7 -0
- package/dist/paywalls/customScreens.d.ts.map +1 -1
- package/dist/paywalls/devHook.d.ts +26 -0
- package/dist/paywalls/devHook.d.ts.map +1 -0
- package/dist/paywalls/devHook.js +29 -0
- package/dist/paywalls/devHook.js.map +1 -0
- package/dist/paywalls/observer.d.ts +2 -0
- package/dist/paywalls/observer.d.ts.map +1 -1
- package/dist/paywalls/observer.js +21 -9
- package/dist/paywalls/observer.js.map +1 -1
- package/dist/paywalls/types.d.ts +22 -0
- package/dist/paywalls/types.d.ts.map +1 -1
- package/dist/products/adapters/expoIap.d.ts +34 -13
- package/dist/products/adapters/expoIap.d.ts.map +1 -1
- package/dist/products/adapters/expoIap.js +136 -21
- package/dist/products/adapters/expoIap.js.map +1 -1
- package/dist/steps/ComposableScreen/types.d.ts +21 -0
- package/dist/steps/ComposableScreen/types.d.ts.map +1 -1
- package/dist/steps/ComposableScreen/types.js +14 -0
- package/dist/steps/ComposableScreen/types.js.map +1 -1
- package/dist/types.d.ts +47 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -1
- package/dist/userProperties/reserved.d.ts +8 -5
- package/dist/userProperties/reserved.d.ts.map +1 -1
- package/dist/userProperties/reserved.js +9 -4
- package/dist/userProperties/reserved.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/OnboardingStudio.ts +19 -1
- package/src/OnboardingStudioClient.ts +84 -31
- package/src/__tests__/assignmentId.clear.test.ts +413 -0
- package/src/__tests__/assignmentId.client.test.ts +288 -0
- package/src/__tests__/assignmentId.test.ts +195 -0
- package/src/__tests__/onboardingMetadata.client.test.ts +76 -0
- package/src/assignmentId.ts +278 -0
- package/src/index.ts +9 -0
- package/src/paywalls/PaywallProvider.tsx +13 -0
- package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +51 -0
- package/src/paywalls/__tests__/devHook.test.ts +70 -0
- package/src/paywalls/__tests__/getPaywalls.test.ts +77 -2
- package/src/paywalls/__tests__/observer.test.ts +37 -0
- package/src/paywalls/__tests__/present.test.ts +14 -0
- package/src/paywalls/customScreens.ts +7 -0
- package/src/paywalls/devHook.ts +48 -0
- package/src/paywalls/observer.ts +22 -2
- package/src/paywalls/types.ts +22 -0
- package/src/products/adapters/__tests__/expoIap.contract.test.ts +305 -0
- package/src/products/adapters/expoIap.ts +171 -32
- package/src/steps/ComposableScreen/types.ts +21 -0
- package/src/types.ts +48 -0
- package/src/userProperties/__tests__/primitives.test.ts +1 -1
- package/src/userProperties/reserved.ts +9 -4
- package/src/version.ts +1 -1
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
ASSIGNMENT_ID_STORAGE_KEY,
|
|
4
|
+
createInstallationIdStore,
|
|
5
|
+
resolveAssignmentId,
|
|
6
|
+
type AssignmentIdStorage,
|
|
7
|
+
} from "../assignmentId";
|
|
8
|
+
import { ONBOARDING_CACHE_KEY_PREFIX, PAYWALLS_CACHE_KEY_PREFIX } from "../infra/queries/cacheKey";
|
|
9
|
+
import { USER_PROPERTIES_STORAGE_KEY } from "../userProperties/store";
|
|
10
|
+
|
|
11
|
+
const memoryStorage = (initial: Record<string, string> = {}) => {
|
|
12
|
+
const data = { ...initial };
|
|
13
|
+
const storage = {
|
|
14
|
+
getItem: vi.fn(async (k: string) => data[k] ?? null),
|
|
15
|
+
setItem: vi.fn(async (k: string, v: string) => {
|
|
16
|
+
data[k] = v;
|
|
17
|
+
}),
|
|
18
|
+
removeItem: vi.fn(async (k: string) => {
|
|
19
|
+
delete data[k];
|
|
20
|
+
}),
|
|
21
|
+
} satisfies AssignmentIdStorage;
|
|
22
|
+
return { data, storage };
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
let n = 0;
|
|
26
|
+
const counter = () => `generated-${++n}`;
|
|
27
|
+
|
|
28
|
+
describe("installation id store", () => {
|
|
29
|
+
it("generates once, persists it, and reads it back on the next launch", async () => {
|
|
30
|
+
const { data, storage } = memoryStorage();
|
|
31
|
+
const first = await createInstallationIdStore(storage, counter).get();
|
|
32
|
+
expect(first).toMatch(/^generated-/);
|
|
33
|
+
expect(data[ASSIGNMENT_ID_STORAGE_KEY]).toBe(first);
|
|
34
|
+
|
|
35
|
+
// A new process: a fresh store over the same disk.
|
|
36
|
+
const generate = vi.fn(counter);
|
|
37
|
+
const second = await createInstallationIdStore(storage, generate).get();
|
|
38
|
+
expect(second).toBe(first);
|
|
39
|
+
expect(generate).not.toHaveBeenCalled();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("concurrent first calls share one id and write it once", async () => {
|
|
43
|
+
const { storage } = memoryStorage();
|
|
44
|
+
const store = createInstallationIdStore(storage, counter);
|
|
45
|
+
const [a, b] = await Promise.all([store.get(), store.get()]);
|
|
46
|
+
expect(a).toBe(b);
|
|
47
|
+
expect(storage.setItem).toHaveBeenCalledTimes(1);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("a failed read is absent, and never overwrites what may be on disk", async () => {
|
|
51
|
+
const { storage } = memoryStorage({ [ASSIGNMENT_ID_STORAGE_KEY]: "kept" });
|
|
52
|
+
storage.getItem.mockRejectedValueOnce(new Error("disk"));
|
|
53
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
54
|
+
const store = createInstallationIdStore(storage, counter);
|
|
55
|
+
expect(await store.get()).toBeUndefined();
|
|
56
|
+
expect(storage.setItem).not.toHaveBeenCalled();
|
|
57
|
+
// Not memoized: the next request retries and finds the stored id.
|
|
58
|
+
expect(await store.get()).toBe("kept");
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("an id that could not be persisted is absent rather than sent", async () => {
|
|
62
|
+
const { storage } = memoryStorage();
|
|
63
|
+
storage.setItem.mockRejectedValueOnce(new Error("disk full"));
|
|
64
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
65
|
+
const store = createInstallationIdStore(storage, counter);
|
|
66
|
+
expect(await store.get()).toBeUndefined();
|
|
67
|
+
const retried = await store.get();
|
|
68
|
+
expect(retried).toMatch(/^generated-/);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("a blank stored value is replaced", async () => {
|
|
72
|
+
const { storage } = memoryStorage({ [ASSIGNMENT_ID_STORAGE_KEY]: " " });
|
|
73
|
+
expect(await createInstallationIdStore(storage, counter).get()).toMatch(/^generated-/);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("the default generator yields distinct uuid-shaped ids", async () => {
|
|
77
|
+
const a = await createInstallationIdStore(memoryStorage().storage).get();
|
|
78
|
+
const b = await createInstallationIdStore(memoryStorage().storage).get();
|
|
79
|
+
expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
|
80
|
+
expect(a).not.toBe(b);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("the default generator works without crypto.randomUUID (Hermes)", async () => {
|
|
84
|
+
vi.stubGlobal("crypto", undefined);
|
|
85
|
+
try {
|
|
86
|
+
const id = await createInstallationIdStore(memoryStorage().storage).get();
|
|
87
|
+
expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
|
88
|
+
} finally {
|
|
89
|
+
vi.unstubAllGlobals();
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("the key survives clearCache() and OnboardingStudio.reset()", () => {
|
|
94
|
+
expect(ASSIGNMENT_ID_STORAGE_KEY.startsWith(ONBOARDING_CACHE_KEY_PREFIX)).toBe(false);
|
|
95
|
+
expect(ASSIGNMENT_ID_STORAGE_KEY.startsWith(PAYWALLS_CACHE_KEY_PREFIX)).toBe(false);
|
|
96
|
+
expect(ASSIGNMENT_ID_STORAGE_KEY).not.toBe(USER_PROPERTIES_STORAGE_KEY);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("resolveAssignmentId", () => {
|
|
101
|
+
const installation = (id: string | undefined) => ({ token: () => 0, get: vi.fn(async () => id) });
|
|
102
|
+
|
|
103
|
+
it("no override: the installation id", async () => {
|
|
104
|
+
expect(await resolveAssignmentId(undefined, installation("inst"))).toBe("inst");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("no override and no installation id: absent", async () => {
|
|
108
|
+
expect(await resolveAssignmentId(undefined, installation(undefined))).toBeUndefined();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it("a host string wins, trimmed, and the installation id is never generated", async () => {
|
|
112
|
+
const inst = installation("inst");
|
|
113
|
+
expect(await resolveAssignmentId(" user-42 ", inst)).toBe("user-42");
|
|
114
|
+
expect(inst.get).not.toHaveBeenCalled();
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("a host getter is called on every resolution (sync or async)", async () => {
|
|
118
|
+
let current = "$RCAnonymousID:abc";
|
|
119
|
+
const getter = vi.fn(async () => current);
|
|
120
|
+
expect(await resolveAssignmentId(getter, installation("inst"))).toBe("$RCAnonymousID:abc");
|
|
121
|
+
current = "user-42";
|
|
122
|
+
expect(await resolveAssignmentId(getter, installation("inst"))).toBe("user-42");
|
|
123
|
+
expect(await resolveAssignmentId(() => "sync-id", installation("inst"))).toBe("sync-id");
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it.each([
|
|
127
|
+
["empty string", ""],
|
|
128
|
+
["blank", " "],
|
|
129
|
+
["null", null],
|
|
130
|
+
["undefined", undefined],
|
|
131
|
+
])("a host value that is %s falls through to the installation id", async (_l, value) => {
|
|
132
|
+
expect(await resolveAssignmentId(value as string | undefined, installation("inst"))).toBe("inst");
|
|
133
|
+
expect(await resolveAssignmentId(() => value, installation("inst"))).toBe("inst");
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("false opts out: absent, and the installation id is never read, created or written", async () => {
|
|
137
|
+
const inst = installation("inst");
|
|
138
|
+
expect(await resolveAssignmentId(false, inst)).toBeUndefined();
|
|
139
|
+
expect(await resolveAssignmentId(() => false, inst)).toBeUndefined();
|
|
140
|
+
expect(await resolveAssignmentId(async () => false as const, inst)).toBeUndefined();
|
|
141
|
+
expect(inst.get).not.toHaveBeenCalled();
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("a getter can opt out per request (e.g. until consent) and opt back in", async () => {
|
|
145
|
+
let consented = false;
|
|
146
|
+
const inst = installation("inst");
|
|
147
|
+
const getter = () => (consented ? undefined : false);
|
|
148
|
+
expect(await resolveAssignmentId(getter, inst)).toBeUndefined();
|
|
149
|
+
expect(inst.get).not.toHaveBeenCalled();
|
|
150
|
+
consented = true;
|
|
151
|
+
expect(await resolveAssignmentId(getter, inst)).toBe("inst");
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// Fail closed: a getter that cannot answer may be one that would have said
|
|
155
|
+
// `false` (no consent yet), so it must never fall back to the stored id.
|
|
156
|
+
it("a throwing or rejecting getter omits the id and never touches the store", async () => {
|
|
157
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
158
|
+
const inst = installation("inst");
|
|
159
|
+
const boom = () => {
|
|
160
|
+
throw new Error("Purchases not configured");
|
|
161
|
+
};
|
|
162
|
+
expect(await resolveAssignmentId(boom, inst)).toBeUndefined();
|
|
163
|
+
expect(await resolveAssignmentId(async () => boom(), inst)).toBeUndefined();
|
|
164
|
+
expect(inst.get).not.toHaveBeenCalled();
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("a getter that never settles is abandoned after the bound: omitted, store untouched", async () => {
|
|
168
|
+
vi.useFakeTimers();
|
|
169
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
170
|
+
try {
|
|
171
|
+
const inst = installation("inst");
|
|
172
|
+
const pending = resolveAssignmentId(() => new Promise<string>(() => {}), inst);
|
|
173
|
+
await vi.advanceTimersByTimeAsync(5000);
|
|
174
|
+
expect(await pending).toBeUndefined();
|
|
175
|
+
expect(inst.get).not.toHaveBeenCalled();
|
|
176
|
+
} finally {
|
|
177
|
+
vi.useRealTimers();
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("a getter that settles false after the bound (2.5s) still sends nothing and stores nothing", async () => {
|
|
182
|
+
vi.useFakeTimers();
|
|
183
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
184
|
+
try {
|
|
185
|
+
const inst = installation("inst");
|
|
186
|
+
const late = () => new Promise<false>((r) => setTimeout(() => r(false), 2500));
|
|
187
|
+
const pending = resolveAssignmentId(late, inst);
|
|
188
|
+
await vi.advanceTimersByTimeAsync(3000);
|
|
189
|
+
expect(await pending).toBeUndefined();
|
|
190
|
+
expect(inst.get).not.toHaveBeenCalled();
|
|
191
|
+
} finally {
|
|
192
|
+
vi.useRealTimers();
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { describe, it, expect, expectTypeOf, vi, beforeEach, afterEach } from "vitest";
|
|
2
|
+
|
|
3
|
+
vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
|
|
4
|
+
vi.mock("@react-native-async-storage/async-storage", () => ({
|
|
5
|
+
default: {
|
|
6
|
+
getItem: vi.fn(async () => null),
|
|
7
|
+
setItem: vi.fn(async () => {}),
|
|
8
|
+
removeItem: vi.fn(async () => {}),
|
|
9
|
+
getAllKeys: vi.fn(async () => []),
|
|
10
|
+
multiRemove: vi.fn(async () => {}),
|
|
11
|
+
},
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
import { OnboardingStudioClient } from "../OnboardingStudioClient";
|
|
15
|
+
import { MAIN_VARIANT_KEY, type OnboardingMetadata } from "../types";
|
|
16
|
+
|
|
17
|
+
const fakeResponse = (body: unknown) => ({
|
|
18
|
+
ok: true,
|
|
19
|
+
status: 200,
|
|
20
|
+
statusText: "OK",
|
|
21
|
+
json: async () => body,
|
|
22
|
+
headers: { get: () => null },
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const getMetadata = async (metadata: Record<string, unknown>) => {
|
|
26
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(fakeResponse({ metadata, steps: [] })));
|
|
27
|
+
const { data } = await new OnboardingStudioClient("proj-1", {}).getSteps({ locale: "en" });
|
|
28
|
+
return data.metadata;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
describe("OnboardingMetadata variant and deployment identity", () => {
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
vi.spyOn(console, "info").mockImplementation(() => {});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
afterEach(() => {
|
|
37
|
+
vi.unstubAllGlobals();
|
|
38
|
+
vi.restoreAllMocks();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("types variantKey and deploymentId as optional and nullable, with no experimentId", () => {
|
|
42
|
+
expectTypeOf<OnboardingMetadata["variantKey"]>().toEqualTypeOf<string | null | undefined>();
|
|
43
|
+
expectTypeOf<OnboardingMetadata["deploymentId"]>().toEqualTypeOf<number | null | undefined>();
|
|
44
|
+
expectTypeOf<OnboardingMetadata>().not.toHaveProperty("experimentId");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("surfaces variantKey and deploymentId from the payload through getSteps", async () => {
|
|
48
|
+
const metadata = await getMetadata({ id: "onb-1", variantKey: "b", deploymentId: 42 });
|
|
49
|
+
expect(metadata.variantKey).toBe("b");
|
|
50
|
+
expect(metadata.deploymentId).toBe(42);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("exports the reserved main variant key as a literal from the package index", () => {
|
|
54
|
+
expect(MAIN_VARIANT_KEY).toBe("main");
|
|
55
|
+
expectTypeOf(MAIN_VARIANT_KEY).toEqualTypeOf<"main">();
|
|
56
|
+
// Type-only: proves the public entry point re-exports it without loading it.
|
|
57
|
+
expectTypeOf<(typeof import("../index"))["MAIN_VARIANT_KEY"]>().toEqualTypeOf<"main">();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("passes the reserved main variantKey through unchanged", async () => {
|
|
61
|
+
const metadata = await getMetadata({ id: "onb-1", variantKey: MAIN_VARIANT_KEY, deploymentId: 7 });
|
|
62
|
+
expect(metadata.variantKey).toBe(MAIN_VARIANT_KEY);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("keeps null variantKey and deploymentId null", async () => {
|
|
66
|
+
const metadata = await getMetadata({ id: "onb-1", draft: true, variantKey: null, deploymentId: null });
|
|
67
|
+
expect(metadata.variantKey).toBeNull();
|
|
68
|
+
expect(metadata.deploymentId).toBeNull();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("reads the fields as undefined on a payload that does not carry them", async () => {
|
|
72
|
+
const metadata = await getMetadata({ id: "onb-1", audienceId: "7" });
|
|
73
|
+
expect(metadata.variantKey).toBeUndefined();
|
|
74
|
+
expect(metadata.deploymentId).toBeUndefined();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `assignmentId`: the stable per-person value every `getSteps` / `getPaywalls`
|
|
5
|
+
* request carries, so the server can put the same person in the same variant
|
|
6
|
+
* every time (it hashes this value with the id of the group being split).
|
|
7
|
+
* The SDK's only job is to send the same value every time for the same person.
|
|
8
|
+
*
|
|
9
|
+
* Resolution, per request:
|
|
10
|
+
* 1. the host's `assignmentId` option (a string, or a getter called on every
|
|
11
|
+
* request — e.g. `() => Purchases.getAppUserID()`),
|
|
12
|
+
* 2. else an installation id, generated once and persisted under
|
|
13
|
+
* `ASSIGNMENT_ID_STORAGE_KEY`,
|
|
14
|
+
* 3. else nothing: the `X-Assignment-Id` header is not sent rather than
|
|
15
|
+
* carrying an invented id, so the server can tell "no stable id" from "a
|
|
16
|
+
* fresh id it will never see again".
|
|
17
|
+
*
|
|
18
|
+
* `false` (as the option, or returned by the getter) OPTS OUT: nothing is sent
|
|
19
|
+
* and the installation id is never read, created or written — e.g. until the
|
|
20
|
+
* user consents. `null` / `""` are not an opt-out; they fall through to 2.
|
|
21
|
+
*
|
|
22
|
+
* A host value of `undefined`, `null` or `""` falls through to the installation
|
|
23
|
+
* id. A getter that throws, rejects, or does not settle within
|
|
24
|
+
* `HOST_ASSIGNMENT_ID_TIMEOUT_MS` FAILS CLOSED: the id is omitted for that
|
|
25
|
+
* request and the installation id is not read, created or written. A getter
|
|
26
|
+
* that cannot answer may be one that would have answered `false` (no consent
|
|
27
|
+
* yet), so it must never be overridden by the stored id.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** `false` opts out; `null` / `undefined` / `""` mean "no host value". */
|
|
31
|
+
export type AssignmentIdValue = string | false | null | undefined;
|
|
32
|
+
|
|
33
|
+
/** The `OnboardingStudioClientOptions.assignmentId` option. */
|
|
34
|
+
export type AssignmentIdOption =
|
|
35
|
+
| AssignmentIdValue
|
|
36
|
+
| (() => AssignmentIdValue | Promise<AssignmentIdValue>);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Deliberately NOT under the `rocapine-onboarding` / `rocapine-paywalls`
|
|
40
|
+
* prefixes `OnboardingStudioClient.clearCache` scans, and not the user
|
|
41
|
+
* property key `OnboardingStudio.reset()` removes: clearing a payload cache or
|
|
42
|
+
* logging out must not move the install to another variant.
|
|
43
|
+
*/
|
|
44
|
+
export const ASSIGNMENT_ID_STORAGE_KEY = "rocapine-assignment-id";
|
|
45
|
+
|
|
46
|
+
/** How long a host getter may take before the installation id is used instead. */
|
|
47
|
+
export const HOST_ASSIGNMENT_ID_TIMEOUT_MS = 2000;
|
|
48
|
+
|
|
49
|
+
export type AssignmentIdStorage = {
|
|
50
|
+
getItem: (key: string) => Promise<string | null>;
|
|
51
|
+
setItem: (key: string, value: string) => Promise<void>;
|
|
52
|
+
removeItem: (key: string) => Promise<void>;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const nonEmpty = (v: unknown): string | undefined =>
|
|
56
|
+
typeof v === "string" && v.trim() !== "" ? v.trim() : undefined;
|
|
57
|
+
|
|
58
|
+
/** RFC 4122 v4. `crypto.randomUUID` when present; Hermes may not have it. */
|
|
59
|
+
const generateUuidV4 = (): string => {
|
|
60
|
+
const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
|
61
|
+
if (typeof c?.randomUUID === "function") return c.randomUUID();
|
|
62
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
|
|
63
|
+
const r = (Math.random() * 16) | 0;
|
|
64
|
+
return (ch === "x" ? r : (r & 0x3) | 0x8).toString(16);
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Bound on how long a CALLER waits for each queued operation. The queue itself
|
|
70
|
+
* still waits for the real storage call, so ordering holds even when it hangs.
|
|
71
|
+
*/
|
|
72
|
+
export const STORAGE_OP_TIMEOUT_MS = HOST_ASSIGNMENT_ID_TIMEOUT_MS;
|
|
73
|
+
|
|
74
|
+
export type InstallationIdStore = {
|
|
75
|
+
/**
|
|
76
|
+
* The current clear() generation. Take it BEFORE any await that precedes
|
|
77
|
+
* `get(token)` (e.g. a host getter), so a `clear()` in between is seen.
|
|
78
|
+
*/
|
|
79
|
+
token: () => number;
|
|
80
|
+
/**
|
|
81
|
+
* The installation id, or `undefined`. With a `token` older than the last
|
|
82
|
+
* `clear()`, returns `undefined` without reading or writing storage.
|
|
83
|
+
*/
|
|
84
|
+
get: (token?: number) => Promise<string | undefined>;
|
|
85
|
+
/**
|
|
86
|
+
* Removes the stored id and forgets the in-memory one, so a later request
|
|
87
|
+
* mints a new id. Rejects if the removal fails or the caller's wait for it
|
|
88
|
+
* exceeds `STORAGE_OP_TIMEOUT_MS` (the removal itself still runs, in order).
|
|
89
|
+
*/
|
|
90
|
+
clear: () => Promise<void>;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* One in-flight resolution per store, so `getSteps` and `getPaywalls` fired
|
|
95
|
+
* together on a first launch share one generated id and write it once. A
|
|
96
|
+
* failure is not memoized: the next request retries.
|
|
97
|
+
*
|
|
98
|
+
* `clear()` must win against a load already in flight, or the id it removes
|
|
99
|
+
* comes back. Two mechanisms:
|
|
100
|
+
* - every storage operation runs on ONE queue, so a removal is ordered after
|
|
101
|
+
* any write already started, and a load started after `clear()` runs after
|
|
102
|
+
* the removal (and is therefore never deleted by it);
|
|
103
|
+
* - an `epoch` bumped by `clear()`: a load that began before it neither writes
|
|
104
|
+
* nor returns an id, so the request in flight sends nothing. Callers that
|
|
105
|
+
* await something first (`resolveAssignmentId` awaits the host getter) take
|
|
106
|
+
* the epoch as a `token()` up front and pass it to `get(token)`.
|
|
107
|
+
*
|
|
108
|
+
* The caller's wait on each queued operation is bounded by
|
|
109
|
+
* `STORAGE_OP_TIMEOUT_MS`, counted from when it was queued. On expiry the
|
|
110
|
+
* caller's promise rejects (`clear()` rejects; `get()` fails closed with
|
|
111
|
+
* `undefined`). A write or removal still holds the queue until the real call
|
|
112
|
+
* settles, so a removal can never overtake a write in flight; callers behind a
|
|
113
|
+
* hung write or removal fail closed at their own bound. A load abandoned BEFORE
|
|
114
|
+
* it issued `setItem` releases the queue at once, since it can no longer write:
|
|
115
|
+
* a hung read does not stall the rest of the process.
|
|
116
|
+
*
|
|
117
|
+
* A timed-out load is marked abandoned, and checks that right before minting
|
|
118
|
+
* and right before writing: a timed-out request never mints. (A write that had
|
|
119
|
+
* already started when the bound fired cannot be recalled; it lands, in order,
|
|
120
|
+
* ahead of any later removal.)
|
|
121
|
+
*/
|
|
122
|
+
export const createInstallationIdStore = (
|
|
123
|
+
storage: AssignmentIdStorage,
|
|
124
|
+
generate: () => string = generateUuidV4,
|
|
125
|
+
): InstallationIdStore => {
|
|
126
|
+
let pending: Promise<string | undefined> | null = null;
|
|
127
|
+
let epoch = 0;
|
|
128
|
+
let queue: Promise<unknown> = Promise.resolve();
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Runs `op` after every earlier operation has settled; the returned promise
|
|
132
|
+
* only bounds how long the caller waits. When the caller gives up,
|
|
133
|
+
* `onTimeout` runs, and if it returns `true` the queue is released at once:
|
|
134
|
+
* the op promises it will issue no further storage writes, so a later
|
|
135
|
+
* operation may safely start while it is still pending. Otherwise the queue
|
|
136
|
+
* keeps waiting for the real call (a write or removal must stay ordered).
|
|
137
|
+
*/
|
|
138
|
+
const enqueue = <T>(op: () => Promise<T>, onTimeout?: () => boolean): Promise<T> => {
|
|
139
|
+
const real = queue.then(op);
|
|
140
|
+
let release!: () => void;
|
|
141
|
+
const released = new Promise<void>((resolve) => {
|
|
142
|
+
release = resolve;
|
|
143
|
+
});
|
|
144
|
+
queue = Promise.race([real.catch(() => {}), released]);
|
|
145
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
146
|
+
return Promise.race([
|
|
147
|
+
real,
|
|
148
|
+
new Promise<never>((_, reject) => {
|
|
149
|
+
timer = setTimeout(() => {
|
|
150
|
+
if (onTimeout?.()) release();
|
|
151
|
+
reject(new Error(`[assignment-id] storage operation timed out after ${STORAGE_OP_TIMEOUT_MS}ms`));
|
|
152
|
+
}, STORAGE_OP_TIMEOUT_MS);
|
|
153
|
+
}),
|
|
154
|
+
]).finally(() => clearTimeout(timer));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** `writing` flips, synchronously, the moment the load issues `setItem`. */
|
|
158
|
+
type LoadState = { abandoned: boolean; writing: boolean };
|
|
159
|
+
|
|
160
|
+
const load = async (startedAt: number, state: LoadState): Promise<string | undefined> => {
|
|
161
|
+
let stored: string | null;
|
|
162
|
+
try {
|
|
163
|
+
stored = await storage.getItem(ASSIGNMENT_ID_STORAGE_KEY);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
// An unreadable key may still hold an id: generating now could overwrite it.
|
|
166
|
+
console.warn("[assignment-id] Failed to read the installation id; omitting it:", error);
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
if (epoch !== startedAt) return undefined; // cleared meanwhile: do not mint
|
|
170
|
+
const existing = nonEmpty(stored);
|
|
171
|
+
if (existing) return existing;
|
|
172
|
+
// The caller timed out: never mint (and so never write). Nothing async lies
|
|
173
|
+
// between here and `setItem`, so this is also the last check before it.
|
|
174
|
+
if (state.abandoned) return undefined;
|
|
175
|
+
const fresh = generate();
|
|
176
|
+
state.writing = true; // same tick as the check above and the call below
|
|
177
|
+
try {
|
|
178
|
+
await storage.setItem(ASSIGNMENT_ID_STORAGE_KEY, fresh);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
// Not persisted means not stable: the next launch would send another one.
|
|
181
|
+
console.warn("[assignment-id] Failed to persist the installation id; omitting it:", error);
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
return fresh;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
token: () => epoch,
|
|
189
|
+
get: (token) => {
|
|
190
|
+
// Cleared since the caller started: no load, no write.
|
|
191
|
+
if (token !== undefined && token !== epoch) return Promise.resolve(undefined);
|
|
192
|
+
if (!pending) {
|
|
193
|
+
const startedAt = epoch;
|
|
194
|
+
const settle = (id: string | undefined) => {
|
|
195
|
+
// Cleared while loading: `clear()` already dropped this memo.
|
|
196
|
+
if (epoch !== startedAt) return undefined;
|
|
197
|
+
if (!id) pending = null;
|
|
198
|
+
return id;
|
|
199
|
+
};
|
|
200
|
+
const state: LoadState = { abandoned: false, writing: false };
|
|
201
|
+
pending = enqueue(
|
|
202
|
+
() => load(startedAt, state),
|
|
203
|
+
() => {
|
|
204
|
+
state.abandoned = true;
|
|
205
|
+
// Not yet writing: the abandoned load will never write now, so the
|
|
206
|
+
// queue need not wait for its read. A write in flight still holds it.
|
|
207
|
+
return !state.writing;
|
|
208
|
+
},
|
|
209
|
+
).then(settle, (error) => {
|
|
210
|
+
console.warn("[assignment-id] Loading the installation id failed; omitting it:", error);
|
|
211
|
+
return settle(undefined);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return pending;
|
|
215
|
+
},
|
|
216
|
+
clear: () => {
|
|
217
|
+
epoch++;
|
|
218
|
+
pending = null;
|
|
219
|
+
return enqueue(() => storage.removeItem(ASSIGNMENT_ID_STORAGE_KEY));
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Calls a host getter; never throws, never waits past the bound. Returns
|
|
226
|
+
* `false` (omit, store untouched) for an explicit opt-out AND for a getter that
|
|
227
|
+
* throws or times out; `undefined` only for "no host value".
|
|
228
|
+
*/
|
|
229
|
+
const readHostValue = async (option: AssignmentIdOption): Promise<string | false | undefined> => {
|
|
230
|
+
if (option === false) return false;
|
|
231
|
+
if (typeof option !== "function") return nonEmpty(option);
|
|
232
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
233
|
+
try {
|
|
234
|
+
const value = await Promise.race([
|
|
235
|
+
Promise.resolve().then(option),
|
|
236
|
+
new Promise<false>((resolve) => {
|
|
237
|
+
timer = setTimeout(() => {
|
|
238
|
+
console.warn(
|
|
239
|
+
`[assignment-id] The assignmentId getter did not settle within ${HOST_ASSIGNMENT_ID_TIMEOUT_MS}ms; ` +
|
|
240
|
+
"sending no assignmentId for this request."
|
|
241
|
+
);
|
|
242
|
+
resolve(false);
|
|
243
|
+
}, HOST_ASSIGNMENT_ID_TIMEOUT_MS);
|
|
244
|
+
}),
|
|
245
|
+
]);
|
|
246
|
+
return value === false ? false : nonEmpty(value);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
console.warn("[assignment-id] The assignmentId getter threw; sending no assignmentId for this request:", error);
|
|
249
|
+
return false;
|
|
250
|
+
} finally {
|
|
251
|
+
clearTimeout(timer);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Opt-out, throw or timeout → `undefined` (store untouched); host value →
|
|
257
|
+
* installation id → `undefined`. Never throws.
|
|
258
|
+
*/
|
|
259
|
+
export const resolveAssignmentId = async (
|
|
260
|
+
option: AssignmentIdOption,
|
|
261
|
+
installation: Pick<InstallationIdStore, "get" | "token">,
|
|
262
|
+
): Promise<string | undefined> => {
|
|
263
|
+
// Before the host getter's await: a clear() while it runs must be seen.
|
|
264
|
+
const token = installation.token();
|
|
265
|
+
const host = await readHostValue(option);
|
|
266
|
+
if (host === false) return undefined;
|
|
267
|
+
return host ?? installation.get(token);
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
let installationIdStore = createInstallationIdStore(AsyncStorage);
|
|
271
|
+
|
|
272
|
+
/** The process-wide installation id store: shared by every client, like the disk it reads. */
|
|
273
|
+
export const getInstallationIdStore = (): InstallationIdStore => installationIdStore;
|
|
274
|
+
|
|
275
|
+
/** Test-only: forget the in-memory id, as a new process would. */
|
|
276
|
+
export const __resetInstallationIdForTests = (): void => {
|
|
277
|
+
installationIdStore = createInstallationIdStore(AsyncStorage);
|
|
278
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Core client and types
|
|
2
2
|
export { OnboardingStudioClient } from "./OnboardingStudioClient";
|
|
3
3
|
export * from "./types";
|
|
4
|
+
export type { AssignmentIdOption, AssignmentIdValue } from "./assignmentId";
|
|
4
5
|
export * from "./onboarding-example";
|
|
5
6
|
// Cache key helper (advanced/host use — e.g. to read/clear the persisted key)
|
|
6
7
|
export {
|
|
@@ -97,6 +98,14 @@ export type {
|
|
|
97
98
|
export { resolveRegisterDecision, shouldRunFeature } from "./paywalls/register";
|
|
98
99
|
export type { RegisterDecision, RegisterFeature, RegisterResult } from "./paywalls/register";
|
|
99
100
|
export { DEFAULT_REGISTER_TIMEOUT_MS } from "./paywalls/PaywallProvider";
|
|
101
|
+
/** devtools-only */
|
|
102
|
+
export {
|
|
103
|
+
setPaywallDevHook,
|
|
104
|
+
notifyPaywallShown,
|
|
105
|
+
hasPaywallDevHook,
|
|
106
|
+
} from "./paywalls/devHook";
|
|
107
|
+
export type { PaywallShownInfo, PaywallDevHook } from "./paywalls/devHook";
|
|
108
|
+
export { SDK_VERSION } from "./version";
|
|
100
109
|
// A step that IS a paywall: `payload.moment` names a moment, and the audience
|
|
101
110
|
// waterfall behind it picks which paywall renders.
|
|
102
111
|
export type { PaywallStepType } from "./steps/Paywall/types";
|
|
@@ -199,6 +199,13 @@ export type PaywallContextValue = {
|
|
|
199
199
|
* `present()` reports itself; a paywall HOST never calls this for it.
|
|
200
200
|
*/
|
|
201
201
|
observePresentation: (paywall: PaywallPresentationSource) => PaywallPresentation;
|
|
202
|
+
/**
|
|
203
|
+
* The studio client this provider fetches with, or null with no provider.
|
|
204
|
+
* Read by the paywall renderers only to describe a shown paywall to a
|
|
205
|
+
* registered dev hook (`notifyPaywallShown`): project id, functions URL, app
|
|
206
|
+
* version.
|
|
207
|
+
*/
|
|
208
|
+
client: OnboardingStudioClient | null;
|
|
202
209
|
};
|
|
203
210
|
|
|
204
211
|
const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
|
|
@@ -227,6 +234,7 @@ const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
|
|
|
227
234
|
customActions: EMPTY_CUSTOM_ACTIONS,
|
|
228
235
|
customScreens: EMPTY_CUSTOM_SCREENS,
|
|
229
236
|
observePresentation: () => NOOP_PAYWALL_PRESENTATION,
|
|
237
|
+
client: null,
|
|
230
238
|
};
|
|
231
239
|
|
|
232
240
|
/**
|
|
@@ -261,6 +269,7 @@ export const usePaywallHost = (): Pick<
|
|
|
261
269
|
| "customActions"
|
|
262
270
|
| "customScreens"
|
|
263
271
|
| "observePresentation"
|
|
272
|
+
| "client"
|
|
264
273
|
> => {
|
|
265
274
|
const {
|
|
266
275
|
activePaywall,
|
|
@@ -269,6 +278,7 @@ export const usePaywallHost = (): Pick<
|
|
|
269
278
|
customActions,
|
|
270
279
|
customScreens,
|
|
271
280
|
observePresentation,
|
|
281
|
+
client,
|
|
272
282
|
} = useContext(PaywallContext);
|
|
273
283
|
return {
|
|
274
284
|
activePaywall,
|
|
@@ -277,6 +287,7 @@ export const usePaywallHost = (): Pick<
|
|
|
277
287
|
customActions,
|
|
278
288
|
customScreens,
|
|
279
289
|
observePresentation,
|
|
290
|
+
client,
|
|
280
291
|
};
|
|
281
292
|
};
|
|
282
293
|
|
|
@@ -957,6 +968,7 @@ const PaywallProviderInner = ({
|
|
|
957
968
|
customActions,
|
|
958
969
|
customScreens,
|
|
959
970
|
observePresentation,
|
|
971
|
+
client,
|
|
960
972
|
}),
|
|
961
973
|
[
|
|
962
974
|
present,
|
|
@@ -971,6 +983,7 @@ const PaywallProviderInner = ({
|
|
|
971
983
|
customActions,
|
|
972
984
|
customScreens,
|
|
973
985
|
observePresentation,
|
|
986
|
+
client,
|
|
974
987
|
]
|
|
975
988
|
);
|
|
976
989
|
|