@rocapine/react-native-onboarding 1.76.0 → 1.78.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.
Files changed (71) hide show
  1. package/README.md +49 -5
  2. package/dist/OnboardingStudio.d.ts +14 -1
  3. package/dist/OnboardingStudio.d.ts.map +1 -1
  4. package/dist/OnboardingStudio.js +5 -1
  5. package/dist/OnboardingStudio.js.map +1 -1
  6. package/dist/OnboardingStudioClient.d.ts +47 -0
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +117 -33
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/assignmentId.d.ts +107 -0
  11. package/dist/assignmentId.d.ts.map +1 -0
  12. package/dist/assignmentId.js +215 -0
  13. package/dist/assignmentId.js.map +1 -0
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/paywalls/customScreens.d.ts +7 -0
  18. package/dist/paywalls/customScreens.d.ts.map +1 -1
  19. package/dist/paywalls/observer.d.ts +2 -0
  20. package/dist/paywalls/observer.d.ts.map +1 -1
  21. package/dist/paywalls/observer.js +21 -9
  22. package/dist/paywalls/observer.js.map +1 -1
  23. package/dist/paywalls/types.d.ts +22 -0
  24. package/dist/paywalls/types.d.ts.map +1 -1
  25. package/dist/products/adapters/expoIap.d.ts +34 -13
  26. package/dist/products/adapters/expoIap.d.ts.map +1 -1
  27. package/dist/products/adapters/expoIap.js +136 -21
  28. package/dist/products/adapters/expoIap.js.map +1 -1
  29. package/dist/requestIdentity.d.ts +41 -0
  30. package/dist/requestIdentity.d.ts.map +1 -0
  31. package/dist/requestIdentity.js +70 -0
  32. package/dist/requestIdentity.js.map +1 -0
  33. package/dist/types.d.ts +64 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js +6 -0
  36. package/dist/types.js.map +1 -1
  37. package/dist/userProperties/reserved.d.ts +17 -15
  38. package/dist/userProperties/reserved.d.ts.map +1 -1
  39. package/dist/userProperties/reserved.js +20 -14
  40. package/dist/userProperties/reserved.js.map +1 -1
  41. package/dist/version.d.ts +10 -0
  42. package/dist/version.d.ts.map +1 -0
  43. package/dist/version.js +13 -0
  44. package/dist/version.js.map +1 -0
  45. package/package.json +5 -1
  46. package/src/OnboardingStudio.ts +19 -1
  47. package/src/OnboardingStudioClient.ts +123 -47
  48. package/src/__tests__/assignmentId.clear.test.ts +413 -0
  49. package/src/__tests__/assignmentId.client.test.ts +288 -0
  50. package/src/__tests__/assignmentId.test.ts +195 -0
  51. package/src/__tests__/getOnboarding.query.test.ts +30 -0
  52. package/src/__tests__/onboardingMetadata.client.test.ts +76 -0
  53. package/src/__tests__/requestIdentity.client.test.ts +115 -0
  54. package/src/__tests__/requestIdentity.test.ts +112 -0
  55. package/src/assignmentId.ts +278 -0
  56. package/src/index.ts +1 -0
  57. package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +51 -0
  58. package/src/paywalls/__tests__/getPaywalls.test.ts +107 -2
  59. package/src/paywalls/__tests__/observer.test.ts +37 -0
  60. package/src/paywalls/__tests__/present.test.ts +14 -0
  61. package/src/paywalls/customScreens.ts +7 -0
  62. package/src/paywalls/observer.ts +22 -2
  63. package/src/paywalls/types.ts +22 -0
  64. package/src/products/adapters/__tests__/expoIap.contract.test.ts +305 -0
  65. package/src/products/adapters/expoIap.ts +171 -32
  66. package/src/requestIdentity.ts +101 -0
  67. package/src/types.ts +65 -0
  68. package/src/userProperties/__tests__/effectiveParams.test.ts +2 -2
  69. package/src/userProperties/__tests__/primitives.test.ts +1 -1
  70. package/src/userProperties/reserved.ts +20 -14
  71. package/src/version.ts +9 -0
@@ -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
+ });
@@ -209,3 +209,33 @@ describe("OnboardingStudioClient.clearCache", () => {
209
209
  warn.mockRestore();
210
210
  });
211
211
  });
212
+
213
+ describe("cache key and request identity", () => {
214
+ beforeEach(() => {
215
+ getItem.mockReset();
216
+ setItem.mockReset();
217
+ getItem.mockResolvedValue(null);
218
+ setItem.mockResolvedValue(undefined);
219
+ });
220
+
221
+ // The SDK's own identity is sent on the request but must NOT enter the cache
222
+ // key: a key that changed with every app update would leave a returning user
223
+ // who is offline right after updating with no cached onboarding, and would stop a
224
+ // custom `cacheKey` from pinning content across updates.
225
+ const withIdentity = (client: any, identity: Record<string, string>) => {
226
+ client.identityParams = () => identity;
227
+ return client;
228
+ };
229
+
230
+ it("same cache key across builds when only the SDK-derived identity changes", async () => {
231
+ await run(withIdentity(makeClient({ isSandbox: false, onboardingId: "real", data: realOnboarding }), { appVersion: "2.3.0", build: "45", sdkVersion: "1.77.0", environment: "production" }));
232
+ await run(withIdentity(makeClient({ isSandbox: false, onboardingId: "real", data: realOnboarding }), { appVersion: "2.4.0", build: "46", sdkVersion: "1.78.0", environment: "production" }));
233
+ const keys = setItem.mock.calls.map(([key]) => key);
234
+ expect(keys).toEqual([CACHE_KEY, CACHE_KEY]);
235
+ });
236
+
237
+ it("custom cacheKey is unaffected by identity", async () => {
238
+ await run(withIdentity(makeClient({ isSandbox: false, onboardingId: "real", data: realOnboarding, cacheKey: CUSTOM_KEY }), { appVersion: "2.3.0", build: "45", sdkVersion: "1.77.0", environment: "production" }));
239
+ expect(setItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY, JSON.stringify(realOnboarding));
240
+ });
241
+ });
@@ -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,115 @@
1
+ import { describe, it, expect, 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
+ // The client reads expo-application through `readNativeAppInfo`; replace only
14
+ // that export so each test chooses what the device reports.
15
+ const native = vi.hoisted(() => ({ info: {} as { appVersion?: string; build?: string } }));
16
+ vi.mock("../requestIdentity", async (importOriginal) => ({
17
+ ...(await importOriginal<typeof import("../requestIdentity")>()),
18
+ readNativeAppInfo: () => native.info,
19
+ }));
20
+
21
+ import { OnboardingStudioClient } from "../OnboardingStudioClient";
22
+ import { SDK_VERSION } from "../version";
23
+
24
+ const fakeResponse = (body: unknown) => ({
25
+ ok: true,
26
+ status: 200,
27
+ statusText: "OK",
28
+ json: async () => body,
29
+ headers: { get: () => null },
30
+ });
31
+
32
+ const fetches = {
33
+ getSteps: (c: OnboardingStudioClient, params?: Record<string, string>) =>
34
+ c.getSteps({ locale: "en" }, params),
35
+ getPaywalls: (c: OnboardingStudioClient, params?: Record<string, string>) =>
36
+ c.getPaywalls({ locale: "en" }, params),
37
+ };
38
+
39
+ describe.each(Object.entries(fetches))("%s request identity", (_name, fetchWith) => {
40
+ let fetchMock: ReturnType<typeof vi.fn>;
41
+
42
+ beforeEach(() => {
43
+ native.info = {};
44
+ fetchMock = vi.fn().mockResolvedValue(fakeResponse({ metadata: {}, steps: [], paywalls: {} }));
45
+ vi.stubGlobal("fetch", fetchMock);
46
+ vi.spyOn(console, "info").mockImplementation(() => {});
47
+ });
48
+
49
+ afterEach(() => {
50
+ vi.unstubAllGlobals();
51
+ vi.restoreAllMocks();
52
+ });
53
+
54
+ const sent = () => new URL(fetchMock.mock.calls[0][0] as string).searchParams;
55
+
56
+ it("sends appVersion and build from expo-application, plus sdkVersion and environment", async () => {
57
+ native.info = { appVersion: "2.3.0", build: "45" };
58
+ await fetchWith(new OnboardingStudioClient("proj-1", {}));
59
+ expect(sent().get("appVersion")).toBe("2.3.0");
60
+ expect(sent().get("build")).toBe("45");
61
+ expect(sent().get("sdkVersion")).toBe(SDK_VERSION);
62
+ expect(sent().get("environment")).toBe("production");
63
+ });
64
+
65
+ it("host appVersion and build win over expo-application", async () => {
66
+ native.info = { appVersion: "2.3.0", build: "45" };
67
+ await fetchWith(new OnboardingStudioClient("proj-1", { appVersion: "3.0.0", build: "300" }));
68
+ expect(sent().get("appVersion")).toBe("3.0.0");
69
+ expect(sent().get("build")).toBe("300");
70
+ });
71
+
72
+ it("omits appVersion and build when neither source has them", async () => {
73
+ await fetchWith(new OnboardingStudioClient("proj-1", {}));
74
+ expect(sent().has("appVersion")).toBe(false);
75
+ expect(sent().has("build")).toBe(false);
76
+ expect(sent().get("sdkVersion")).toBe(SDK_VERSION);
77
+ });
78
+
79
+ it("environment: sandbox in sandbox mode, normalized when the host sets it", async () => {
80
+ await fetchWith(new OnboardingStudioClient("proj-1", { isSandbox: true }));
81
+ expect(sent().get("environment")).toBe("sandbox");
82
+ fetchMock.mockClear();
83
+ await fetchWith(new OnboardingStudioClient("proj-1", { environment: "Staging Env!" }));
84
+ expect(sent().get("environment")).toBe("stagingenv");
85
+ });
86
+
87
+ it("SDK-owned keys replace a same-named user param (the server reads the first occurrence)", async () => {
88
+ native.info = { appVersion: "2.3.0", build: "45" };
89
+ await fetchWith(new OnboardingStudioClient("proj-1", {}), {
90
+ build: "from-user",
91
+ environment: "from-user",
92
+ sdkVersion: "from-user",
93
+ projectId: "other",
94
+ plan: "pro",
95
+ });
96
+ expect(sent().getAll("build")).toEqual(["45"]);
97
+ expect(sent().getAll("environment")).toEqual(["production"]);
98
+ expect(sent().getAll("sdkVersion")).toEqual([SDK_VERSION]);
99
+ expect(sent().getAll("projectId")).toEqual(["proj-1"]);
100
+ expect(sent().get("plan")).toBe("pro");
101
+ });
102
+
103
+ it("a user appVersion or build never reaches the wire, even when the SDK has none to send", async () => {
104
+ // A property persisted before these names were reserved is re-read from
105
+ // disk without a reserved-key check, so it can still arrive here.
106
+ await fetchWith(new OnboardingStudioClient("proj-1", {}), {
107
+ appVersion: "from-user",
108
+ build: "from-user",
109
+ plan: "pro",
110
+ });
111
+ expect(sent().has("appVersion")).toBe(false);
112
+ expect(sent().has("build")).toBe(false);
113
+ expect(sent().get("plan")).toBe("pro");
114
+ });
115
+ });
@@ -0,0 +1,112 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import {
5
+ defaultEnvironment,
6
+ normalizeEnvironment,
7
+ readNativeAppInfo,
8
+ resolveRequestIdentity,
9
+ } from "../requestIdentity";
10
+ import { SDK_VERSION } from "../version";
11
+
12
+ describe("SDK_VERSION", () => {
13
+ it("equals the package version", () => {
14
+ const pkg = JSON.parse(readFileSync(join(__dirname, "../..", "package.json"), "utf8"));
15
+ expect(SDK_VERSION).toBe(pkg.version);
16
+ });
17
+ });
18
+
19
+ describe("readNativeAppInfo", () => {
20
+ it("reads version and build from expo-application", () => {
21
+ expect(
22
+ readNativeAppInfo(() => ({ nativeApplicationVersion: "2.3.0", nativeBuildVersion: "45" })),
23
+ ).toEqual({ appVersion: "2.3.0", build: "45" });
24
+ });
25
+
26
+ it("is empty when expo-application is not installed", () => {
27
+ expect(readNativeAppInfo(() => null)).toEqual({});
28
+ });
29
+
30
+ it("is empty, without throwing, when loading expo-application throws", () => {
31
+ expect(
32
+ readNativeAppInfo(() => {
33
+ throw new Error("Cannot find module 'expo-application'");
34
+ }),
35
+ ).toEqual({});
36
+ });
37
+
38
+ it("omits null and blank values (web, or an unlinked native module)", () => {
39
+ expect(
40
+ readNativeAppInfo(() => ({ nativeApplicationVersion: null, nativeBuildVersion: " " })),
41
+ ).toEqual({ appVersion: undefined, build: undefined });
42
+ });
43
+
44
+ it("the default loader never throws", () => {
45
+ expect(() => readNativeAppInfo()).not.toThrow();
46
+ });
47
+ });
48
+
49
+ describe("defaultEnvironment", () => {
50
+ it("is sandbox in sandbox mode, whatever __DEV__ says", () => {
51
+ expect(defaultEnvironment(true, true)).toBe("sandbox");
52
+ expect(defaultEnvironment(true, false)).toBe("sandbox");
53
+ });
54
+ it("is development under __DEV__, production otherwise", () => {
55
+ expect(defaultEnvironment(false, true)).toBe("development");
56
+ expect(defaultEnvironment(undefined, false)).toBe("production");
57
+ });
58
+ it("reads __DEV__ when not told, and treats an undefined __DEV__ as production", () => {
59
+ expect(defaultEnvironment(undefined)).toBe("production");
60
+ });
61
+ });
62
+
63
+ describe("normalizeEnvironment", () => {
64
+ it("lower-cases and drops characters outside [a-z0-9_-]", () => {
65
+ expect(normalizeEnvironment("Staging Env!", "production")).toBe("stagingenv");
66
+ expect(normalizeEnvironment("qa_2-eu", "production")).toBe("qa_2-eu");
67
+ });
68
+ it("caps at 32 characters", () => {
69
+ expect(normalizeEnvironment("a".repeat(200), "production")).toBe("a".repeat(32));
70
+ });
71
+ it("falls back when nothing survives or the value is not a string", () => {
72
+ expect(normalizeEnvironment(" ", "production")).toBe("production");
73
+ expect(normalizeEnvironment("!!!", "sandbox")).toBe("sandbox");
74
+ expect(normalizeEnvironment(undefined, "development")).toBe("development");
75
+ expect(normalizeEnvironment(42, "production")).toBe("production");
76
+ });
77
+ });
78
+
79
+ describe("resolveRequestIdentity", () => {
80
+ const native = { appVersion: "2.3.0", build: "45" };
81
+
82
+ it("host values win over expo-application", () => {
83
+ expect(resolveRequestIdentity({ appVersion: "9.9.9", build: "1" }, native, false)).toEqual({
84
+ appVersion: "9.9.9",
85
+ build: "1",
86
+ sdkVersion: SDK_VERSION,
87
+ environment: "production",
88
+ });
89
+ });
90
+
91
+ it("expo-application fills what the host left out, and a blank host value counts as left out", () => {
92
+ expect(resolveRequestIdentity({ appVersion: " " }, native, false)).toEqual({
93
+ appVersion: "2.3.0",
94
+ build: "45",
95
+ sdkVersion: SDK_VERSION,
96
+ environment: "production",
97
+ });
98
+ });
99
+
100
+ it("omits appVersion and build when neither source has them", () => {
101
+ expect(resolveRequestIdentity({}, {}, false)).toEqual({
102
+ sdkVersion: SDK_VERSION,
103
+ environment: "production",
104
+ });
105
+ });
106
+
107
+ it("normalizes a host environment and defaults from the mode", () => {
108
+ expect(resolveRequestIdentity({ environment: "Staging" }, {}, false).environment).toBe("staging");
109
+ expect(resolveRequestIdentity({ isSandbox: true }, {}, false).environment).toBe("sandbox");
110
+ expect(resolveRequestIdentity({}, {}, true).environment).toBe("development");
111
+ });
112
+ });