@rocapine/react-native-onboarding 1.72.0 → 1.74.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 (117) hide show
  1. package/README.md +136 -3
  2. package/dist/OnboardingStudio.d.ts +82 -0
  3. package/dist/OnboardingStudio.d.ts.map +1 -0
  4. package/dist/OnboardingStudio.js +91 -0
  5. package/dist/OnboardingStudio.js.map +1 -0
  6. package/dist/OnboardingStudioClient.d.ts +14 -5
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +24 -9
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +43 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/infra/provider/OnboardingProvider.d.ts +11 -2
  15. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  16. package/dist/infra/provider/OnboardingProvider.js +26 -2
  17. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  18. package/dist/infra/queries/cacheKey.d.ts +41 -3
  19. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  20. package/dist/infra/queries/cacheKey.js +44 -8
  21. package/dist/infra/queries/cacheKey.js.map +1 -1
  22. package/dist/infra/queries/getOnboarding.query.d.ts.map +1 -1
  23. package/dist/infra/queries/getOnboarding.query.js +6 -1
  24. package/dist/infra/queries/getOnboarding.query.js.map +1 -1
  25. package/dist/paywalls/PaywallProvider.d.ts +95 -5
  26. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  27. package/dist/paywalls/PaywallProvider.js +121 -9
  28. package/dist/paywalls/PaywallProvider.js.map +1 -1
  29. package/dist/paywalls/catalogSettleWaiter.d.ts +31 -0
  30. package/dist/paywalls/catalogSettleWaiter.d.ts.map +1 -0
  31. package/dist/paywalls/catalogSettleWaiter.js +58 -0
  32. package/dist/paywalls/catalogSettleWaiter.js.map +1 -0
  33. package/dist/paywalls/customScreens.d.ts +83 -0
  34. package/dist/paywalls/customScreens.d.ts.map +1 -0
  35. package/dist/paywalls/customScreens.js +3 -0
  36. package/dist/paywalls/customScreens.js.map +1 -0
  37. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -1
  38. package/dist/paywalls/getPaywalls.query.js +6 -1
  39. package/dist/paywalls/getPaywalls.query.js.map +1 -1
  40. package/dist/paywalls/register.d.ts +105 -0
  41. package/dist/paywalls/register.d.ts.map +1 -0
  42. package/dist/paywalls/register.js +112 -0
  43. package/dist/paywalls/register.js.map +1 -0
  44. package/dist/paywalls/usePaywall.d.ts +43 -0
  45. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  46. package/dist/paywalls/usePaywall.js +11 -2
  47. package/dist/paywalls/usePaywall.js.map +1 -1
  48. package/dist/steps/Paywall/types.d.ts +63 -0
  49. package/dist/steps/Paywall/types.d.ts.map +1 -0
  50. package/dist/steps/Paywall/types.js +29 -0
  51. package/dist/steps/Paywall/types.js.map +1 -0
  52. package/dist/steps/types.d.ts +2 -1
  53. package/dist/steps/types.d.ts.map +1 -1
  54. package/dist/userProperties/applyPatch.d.ts +18 -0
  55. package/dist/userProperties/applyPatch.d.ts.map +1 -0
  56. package/dist/userProperties/applyPatch.js +57 -0
  57. package/dist/userProperties/applyPatch.js.map +1 -0
  58. package/dist/userProperties/effectiveParams.d.ts +29 -0
  59. package/dist/userProperties/effectiveParams.d.ts.map +1 -0
  60. package/dist/userProperties/effectiveParams.js +56 -0
  61. package/dist/userProperties/effectiveParams.js.map +1 -0
  62. package/dist/userProperties/index.d.ts +9 -0
  63. package/dist/userProperties/index.d.ts.map +1 -0
  64. package/dist/userProperties/index.js +21 -0
  65. package/dist/userProperties/index.js.map +1 -0
  66. package/dist/userProperties/reserved.d.ts +33 -0
  67. package/dist/userProperties/reserved.d.ts.map +1 -0
  68. package/dist/userProperties/reserved.js +45 -0
  69. package/dist/userProperties/reserved.js.map +1 -0
  70. package/dist/userProperties/serialize.d.ts +38 -0
  71. package/dist/userProperties/serialize.d.ts.map +1 -0
  72. package/dist/userProperties/serialize.js +67 -0
  73. package/dist/userProperties/serialize.js.map +1 -0
  74. package/dist/userProperties/store.d.ts +63 -0
  75. package/dist/userProperties/store.d.ts.map +1 -0
  76. package/dist/userProperties/store.js +153 -0
  77. package/dist/userProperties/store.js.map +1 -0
  78. package/dist/userProperties/types.d.ts +21 -0
  79. package/dist/userProperties/types.d.ts.map +1 -0
  80. package/dist/userProperties/types.js +3 -0
  81. package/dist/userProperties/types.js.map +1 -0
  82. package/dist/userProperties/useUserProperties.d.ts +20 -0
  83. package/dist/userProperties/useUserProperties.d.ts.map +1 -0
  84. package/dist/userProperties/useUserProperties.js +30 -0
  85. package/dist/userProperties/useUserProperties.js.map +1 -0
  86. package/package.json +1 -1
  87. package/src/OnboardingStudio.ts +147 -0
  88. package/src/OnboardingStudioClient.ts +27 -11
  89. package/src/__tests__/OnboardingStudio.test.ts +208 -0
  90. package/src/__tests__/cacheKey.test.ts +71 -0
  91. package/src/__tests__/getOnboarding.query.test.ts +47 -8
  92. package/src/index.ts +51 -0
  93. package/src/infra/provider/OnboardingProvider.tsx +45 -4
  94. package/src/infra/queries/cacheKey.ts +54 -9
  95. package/src/infra/queries/getOnboarding.query.ts +9 -1
  96. package/src/paywalls/PaywallProvider.tsx +226 -9
  97. package/src/paywalls/__tests__/catalogSettleWaiter.test.ts +134 -0
  98. package/src/paywalls/__tests__/getPaywalls.test.ts +29 -11
  99. package/src/paywalls/__tests__/register.test.ts +266 -0
  100. package/src/paywalls/catalogSettleWaiter.ts +72 -0
  101. package/src/paywalls/customScreens.ts +82 -0
  102. package/src/paywalls/getPaywalls.query.ts +9 -1
  103. package/src/paywalls/register.ts +169 -0
  104. package/src/paywalls/usePaywall.ts +63 -3
  105. package/src/steps/Paywall/types.ts +29 -0
  106. package/src/steps/types.ts +2 -0
  107. package/src/userProperties/__tests__/effectiveParams.test.ts +51 -0
  108. package/src/userProperties/__tests__/primitives.test.ts +96 -0
  109. package/src/userProperties/__tests__/store.test.ts +181 -0
  110. package/src/userProperties/applyPatch.ts +68 -0
  111. package/src/userProperties/effectiveParams.ts +60 -0
  112. package/src/userProperties/index.ts +11 -0
  113. package/src/userProperties/reserved.ts +44 -0
  114. package/src/userProperties/serialize.ts +61 -0
  115. package/src/userProperties/store.ts +177 -0
  116. package/src/userProperties/types.ts +22 -0
  117. package/src/userProperties/useUserProperties.ts +26 -0
@@ -3,6 +3,8 @@ import { PaywallContext } from "./PaywallProvider";
3
3
  import { PaywallCatalog, PresentResult } from "./types";
4
4
  import type { CatalogStatus } from "./present";
5
5
  import type { ProductStatus } from "../products/types";
6
+ import type { CustomPaywallScreens } from "./customScreens";
7
+ import type { RegisterFeature, RegisterResult } from "./register";
6
8
 
7
9
  export type UsePaywallResult = {
8
10
  /**
@@ -16,6 +18,34 @@ export type UsePaywallResult = {
16
18
  * presented. See `resolvePresentDecision` in `present.ts`.
17
19
  */
18
20
  present: (moment: string) => Promise<PresentResult>;
21
+ /**
22
+ * Gate a feature on a moment — Superwall's `registerPlacement`, in this SDK's
23
+ * vocabulary:
24
+ *
25
+ * ```ts
26
+ * await register("unlock_stats", () => router.push("/stats"));
27
+ * ```
28
+ *
29
+ * - The moment has **no paywall** (not monetised, or not authored yet) → runs
30
+ * the feature immediately.
31
+ * - The moment **has** a paywall → presents it, and runs the feature **only**
32
+ * on a purchase. A dismiss or a cancel withholds it.
33
+ * - **No catalog is reachable** → fails OPEN: runs the feature and warns. An
34
+ * offline launch must not silently disable the app's features. Read
35
+ * `reason: "catalog-unavailable"` off the result to measure how often this
36
+ * happens.
37
+ *
38
+ * Gates on the moment **alone** — there is no entitlement check. Exclude
39
+ * paying users by setting a user property
40
+ * (`OnboardingStudio.setUserProperty("plan", "pro")`)
41
+ * and authoring an audience filter on it.
42
+ *
43
+ * **A Stripe-billed paywall never runs the feature**, even on a successful
44
+ * checkout: a Payment Link resolves out-of-band through RevenueCat, so the
45
+ * presentation never reports `"purchased"`. Grant access from your RevenueCat
46
+ * entitlement webhook. `register` warns when it presents one.
47
+ */
48
+ register: (moment: string, feature?: RegisterFeature) => Promise<RegisterResult>;
19
49
  /**
20
50
  * `true` once BOTH the catalog and its products have resolved — the one
21
51
  * flag meaning "calling `present()` now will not show a spinner".
@@ -36,6 +66,19 @@ export type UsePaywallResult = {
36
66
  * host tell "still waiting on the store" from "still waiting on us".
37
67
  */
38
68
  productsStatus: ProductStatus;
69
+ /**
70
+ * Whether a real `PaywallProvider` is above this consumer — see the field's
71
+ * doc on `PaywallContextValue`. Needed by any consumer that renders a
72
+ * spinner while the catalog loads, because with no provider
73
+ * `catalogStatus` reports `"loading"` and nothing ever arrives.
74
+ */
75
+ isProviderMounted: boolean;
76
+ /**
77
+ * Host-registered screens for `renderMode: "custom"` paywalls, keyed by
78
+ * `customScreenId`. Exposed here because the inline `Paywall` onboarding
79
+ * step renders them itself, never going through `PaywallHost`.
80
+ */
81
+ customScreens: CustomPaywallScreens;
39
82
  };
40
83
 
41
84
  /**
@@ -45,7 +88,24 @@ export type UsePaywallResult = {
45
88
  * `useProductRuntime()` degrades to `null` with no ancestor.
46
89
  */
47
90
  export const usePaywall = (): UsePaywallResult => {
48
- const { present, isReady, catalog, catalogStatus, productsStatus } =
49
- useContext(PaywallContext);
50
- return { present, isReady, catalog, catalogStatus, productsStatus };
91
+ const {
92
+ present,
93
+ register,
94
+ isReady,
95
+ catalog,
96
+ catalogStatus,
97
+ productsStatus,
98
+ isProviderMounted,
99
+ customScreens,
100
+ } = useContext(PaywallContext);
101
+ return {
102
+ present,
103
+ register,
104
+ isReady,
105
+ catalog,
106
+ catalogStatus,
107
+ productsStatus,
108
+ isProviderMounted,
109
+ customScreens,
110
+ };
51
111
  };
@@ -0,0 +1,29 @@
1
+ import { z } from "zod";
2
+ import { BaseStepTypeSchema } from "../common.types";
3
+
4
+ /**
5
+ * A step that IS a paywall.
6
+ *
7
+ * `moment` is a `moments.key` — the same address a host passes to `present()`.
8
+ * It resolves through the catalog `get-paywalls` already returns keyed by
9
+ * moment, which means the audience waterfall has ALREADY picked the variant:
10
+ * targeting and weighted A/B come for free, and this payload needs exactly one
11
+ * field. No wire change was required anywhere for this step type.
12
+ *
13
+ * Deliberately not a paywall id: that would bypass the waterfall, so
14
+ * A/B-testing a paywall inside an onboarding would mean duplicating the whole
15
+ * onboarding.
16
+ *
17
+ * Rendered inline by the UI package's `Pages/Paywall/Renderer.tsx`, and
18
+ * HARD-GATED — only a purchase advances past it.
19
+ */
20
+ export const PaywallStepPayloadSchema = z.object({
21
+ moment: z.string().min(1),
22
+ });
23
+
24
+ export const PaywallStepTypeSchema = BaseStepTypeSchema.extend({
25
+ type: z.literal("Paywall"),
26
+ payload: PaywallStepPayloadSchema,
27
+ });
28
+
29
+ export type PaywallStepType = z.infer<typeof PaywallStepTypeSchema>;
@@ -3,6 +3,7 @@ import { CommitmentStepType } from "./Commitment/types";
3
3
  import { LoaderStepType } from "./Loader/types";
4
4
  import { MediaContentStepType } from "./MediaContent/types";
5
5
  import { ComposableScreenStepType } from "./ComposableScreen/types";
6
+ import { PaywallStepType } from "./Paywall/types";
6
7
  import { PickerStepType } from "./Picker/types";
7
8
  import { QuestionStepType } from "./Question/types";
8
9
  import { RatingsStepType } from "./Ratings/types";
@@ -13,6 +14,7 @@ export type OnboardingStepType =
13
14
  | LoaderStepType
14
15
  | MediaContentStepType
15
16
  | ComposableScreenStepType
17
+ | PaywallStepType
16
18
  | PickerStepType
17
19
  | QuestionStepType
18
20
  | RatingsStepType;
@@ -0,0 +1,51 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { resolveEffectiveParams } from "../effectiveParams";
3
+
4
+ beforeEach(() => {
5
+ vi.restoreAllMocks();
6
+ });
7
+
8
+ describe("resolveEffectiveParams", () => {
9
+ it("merges the store over the prop", () => {
10
+ expect(resolveEffectiveParams({ onboardingId: "abc", plan: "stale" }, { plan: "free" })).toEqual({
11
+ onboardingId: "abc",
12
+ plan: "free",
13
+ });
14
+ });
15
+
16
+ it("serializes both sides to strings", () => {
17
+ expect(resolveEffectiveParams({ build: 42 }, { days: 3, trial: true })).toEqual({
18
+ build: "42",
19
+ days: "3",
20
+ trial: "true",
21
+ });
22
+ });
23
+
24
+ it('drops a null or undefined baseline value rather than sending "null"', () => {
25
+ expect(resolveEffectiveParams({ a: null, b: undefined, c: "keep" }, {})).toEqual({ c: "keep" });
26
+ });
27
+
28
+ it("drops a reserved key present in the baseline prop, warning once", () => {
29
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
30
+ expect(resolveEffectiveParams({ projectId: "sneaky", plan: "free" }, {})).toEqual({
31
+ plan: "free",
32
+ });
33
+ expect(warn).toHaveBeenCalledTimes(1);
34
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("projectId"));
35
+ });
36
+
37
+ it("returns an empty map for empty inputs", () => {
38
+ expect(resolveEffectiveParams({}, {})).toEqual({});
39
+ });
40
+
41
+ it("tolerates a missing baseline", () => {
42
+ expect(resolveEffectiveParams(undefined as any, { plan: "free" })).toEqual({ plan: "free" });
43
+ });
44
+
45
+ it("stringifies an unsupported baseline value rather than dropping it", () => {
46
+ // `customAudienceParams` is typed `Record<string, any>` and predates this
47
+ // module, so an existing host may already be passing something exotic. It
48
+ // must keep reaching the server exactly as it did before.
49
+ expect(resolveEffectiveParams({ ids: [1, 2] }, {})).toEqual({ ids: "1,2" });
50
+ });
51
+ });
@@ -0,0 +1,96 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { isReservedUserPropertyKey, RESERVED_USER_PROPERTY_KEYS } from "../reserved";
3
+ import { serializeUserPropertyValue, toQueryParams, paramsHash } from "../serialize";
4
+ import { applyUserPropertyPatch } from "../applyPatch";
5
+
6
+ describe("reserved keys", () => {
7
+ it("names every key the client itself puts on the querystring", () => {
8
+ expect([...RESERVED_USER_PROPERTY_KEYS].sort()).toEqual(
9
+ ["appVersion", "draft", "locale", "moment", "now", "omitNulls", "platform", "projectId"],
10
+ );
11
+ });
12
+
13
+ it("is exact, not a prefix match", () => {
14
+ expect(isReservedUserPropertyKey("projectId")).toBe(true);
15
+ expect(isReservedUserPropertyKey("projectIdentifier")).toBe(false);
16
+ });
17
+ });
18
+
19
+ describe("serializeUserPropertyValue", () => {
20
+ it("stringifies each supported value type", () => {
21
+ expect(serializeUserPropertyValue("free")).toBe("free");
22
+ expect(serializeUserPropertyValue(3)).toBe("3");
23
+ expect(serializeUserPropertyValue(0)).toBe("0");
24
+ expect(serializeUserPropertyValue(true)).toBe("true");
25
+ expect(serializeUserPropertyValue(false)).toBe("false");
26
+ });
27
+
28
+ it("keeps a version-shaped string intact for the server's version conversion", () => {
29
+ expect(serializeUserPropertyValue("1.2.3")).toBe("1.2.3");
30
+ });
31
+ });
32
+
33
+ describe("toQueryParams", () => {
34
+ it("serializes every value", () => {
35
+ expect(toQueryParams({ plan: "free", days: 3, trial: false })).toEqual({
36
+ plan: "free",
37
+ days: "3",
38
+ trial: "false",
39
+ });
40
+ });
41
+ });
42
+
43
+ describe("paramsHash", () => {
44
+ it("is stable under key reordering", () => {
45
+ expect(paramsHash({ a: "1", b: "2" })).toBe(paramsHash({ b: "2", a: "1" }));
46
+ });
47
+
48
+ it("changes when any value changes", () => {
49
+ expect(paramsHash({ a: "1" })).not.toBe(paramsHash({ a: "2" }));
50
+ });
51
+
52
+ it("distinguishes a moved delimiter", () => {
53
+ // Without a delimiter per pair, {ab:"c"} and {a:"bc"} would collide.
54
+ expect(paramsHash({ ab: "c" })).not.toBe(paramsHash({ a: "bc" }));
55
+ });
56
+
57
+ it("returns an empty string for no params, so the legacy cache key is unchanged", () => {
58
+ expect(paramsHash({})).toBe("");
59
+ });
60
+ });
61
+
62
+ describe("applyUserPropertyPatch", () => {
63
+ it("merges shallowly rather than replacing", () => {
64
+ const { next } = applyUserPropertyPatch({ plan: "free", days: 3 }, { days: 4 });
65
+ expect(next).toEqual({ plan: "free", days: 4 });
66
+ });
67
+
68
+ it("deletes a key set to null or undefined", () => {
69
+ expect(applyUserPropertyPatch({ plan: "free", days: 3 }, { plan: null }).next).toEqual({ days: 3 });
70
+ expect(applyUserPropertyPatch({ plan: "free" }, { plan: undefined }).next).toEqual({});
71
+ });
72
+
73
+ it("rejects a reserved key, leaving it absent, and warns naming it", () => {
74
+ const { next, warnings } = applyUserPropertyPatch({}, { projectId: "sneaky", plan: "free" });
75
+ expect(next).toEqual({ plan: "free" });
76
+ expect(warnings).toHaveLength(1);
77
+ expect(warnings[0]).toContain("projectId");
78
+ });
79
+
80
+ it("rejects a non-finite number rather than serializing NaN", () => {
81
+ const { next, warnings } = applyUserPropertyPatch({}, { days: NaN, ok: 1 });
82
+ expect(next).toEqual({ ok: 1 });
83
+ expect(warnings[0]).toContain("days");
84
+ });
85
+
86
+ it("rejects an unsupported value type", () => {
87
+ const { next, warnings } = applyUserPropertyPatch({}, { nested: { a: 1 } as any });
88
+ expect(next).toEqual({});
89
+ expect(warnings[0]).toContain("nested");
90
+ });
91
+
92
+ it("returns the same object when the patch changes nothing", () => {
93
+ const current = { plan: "free" };
94
+ expect(applyUserPropertyPatch(current, { plan: "free" }).next).toBe(current);
95
+ });
96
+ });
@@ -0,0 +1,181 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { createUserPropertyStore, USER_PROPERTIES_STORAGE_KEY } from "../store";
3
+
4
+ const makeStorage = (initial: string | null = null) => {
5
+ const store = new Map<string, string>();
6
+ if (initial !== null) store.set(USER_PROPERTIES_STORAGE_KEY, initial);
7
+ return {
8
+ store,
9
+ getItem: vi.fn(async (k: string) => store.get(k) ?? null),
10
+ setItem: vi.fn(async (k: string, v: string) => void store.set(k, v)),
11
+ removeItem: vi.fn(async (k: string) => void store.delete(k)),
12
+ };
13
+ };
14
+
15
+ const flush = () => new Promise<void>((r) => setTimeout(r, 0));
16
+
17
+ beforeEach(() => {
18
+ vi.restoreAllMocks();
19
+ vi.spyOn(console, "warn").mockImplementation(() => {});
20
+ });
21
+
22
+ describe("createUserPropertyStore", () => {
23
+ it("starts hydrating and empty", () => {
24
+ const s = createUserPropertyStore(makeStorage());
25
+ expect(s.getSnapshot()).toEqual({ properties: {}, status: "hydrating" });
26
+ });
27
+
28
+ it("hydrates from storage and flips to ready", async () => {
29
+ const s = createUserPropertyStore(makeStorage(JSON.stringify({ plan: "pro", days: 9 })));
30
+ await s.ensureHydrated();
31
+ expect(s.getSnapshot()).toEqual({ properties: { plan: "pro", days: 9 }, status: "ready" });
32
+ });
33
+
34
+ it("is ready even when storage holds nothing", async () => {
35
+ const s = createUserPropertyStore(makeStorage());
36
+ await s.ensureHydrated();
37
+ expect(s.getSnapshot().status).toBe("ready");
38
+ });
39
+
40
+ it("is ready even when storage throws", async () => {
41
+ const storage = makeStorage();
42
+ storage.getItem.mockRejectedValueOnce(new Error("disk gone"));
43
+ const s = createUserPropertyStore(storage);
44
+ await s.ensureHydrated();
45
+ expect(s.getSnapshot()).toEqual({ properties: {}, status: "ready" });
46
+ });
47
+
48
+ it("discards a corrupt payload rather than throwing", async () => {
49
+ const s = createUserPropertyStore(makeStorage("not json"));
50
+ await s.ensureHydrated();
51
+ expect(s.getSnapshot()).toEqual({ properties: {}, status: "ready" });
52
+ });
53
+
54
+ it("discards a non-object payload", async () => {
55
+ const s = createUserPropertyStore(makeStorage(JSON.stringify([1, 2, 3])));
56
+ await s.ensureHydrated();
57
+ expect(s.getSnapshot().properties).toEqual({});
58
+ });
59
+
60
+ it("drops invalid entries from a persisted payload", async () => {
61
+ const s = createUserPropertyStore(
62
+ makeStorage(JSON.stringify({ plan: "pro", projectId: "sneaky", nested: { a: 1 } })),
63
+ );
64
+ await s.ensureHydrated();
65
+ expect(s.getSnapshot().properties).toEqual({ plan: "pro" });
66
+ });
67
+
68
+ it("hydrates UNDER values already set in memory", async () => {
69
+ const s = createUserPropertyStore(makeStorage(JSON.stringify({ plan: "pro", days: 9 })));
70
+ s.set({ plan: "free" }); // set before hydration resolves
71
+ await s.ensureHydrated();
72
+ // in-memory wins; disk fills the gap
73
+ expect(s.getSnapshot().properties).toEqual({ plan: "free", days: 9 });
74
+ });
75
+
76
+ it("ensureHydrated reads storage once however many callers await it", async () => {
77
+ const storage = makeStorage(JSON.stringify({ a: 1 }));
78
+ const s = createUserPropertyStore(storage);
79
+ await Promise.all([s.ensureHydrated(), s.ensureHydrated(), s.ensureHydrated()]);
80
+ expect(storage.getItem).toHaveBeenCalledTimes(1);
81
+ });
82
+
83
+ it("notifies subscribers on a real change and not on a no-op", async () => {
84
+ const s = createUserPropertyStore(makeStorage());
85
+ await s.ensureHydrated();
86
+ const listener = vi.fn();
87
+ s.subscribe(listener);
88
+
89
+ s.set({ plan: "free" });
90
+ expect(listener).toHaveBeenCalledTimes(1);
91
+
92
+ s.set({ plan: "free" });
93
+ expect(listener).toHaveBeenCalledTimes(1);
94
+ });
95
+
96
+ it("returns an identical snapshot object until something changes", async () => {
97
+ const s = createUserPropertyStore(makeStorage());
98
+ await s.ensureHydrated();
99
+ const a = s.getSnapshot();
100
+ expect(s.getSnapshot()).toBe(a);
101
+ s.set({ plan: "free" });
102
+ expect(s.getSnapshot()).not.toBe(a);
103
+ });
104
+
105
+ it("unsubscribes", async () => {
106
+ const s = createUserPropertyStore(makeStorage());
107
+ await s.ensureHydrated();
108
+ const listener = vi.fn();
109
+ s.subscribe(listener)();
110
+ s.set({ plan: "free" });
111
+ expect(listener).not.toHaveBeenCalled();
112
+ });
113
+
114
+ it("coalesces a burst of mutations into one write", async () => {
115
+ const storage = makeStorage();
116
+ const s = createUserPropertyStore(storage);
117
+ await s.ensureHydrated();
118
+ storage.setItem.mockClear();
119
+
120
+ s.set({ a: 1 });
121
+ s.set({ b: 2 });
122
+ s.set({ c: 3 });
123
+ await flush();
124
+
125
+ expect(storage.setItem).toHaveBeenCalledTimes(1);
126
+ expect(JSON.parse(storage.setItem.mock.calls[0][1])).toEqual({ a: 1, b: 2, c: 3 });
127
+ });
128
+
129
+ it("warns and ignores a reserved key", async () => {
130
+ const s = createUserPropertyStore(makeStorage());
131
+ await s.ensureHydrated();
132
+ s.set({ projectId: "sneaky" });
133
+ expect(s.get()).toEqual({});
134
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("projectId"));
135
+ });
136
+
137
+ it("removes a single key", async () => {
138
+ const s = createUserPropertyStore(makeStorage());
139
+ await s.ensureHydrated();
140
+ s.set({ a: 1, b: 2 });
141
+ s.remove("a");
142
+ expect(s.get()).toEqual({ b: 2 });
143
+ });
144
+
145
+ it("reset clears memory and deletes the persisted map", async () => {
146
+ const storage = makeStorage();
147
+ const s = createUserPropertyStore(storage);
148
+ await s.ensureHydrated();
149
+ s.set({ a: 1 });
150
+ await flush();
151
+ s.reset();
152
+ await flush();
153
+ expect(s.get()).toEqual({});
154
+ expect(storage.removeItem).toHaveBeenCalledWith(USER_PROPERTIES_STORAGE_KEY);
155
+ });
156
+
157
+ it("does not touch storage before hydration, so it cannot clobber the disk", async () => {
158
+ const storage = makeStorage(JSON.stringify({ persisted: "yes" }));
159
+ const s = createUserPropertyStore(storage);
160
+ s.set({ plan: "free" });
161
+ await flush();
162
+ expect(storage.setItem).not.toHaveBeenCalled();
163
+
164
+ await s.ensureHydrated();
165
+ await flush();
166
+ expect(JSON.parse(storage.setItem.mock.calls[0][1])).toEqual({
167
+ persisted: "yes",
168
+ plan: "free",
169
+ });
170
+ });
171
+
172
+ it("survives a failed write without losing the in-memory value", async () => {
173
+ const storage = makeStorage();
174
+ const s = createUserPropertyStore(storage);
175
+ await s.ensureHydrated();
176
+ storage.setItem.mockRejectedValueOnce(new Error("disk full"));
177
+ s.set({ plan: "free" });
178
+ await flush();
179
+ expect(s.get()).toEqual({ plan: "free" });
180
+ });
181
+ });
@@ -0,0 +1,68 @@
1
+ import { isReservedUserPropertyKey } from "./reserved";
2
+ import type { UserProperties, UserPropertyPatch } from "./types";
3
+
4
+ /**
5
+ * The store's entire mutation logic, as a pure function — so merge semantics,
6
+ * deletion, and every rejection rule are covered by an importable test rather
7
+ * than through AsyncStorage and React.
8
+ *
9
+ * Warnings are RETURNED rather than logged here, so the same rules can be
10
+ * asserted without spying on `console`. The store logs them.
11
+ *
12
+ * Returns the SAME `current` object when nothing changed, so a no-op `set` does
13
+ * not notify subscribers or trigger a refetch — a host calling `set({ plan })`
14
+ * on every render must not re-key the catalog query each time.
15
+ */
16
+ export const applyUserPropertyPatch = (
17
+ current: UserProperties,
18
+ patch: UserPropertyPatch,
19
+ ): { next: UserProperties; warnings: string[] } => {
20
+ const warnings: string[] = [];
21
+ const next: UserProperties = { ...current };
22
+ let changed = false;
23
+
24
+ for (const key of Object.keys(patch)) {
25
+ if (isReservedUserPropertyKey(key)) {
26
+ warnings.push(
27
+ `[user-properties] Ignoring "${key}" — the SDK puts that name on the ` +
28
+ "request querystring itself, and a duplicate silently breaks the request. " +
29
+ "Rename the property.",
30
+ );
31
+ continue;
32
+ }
33
+
34
+ const value = patch[key];
35
+
36
+ if (value === null || value === undefined) {
37
+ if (key in next) {
38
+ delete next[key];
39
+ changed = true;
40
+ }
41
+ continue;
42
+ }
43
+
44
+ const type = typeof value;
45
+ if (type === "number") {
46
+ if (!Number.isFinite(value)) {
47
+ warnings.push(
48
+ `[user-properties] Ignoring "${key}" — ${String(value)} is not a finite ` +
49
+ 'number and would reach the server as "NaN"/"Infinity", matching nothing.',
50
+ );
51
+ continue;
52
+ }
53
+ } else if (type !== "string" && type !== "boolean") {
54
+ warnings.push(
55
+ `[user-properties] Ignoring "${key}" — a user property must be a string, ` +
56
+ `number or boolean, not ${type}. Audience filters compare scalars.`,
57
+ );
58
+ continue;
59
+ }
60
+
61
+ if (next[key] !== value) {
62
+ next[key] = value;
63
+ changed = true;
64
+ }
65
+ }
66
+
67
+ return { next: changed ? next : current, warnings };
68
+ };
@@ -0,0 +1,60 @@
1
+ import { isReservedUserPropertyKey } from "./reserved";
2
+ import { serializeUserPropertyValue } from "./serialize";
3
+ import type { UserProperties } from "./types";
4
+
5
+ /**
6
+ * The audience params a provider actually sends: the `customAudienceParams` prop
7
+ * as a static baseline, with the user-property store merged OVER it.
8
+ *
9
+ * Precedence is the store, per key. `customAudienceParams` is where build-time
10
+ * facts live (an `onboardingId`, a build channel) — set once at mount — and the
11
+ * store is where anything that changes at runtime lives. A runtime value losing
12
+ * to a mount-time prop would make the store useless for the case it exists for.
13
+ *
14
+ * The prop is neither deprecated nor removed: merging means every existing host
15
+ * keeps working untouched.
16
+ *
17
+ * Everything is serialized to a string here, once, so the query key, the cache
18
+ * key hash and the querystring all see the same bytes.
19
+ *
20
+ * The prop is typed `Record<string, any>` and predates this module, so its values
21
+ * are treated conservatively:
22
+ *
23
+ * - a reserved name is DROPPED, because it would break the request outright (the
24
+ * client puts that name on the querystring itself — see `reserved.ts`);
25
+ * - `null`/`undefined` is OMITTED rather than sent as the string `"null"`, which
26
+ * would match an audience filter testing for absence;
27
+ * - anything else non-scalar is stringified with `String(...)` rather than
28
+ * dropped, so a host already passing something exotic keeps the exact wire
29
+ * behaviour it had before this module existed.
30
+ */
31
+ export const resolveEffectiveParams = (
32
+ baseline: Record<string, any>,
33
+ properties: UserProperties,
34
+ ): Record<string, string> => {
35
+ const out: Record<string, string> = {};
36
+
37
+ for (const key of Object.keys(baseline ?? {})) {
38
+ if (isReservedUserPropertyKey(key)) {
39
+ console.warn(
40
+ `[user-properties] Ignoring customAudienceParams."${key}" — the SDK puts ` +
41
+ "that name on the request querystring itself, and a duplicate silently " +
42
+ "breaks the request.",
43
+ );
44
+ continue;
45
+ }
46
+ const value = baseline[key];
47
+ if (value === null || value === undefined) continue;
48
+ out[key] =
49
+ typeof value === "string" || typeof value === "number" || typeof value === "boolean"
50
+ ? serializeUserPropertyValue(value)
51
+ : String(value);
52
+ }
53
+
54
+ // The store wins.
55
+ for (const key of Object.keys(properties)) {
56
+ out[key] = serializeUserPropertyValue(properties[key]);
57
+ }
58
+
59
+ return out;
60
+ };
@@ -0,0 +1,11 @@
1
+ export type { UserProperties, UserPropertyPatch, UserPropertyValue } from "./types";
2
+ export { RESERVED_USER_PROPERTY_KEYS, isReservedUserPropertyKey } from "./reserved";
3
+ export type { ReservedUserPropertyKey } from "./reserved";
4
+ export { serializeUserPropertyValue, toQueryParams, paramsHash } from "./serialize";
5
+ export { applyUserPropertyPatch } from "./applyPatch";
6
+ // `userPropertyStore` — the process-wide instance — is deliberately NOT
7
+ // re-exported for hosts: `OnboardingStudio` is the front door. It is imported
8
+ // directly by `OnboardingStudio.ts` and `useUserProperties.ts`.
9
+ export { createUserPropertyStore, USER_PROPERTIES_STORAGE_KEY } from "./store";
10
+ export type { UserPropertySnapshot, UserPropertyStorage, UserPropertyStore } from "./store";
11
+ export { useUserProperties } from "./useUserProperties";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Property names a host may NOT use, because `OnboardingStudioClient` puts them
3
+ * on the querystring itself.
4
+ *
5
+ * Two of them — `moment` and `now` — mirror the server's own
6
+ * `RESERVED_AUDIENCE_VARS`, which strips them because they are server-owned (a
7
+ * client supplying `now` is self-selecting into a time-gated audience).
8
+ *
9
+ * The other six close a collision that is live today and merely unreachable,
10
+ * because nobody hand-writes these names into `customAudienceParams`. The
11
+ * client appends user params FIRST, then its own:
12
+ *
13
+ * Object.entries(userDefinedParams).forEach(([k, v]) => urlParams.append(k, v));
14
+ * urlParams.append("projectId", this.projectId);
15
+ *
16
+ * `URLSearchParams.append` permits duplicates, and the two server-side readers
17
+ * disagree about which one wins: `url.searchParams.get("projectId")` returns the
18
+ * FIRST occurrence (the user's value — so the request resolves the wrong
19
+ * project, or 400s), while `Object.fromEntries(...)` is last-wins (so the
20
+ * json-logic data still holds the real one). The result is a failed or
21
+ * cross-project request with no diagnostic pointing at the property that caused
22
+ * it.
23
+ *
24
+ * A store whose whole purpose is to let a host name keys freely makes that a
25
+ * plausible accident, so this is where it gets refused. Refusing — rather than
26
+ * prefixing or escaping — keeps the wire format unchanged and puts the warning
27
+ * at the call site responsible.
28
+ */
29
+ export const RESERVED_USER_PROPERTY_KEYS = [
30
+ "projectId",
31
+ "platform",
32
+ "appVersion",
33
+ "draft",
34
+ "locale",
35
+ "omitNulls",
36
+ "moment",
37
+ "now",
38
+ ] as const;
39
+
40
+ export type ReservedUserPropertyKey = (typeof RESERVED_USER_PROPERTY_KEYS)[number];
41
+
42
+ /** Exact match, never a prefix — `projectIdentifier` is a perfectly good property. */
43
+ export const isReservedUserPropertyKey = (key: string): boolean =>
44
+ (RESERVED_USER_PROPERTY_KEYS as readonly string[]).includes(key);