@rocapine/react-native-onboarding 1.74.0 → 1.75.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 (62) hide show
  1. package/README.md +31 -3
  2. package/dist/evaluateCondition.d.ts.map +1 -1
  3. package/dist/evaluateCondition.js +103 -4
  4. package/dist/evaluateCondition.js.map +1 -1
  5. package/dist/index.d.ts +6 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +25 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/infra/provider/OnboardingProvider.d.ts +4 -0
  10. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  11. package/dist/infra/provider/OnboardingProvider.js +51 -15
  12. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  13. package/dist/onboarding-example.d.ts +235 -99
  14. package/dist/onboarding-example.d.ts.map +1 -1
  15. package/dist/onboarding-example.js +77 -0
  16. package/dist/onboarding-example.js.map +1 -1
  17. package/dist/screens/completingActions.d.ts +43 -0
  18. package/dist/screens/completingActions.d.ts.map +1 -0
  19. package/dist/screens/completingActions.js +108 -0
  20. package/dist/screens/completingActions.js.map +1 -0
  21. package/dist/screens/elementTypeRegistry.d.ts +31 -0
  22. package/dist/screens/elementTypeRegistry.d.ts.map +1 -0
  23. package/dist/screens/elementTypeRegistry.js +82 -0
  24. package/dist/screens/elementTypeRegistry.js.map +1 -0
  25. package/dist/screens/resolveRenderableStep.d.ts +42 -0
  26. package/dist/screens/resolveRenderableStep.d.ts.map +1 -0
  27. package/dist/screens/resolveRenderableStep.js +28 -0
  28. package/dist/screens/resolveRenderableStep.js.map +1 -0
  29. package/dist/screens/unknownElementTypes.d.ts +94 -0
  30. package/dist/screens/unknownElementTypes.d.ts.map +1 -0
  31. package/dist/screens/unknownElementTypes.js +141 -0
  32. package/dist/screens/unknownElementTypes.js.map +1 -0
  33. package/dist/screens/unknownKeys.d.ts +5 -2
  34. package/dist/screens/unknownKeys.d.ts.map +1 -1
  35. package/dist/screens/unknownKeys.js +7 -52
  36. package/dist/screens/unknownKeys.js.map +1 -1
  37. package/dist/steps/common.types.d.ts +84 -3
  38. package/dist/steps/common.types.d.ts.map +1 -1
  39. package/dist/steps/common.types.js.map +1 -1
  40. package/dist/userProperties/store.d.ts +3 -1
  41. package/dist/userProperties/store.d.ts.map +1 -1
  42. package/dist/userProperties/store.js +3 -1
  43. package/dist/userProperties/store.js.map +1 -1
  44. package/package.json +5 -1
  45. package/src/__tests__/OnboardingDataGate.test.tsx +445 -0
  46. package/src/__tests__/completingActions.test.ts +139 -0
  47. package/src/__tests__/elementTypeRegistry.test.ts +48 -0
  48. package/src/__tests__/evaluateCondition.test.ts +228 -3
  49. package/src/__tests__/onboardingExampleElements.test.ts +27 -0
  50. package/src/__tests__/resolveRenderableStep.test.ts +117 -0
  51. package/src/__tests__/unknownElementTypes.test.ts +240 -0
  52. package/src/evaluateCondition.ts +107 -4
  53. package/src/index.ts +23 -0
  54. package/src/infra/provider/OnboardingProvider.tsx +67 -20
  55. package/src/onboarding-example.ts +78 -0
  56. package/src/screens/completingActions.ts +108 -0
  57. package/src/screens/elementTypeRegistry.ts +88 -0
  58. package/src/screens/resolveRenderableStep.ts +59 -0
  59. package/src/screens/unknownElementTypes.ts +204 -0
  60. package/src/screens/unknownKeys.ts +7 -50
  61. package/src/steps/common.types.ts +84 -3
  62. package/src/userProperties/store.ts +3 -1
@@ -0,0 +1,445 @@
1
+ // @vitest-environment jsdom
2
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
3
+ import React, { StrictMode, Suspense, useEffect } from "react";
4
+ import { act } from "react";
5
+ import { createRoot, type Root } from "react-dom/client";
6
+ import { useQueryClient } from "@tanstack/react-query";
7
+ import { USER_PROPERTIES_STORAGE_KEY } from "../userProperties/store";
8
+
9
+ /**
10
+ * The serve-time rule, end to end through a real render:
11
+ *
12
+ * Audience resolution happens at serve time, and a served payload is frozen
13
+ * for that presentation. User-property changes apply to the NEXT serve.
14
+ *
15
+ * These render the real `OnboardingProvider` (react-dom under jsdom — the gate
16
+ * has no RN-only code path; `react-native` is stubbed the way the other suites
17
+ * stub it) against a fake client, so the assertions are about what a host
18
+ * observes: how many times `getSteps` ran, with which audience params, and
19
+ * whether the subtree under the provider ever unmounted.
20
+ *
21
+ * Every test loads a FRESH module graph (`vi.resetModules` + dynamic import):
22
+ * the user-property store, the `OnboardingStudio` facade and the provider's
23
+ * `QueryClient` are all module singletons, and a "next launch" is exactly a
24
+ * fresh graph over the same persisted storage.
25
+ */
26
+
27
+ // In-memory AsyncStorage shared across module resets, so a property persisted
28
+ // during one "launch" is there to hydrate on the next. `holdHydration` makes
29
+ // the user-property read (only that one — a production client's payload cache
30
+ // read must not deadlock on it) block until released: the window in which a
31
+ // host writes a property before the store is ready.
32
+ const storage = vi.hoisted(() => {
33
+ const map = new Map<string, string>();
34
+ let gate: { promise: Promise<void>; release: () => void } | null = null;
35
+ // Literal, not the imported constant: `vi.hoisted` runs before imports.
36
+ // `beforeEach` checks it still matches `USER_PROPERTIES_STORAGE_KEY`.
37
+ const heldKey = "rocapine-user-properties";
38
+ return {
39
+ map,
40
+ heldKey,
41
+ holdHydration() {
42
+ let release!: () => void;
43
+ const promise = new Promise<void>((r) => (release = r));
44
+ gate = { promise, release };
45
+ },
46
+ releaseHydration() {
47
+ gate?.release();
48
+ gate = null;
49
+ },
50
+ getItem: vi.fn(async (key: string) => {
51
+ if (gate && key === heldKey) await gate.promise;
52
+ return map.get(key) ?? null;
53
+ }),
54
+ setItem: vi.fn(async (key: string, value: string) => void map.set(key, value)),
55
+ removeItem: vi.fn(async (key: string) => void map.delete(key)),
56
+ getAllKeys: vi.fn(async () => [...map.keys()]),
57
+ multiRemove: vi.fn(async (keys: string[]) => keys.forEach((k) => map.delete(k))),
58
+ };
59
+ });
60
+ vi.mock("@react-native-async-storage/async-storage", () => ({ default: storage }));
61
+ // `OnboardingStudioClient` reads `Platform.OS`; `preloadAssets` reaches for
62
+ // `Image.prefetch`. Neither is exercised here beyond loading.
63
+ vi.mock("react-native", () => ({
64
+ Platform: { OS: "ios" },
65
+ Image: { prefetch: vi.fn(async () => true) },
66
+ }));
67
+
68
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
69
+
70
+ type Modules = {
71
+ OnboardingProvider: typeof import("../infra/provider/OnboardingProvider").OnboardingProvider;
72
+ OnboardingStudio: typeof import("../OnboardingStudio").OnboardingStudio;
73
+ useOnboardingStep: typeof import("../infra/hooks/useOnboardingStep").useOnboardingStep;
74
+ useOnboardingStart: typeof import("../infra/hooks/useOnboardingStart").useOnboardingStart;
75
+ };
76
+
77
+ /** A fresh module graph — a fresh store, facade and QueryClient — i.e. one launch. */
78
+ const launch = async (): Promise<Modules> => {
79
+ vi.resetModules();
80
+ const [provider, studio, step, start] = await Promise.all([
81
+ import("../infra/provider/OnboardingProvider"),
82
+ import("../OnboardingStudio"),
83
+ import("../infra/hooks/useOnboardingStep"),
84
+ import("../infra/hooks/useOnboardingStart"),
85
+ ]);
86
+ return {
87
+ OnboardingProvider: provider.OnboardingProvider,
88
+ OnboardingStudio: studio.OnboardingStudio,
89
+ useOnboardingStep: step.useOnboardingStep,
90
+ useOnboardingStart: start.useOnboardingStart,
91
+ };
92
+ };
93
+
94
+ type Fonts = Record<string, Record<string, string>>;
95
+
96
+ const onboarding = (id: string, fonts: Fonts = {}) =>
97
+ ({
98
+ metadata: { id, name: id },
99
+ steps: [{ id: `${id}-step-1`, name: "one", type: "MediaContent", displayProgressHeader: true, payload: {} }],
100
+ fonts,
101
+ }) as any;
102
+
103
+ // A real fonts manifest. With an empty one `FontLoaderGate` never passes through
104
+ // `null`, which would make every "did not unmount" assertion vacuous.
105
+ const FONTS: Fonts = { Inter: { regular: "https://cdn.test/inter.ttf" } };
106
+
107
+ /**
108
+ * A sandbox client (no disk cache, so every serve is a network call and the
109
+ * `getSteps` spy is the whole story). Answers with an onboarding named after
110
+ * the `plan` param it was asked for, so the assertions can tell WHICH audience
111
+ * a payload was resolved against.
112
+ */
113
+ const makeClient = () => {
114
+ const getSteps = vi.fn(async (_opts: unknown, params: Record<string, string>) => ({
115
+ data: onboarding(`for-${params.plan ?? "nobody"}`, FONTS),
116
+ headers: {
117
+ "ONBS-Onboarding-Id": "real",
118
+ "ONBS-Onboarding-Name": "real",
119
+ "ONBS-Audience-Id": "real",
120
+ },
121
+ }));
122
+ return { projectId: "p1", options: { isSandbox: true }, getSteps } as any;
123
+ };
124
+
125
+ // Counts mounts/unmounts of the subtree the gate guards. A `null` render by the
126
+ // gate — the defect under test — shows up here as an unmount.
127
+ const probe = { mounts: 0, unmounts: 0 };
128
+ const Probe = ({ label }: { label: string }) => {
129
+ useEffect(() => {
130
+ probe.mounts += 1;
131
+ return () => {
132
+ probe.unmounts += 1;
133
+ };
134
+ }, []);
135
+ return <div data-testid="probe">{label}</div>;
136
+ };
137
+
138
+ let root: Root | null = null;
139
+ let container: HTMLDivElement | null = null;
140
+
141
+ const flush = () => new Promise<void>((r) => setTimeout(r, 0));
142
+ /** Lets pending promises, effects and the store's coalesced write all land. */
143
+ const settle = async () => {
144
+ await act(async () => {
145
+ await flush();
146
+ await flush();
147
+ });
148
+ };
149
+
150
+ const render = async (element: React.ReactElement) => {
151
+ container = document.createElement("div");
152
+ document.body.appendChild(container);
153
+ root = createRoot(container);
154
+ await act(async () => {
155
+ root!.render(element);
156
+ });
157
+ await settle();
158
+ };
159
+
160
+ const rerender = async (element: React.ReactElement) => {
161
+ await act(async () => {
162
+ root!.render(element);
163
+ });
164
+ await settle();
165
+ };
166
+
167
+ const unmount = async () => {
168
+ if (root) await act(async () => root!.unmount());
169
+ container?.remove();
170
+ root = null;
171
+ container = null;
172
+ };
173
+
174
+ const text = () => container?.textContent ?? "";
175
+
176
+ beforeEach(() => {
177
+ expect(storage.heldKey).toBe(USER_PROPERTIES_STORAGE_KEY);
178
+ storage.map.clear();
179
+ storage.releaseHydration();
180
+ // `vi.restoreAllMocks` only restores `spyOn` spies; these `vi.fn`s would
181
+ // otherwise carry call history from one test into the next.
182
+ storage.getItem.mockClear();
183
+ storage.setItem.mockClear();
184
+ storage.removeItem.mockClear();
185
+ storage.getAllKeys.mockClear();
186
+ storage.multiRemove.mockClear();
187
+ probe.mounts = 0;
188
+ probe.unmounts = 0;
189
+ vi.spyOn(console, "warn").mockImplementation(() => {});
190
+ vi.spyOn(console, "info").mockImplementation(() => {});
191
+ });
192
+
193
+ afterEach(async () => {
194
+ await unmount();
195
+ vi.restoreAllMocks();
196
+ });
197
+
198
+ describe("OnboardingDataGate — audience params are pinned at serve time", () => {
199
+ it("a user-property write after the first serve does not re-key, refetch, or unmount the subtree", async () => {
200
+ const { OnboardingProvider, OnboardingStudio } = await launch();
201
+ const client = makeClient();
202
+
203
+ await render(
204
+ <OnboardingProvider client={client} fontsFallback={<div>fallback</div>}>
205
+ <Probe label="served" />
206
+ </OnboardingProvider>
207
+ );
208
+
209
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
210
+ expect(text()).toBe("served");
211
+ expect(probe.mounts).toBe(1);
212
+
213
+ // The write that used to blank the whole app: the merged params changed, the
214
+ // query key followed them, react-query answered `undefined` for the unseen
215
+ // key, and the gate rendered `null`.
216
+ await act(async () => {
217
+ OnboardingStudio.setUserProperty("plan", "pro");
218
+ });
219
+ await settle();
220
+ await act(async () => {
221
+ OnboardingStudio.setUserProperties({ demandScore: 87 });
222
+ });
223
+ await settle();
224
+
225
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
226
+ expect(text()).toBe("served");
227
+ expect(probe.unmounts).toBe(0);
228
+ expect(probe.mounts).toBe(1);
229
+ });
230
+
231
+ it("pins once under StrictMode's double render: one fetch, with the merged params", async () => {
232
+ const { OnboardingProvider, OnboardingStudio } = await launch();
233
+ OnboardingStudio.setUserProperty("plan", "pro");
234
+ const client = makeClient();
235
+
236
+ await render(
237
+ <StrictMode>
238
+ <OnboardingProvider client={client} customAudienceParams={{ channel: "a" }}>
239
+ <Probe label="served" />
240
+ </OnboardingProvider>
241
+ </StrictMode>
242
+ );
243
+
244
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
245
+ expect(client.getSteps.mock.calls[0][1]).toEqual({ channel: "a", plan: "pro" });
246
+ expect(text()).toBe("served");
247
+ });
248
+
249
+ it("a `customAudienceParams` prop change after the first serve is frozen too", async () => {
250
+ const { OnboardingProvider } = await launch();
251
+ const client = makeClient();
252
+ const tree = (params: Record<string, string>) => (
253
+ <OnboardingProvider client={client} customAudienceParams={params}>
254
+ <Probe label="served" />
255
+ </OnboardingProvider>
256
+ );
257
+
258
+ await render(tree({ channel: "a" }));
259
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
260
+ expect(client.getSteps.mock.calls[0][1]).toEqual({ channel: "a" });
261
+
262
+ await rerender(tree({ channel: "b" }));
263
+
264
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
265
+ expect(text()).toBe("served");
266
+ expect(probe.unmounts).toBe(0);
267
+ });
268
+
269
+ it("a write BEFORE the first serve (during hydration) is in the first fetch's params", async () => {
270
+ storage.holdHydration();
271
+ const { OnboardingProvider, OnboardingStudio } = await launch();
272
+ const client = makeClient();
273
+
274
+ await render(
275
+ <OnboardingProvider client={client} customAudienceParams={{ plan: "prop", channel: "a" }}>
276
+ <Probe label="served" />
277
+ </OnboardingProvider>
278
+ );
279
+
280
+ // Still hydrating: nothing fetched, nothing pinned.
281
+ expect(client.getSteps).not.toHaveBeenCalled();
282
+
283
+ await act(async () => {
284
+ OnboardingStudio.setUserProperty("plan", "pro");
285
+ });
286
+ await act(async () => {
287
+ storage.releaseHydration();
288
+ });
289
+ await settle();
290
+
291
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
292
+ // Store wins over the prop, per key; the pin was taken from the READY
293
+ // snapshot, not from the empty pre-hydration map.
294
+ expect(client.getSteps.mock.calls[0][1]).toEqual({ plan: "pro", channel: "a" });
295
+ expect(text()).toBe("served");
296
+ });
297
+
298
+ it("the next serve (a fresh launch) picks up properties written during the previous one", async () => {
299
+ // Launch 1: serve, then write a property mid-flow.
300
+ const first = await launch();
301
+ const client1 = makeClient();
302
+ await render(
303
+ <first.OnboardingProvider client={client1}>
304
+ <Probe label="served" />
305
+ </first.OnboardingProvider>
306
+ );
307
+ expect(client1.getSteps.mock.calls[0][1]).toEqual({});
308
+
309
+ await act(async () => {
310
+ first.OnboardingStudio.setUserProperty("plan", "pro");
311
+ });
312
+ await settle(); // the store's coalesced write reaches "disk"
313
+ expect(client1.getSteps).toHaveBeenCalledTimes(1);
314
+ await unmount();
315
+
316
+ // Launch 2: a fresh module graph hydrates from the same storage.
317
+ const second = await launch();
318
+ const client2 = makeClient();
319
+ await render(
320
+ <second.OnboardingProvider client={client2}>
321
+ <Probe label="served again" />
322
+ </second.OnboardingProvider>
323
+ );
324
+
325
+ expect(client2.getSteps).toHaveBeenCalledTimes(1);
326
+ expect(client2.getSteps.mock.calls[0][1]).toEqual({ plan: "pro" });
327
+ expect(text()).toBe("served again");
328
+ });
329
+
330
+ it("a remount of the provider is a new serve and re-resolves with the current properties", async () => {
331
+ const { OnboardingProvider, OnboardingStudio } = await launch();
332
+ const client = makeClient();
333
+ const tree = (key: number) => (
334
+ <OnboardingProvider key={key} client={client}>
335
+ <Probe label={`serve ${key}`} />
336
+ </OnboardingProvider>
337
+ );
338
+
339
+ await render(tree(1));
340
+ await act(async () => {
341
+ OnboardingStudio.setUserProperty("plan", "pro");
342
+ });
343
+ await settle();
344
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
345
+
346
+ await rerender(tree(2));
347
+
348
+ expect(client.getSteps).toHaveBeenCalledTimes(2);
349
+ expect(client.getSteps.mock.calls[1][1]).toEqual({ plan: "pro" });
350
+ expect(text()).toBe("serve 2");
351
+ // The price of re-targeting: a remount IS the full teardown the pin exists
352
+ // to prevent mid-flow, so it belongs at a flow boundary, never mid-onboarding.
353
+ expect(probe.unmounts).toBe(1);
354
+ expect(probe.mounts).toBe(2);
355
+ });
356
+
357
+ it("the forced-refetch escape hatch still works, under the pinned audience, without unmounting", async () => {
358
+ const { OnboardingProvider, OnboardingStudio } = await launch();
359
+ const client = makeClient();
360
+
361
+ let invalidate: (() => Promise<void>) | null = null;
362
+ const Escape = () => {
363
+ const queryClient = useQueryClient();
364
+ invalidate = () => queryClient.invalidateQueries({ queryKey: ["onboardingQuestions"] });
365
+ return null;
366
+ };
367
+
368
+ await render(
369
+ <OnboardingProvider client={client} customAudienceParams={{ plan: "prop" }}>
370
+ <Escape />
371
+ <Probe label="served" />
372
+ </OnboardingProvider>
373
+ );
374
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
375
+
376
+ // A property written mid-flow does not re-target the presentation, even
377
+ // when the host then forces a content refresh: the refetch re-serves the
378
+ // same pinned audience. Re-targeting is a new serve, i.e. a remount.
379
+ await act(async () => {
380
+ OnboardingStudio.setUserProperty("plan", "pro");
381
+ });
382
+ await settle();
383
+ await act(async () => {
384
+ await invalidate!();
385
+ });
386
+ await settle();
387
+
388
+ expect(client.getSteps).toHaveBeenCalledTimes(2);
389
+ expect(client.getSteps.mock.calls[1][1]).toEqual({ plan: "prop" });
390
+ expect(text()).toBe("served");
391
+ expect(probe.unmounts).toBe(0);
392
+ });
393
+ });
394
+
395
+ describe("the step hooks read the served audience params", () => {
396
+ it("shares the gate's query when the store is non-empty: one fetch, the store-targeted payload", async () => {
397
+ const { OnboardingProvider, OnboardingStudio, useOnboardingStep } = await launch();
398
+ OnboardingStudio.setUserProperty("plan", "pro");
399
+ const client = makeClient();
400
+
401
+ const Step = () => {
402
+ const { onboardingMetadata } = useOnboardingStep({ stepNumber: 1 });
403
+ return <div>{onboardingMetadata.id}</div>;
404
+ };
405
+
406
+ await render(
407
+ <OnboardingProvider client={client} customAudienceParams={{ channel: "a" }}>
408
+ <Suspense fallback={<div>suspended</div>}>
409
+ <Step />
410
+ </Suspense>
411
+ </OnboardingProvider>
412
+ );
413
+
414
+ // Before this change the hook built its own query from the RAW prop
415
+ // (`{ channel: "a" }`), so a non-empty store meant a second fetch under a
416
+ // second key — and the screens rendered the payload resolved WITHOUT the
417
+ // user's properties.
418
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
419
+ expect(client.getSteps.mock.calls[0][1]).toEqual({ channel: "a", plan: "pro" });
420
+ expect(text()).toBe("for-pro");
421
+ });
422
+
423
+ it("useOnboardingStart shares it too", async () => {
424
+ const { OnboardingProvider, OnboardingStudio, useOnboardingStart } = await launch();
425
+ OnboardingStudio.setUserProperty("plan", "pro");
426
+ const client = makeClient();
427
+
428
+ const Start = () => {
429
+ const { startStepNumber } = useOnboardingStart();
430
+ return <div>start {startStepNumber}</div>;
431
+ };
432
+
433
+ await render(
434
+ <OnboardingProvider client={client}>
435
+ <Suspense fallback={<div>suspended</div>}>
436
+ <Start />
437
+ </Suspense>
438
+ </OnboardingProvider>
439
+ );
440
+
441
+ expect(client.getSteps).toHaveBeenCalledTimes(1);
442
+ expect(client.getSteps.mock.calls[0][1]).toEqual({ plan: "pro" });
443
+ expect(text()).toBe("start 1");
444
+ });
445
+ });
@@ -0,0 +1,139 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { hasCompletingAction } from "../screens/completingActions";
3
+
4
+ /**
5
+ * "Can the user still get off this screen?" (#209, review finding 1).
6
+ *
7
+ * The unknown-element strip removes a subtree, and a ComposableScreen's CTA is
8
+ * authored INSIDE that tree — `ComposableScreenRenderer` passes no `button` to
9
+ * `OnboardingTemplate`, so nothing outside `ScreenRenderer` can call
10
+ * `onContinue`. Strip the element that happened to be the screen's root
11
+ * container and the payload parses cleanly to `elements: []`: a blank screen,
12
+ * no CTA, and with `displayProgressHeader: false` no back chevron either. The
13
+ * throw that at least reached an error boundary became a silent trap.
14
+ *
15
+ * This predicate is what the renderer consults to decide whether it must supply
16
+ * its own escape. `runActions` is the only thing in the runtime that ever calls
17
+ * `onContinue`, and it does so for exactly two actions — `"continue"` and
18
+ * `{type:"dismiss"}` — so those two, wherever they are reachable from a press,
19
+ * are the whole definition of "this screen can be completed".
20
+ */
21
+
22
+ const button = (id: string, actions: unknown[]) => ({
23
+ id,
24
+ type: "Button",
25
+ props: { label: "Go", actions },
26
+ });
27
+
28
+ describe("hasCompletingAction", () => {
29
+ it("finds a Button whose actions continue", () => {
30
+ expect(hasCompletingAction([button("cta", ["continue"])])).toBe(true);
31
+ });
32
+
33
+ it("finds a continue nested inside a container", () => {
34
+ const tree = [
35
+ { id: "root", type: "YStack", props: {}, children: [button("cta", ["continue"])] },
36
+ ];
37
+ expect(hasCompletingAction(tree)).toBe(true);
38
+ });
39
+
40
+ it("reports no way forward for a screen of static content", () => {
41
+ const tree = [
42
+ {
43
+ id: "root",
44
+ type: "YStack",
45
+ props: {},
46
+ children: [{ id: "t", type: "Text", props: { content: "hello" } }],
47
+ },
48
+ ];
49
+ expect(hasCompletingAction(tree)).toBe(false);
50
+ });
51
+
52
+ it("reports no way forward for an empty screen — the exact post-strip case", () => {
53
+ expect(hasCompletingAction([])).toBe(false);
54
+ });
55
+
56
+ it("accepts the deprecated `action: \"continue\"` shorthand", () => {
57
+ expect(hasCompletingAction([{ id: "cta", type: "Button", props: { label: "Go", action: "continue" } }])).toBe(
58
+ true
59
+ );
60
+ });
61
+
62
+ it("accepts the generic `onPress` any element can carry", () => {
63
+ const tree = [{ id: "card", type: "YStack", props: { onPress: ["continue"] }, children: [] }];
64
+ expect(hasCompletingAction(tree)).toBe(true);
65
+ });
66
+
67
+ it("ignores an `onPress` on a Button, which renderElement never wires", () => {
68
+ // `PRESS_HANDLED_TYPES` in `renderElement.tsx`: Button and the other
69
+ // self-handling elements dispatch their own actions, so the generic
70
+ // `onPress` from BaseBoxProps is not wired for them. Counting it would read
71
+ // as "the user can leave" on a screen whose only control does nothing.
72
+ const tree = [{ id: "cta", type: "Button", props: { label: "Go", onPress: ["continue"] } }];
73
+ expect(hasCompletingAction(tree)).toBe(false);
74
+ });
75
+
76
+ it("counts `dismiss`, which completes the screen just as `continue` does", () => {
77
+ expect(hasCompletingAction([button("x", [{ type: "dismiss" }])])).toBe(true);
78
+ });
79
+
80
+ it("finds a continue in a purchase action's onSuccess branch", () => {
81
+ const tree = [
82
+ button("buy", [
83
+ { type: "purchase", product: "p1", onSuccess: ["continue"] },
84
+ ]),
85
+ ];
86
+ expect(hasCompletingAction(tree)).toBe(true);
87
+ });
88
+
89
+ it("finds a continue in a restore action's onNothingToRestore branch", () => {
90
+ const tree = [
91
+ button("restore", [{ type: "restore", onNothingToRestore: ["continue"] }]),
92
+ ];
93
+ expect(hasCompletingAction(tree)).toBe(true);
94
+ });
95
+
96
+ it("does not count setVariable, which leaves the user on the screen", () => {
97
+ const tree = [button("pick", [{ type: "setVariable", name: "goal", value: "lose" }])];
98
+ expect(hasCompletingAction(tree)).toBe(false);
99
+ });
100
+
101
+ it("does not count presentPaywall — a modal opens over the screen, the step does not advance", () => {
102
+ const tree = [button("open", [{ type: "presentPaywall", placement: "hard_paywall" }])];
103
+ expect(hasCompletingAction(tree)).toBe(false);
104
+ });
105
+
106
+ it("does not count a host `custom` action, whose effect this SDK cannot know", () => {
107
+ // Deliberate, and the safer of the two errors: a host handler that
108
+ // navigates by itself would get a redundant escape CTA on an
109
+ // already-degraded screen, whereas guessing the other way re-creates the
110
+ // trap. `runActions` does not call `onContinue` for `custom`.
111
+ const tree = [button("skip", [{ type: "custom", name: "skipOnboarding" }])];
112
+ expect(hasCompletingAction(tree)).toBe(false);
113
+ });
114
+
115
+ it("looks inside a Repeat's children, where a CTA can legitimately live", () => {
116
+ const tree = [
117
+ {
118
+ id: "rep",
119
+ type: "Repeat",
120
+ props: { over: "goals" },
121
+ children: [button("cta", ["continue"])],
122
+ },
123
+ ];
124
+ expect(hasCompletingAction(tree)).toBe(true);
125
+ });
126
+
127
+ it("survives a malformed payload rather than throwing", () => {
128
+ expect(hasCompletingAction([null, 3, "x", { id: "a" }, { props: null }])).toBe(false);
129
+ expect(hasCompletingAction(undefined)).toBe(false);
130
+ expect(hasCompletingAction({ not: "an array" })).toBe(false);
131
+ });
132
+
133
+ it("ignores a bare `{type:\"continue\"}` object — that is not an action this runtime runs", () => {
134
+ // `ButtonActionSchema` declares continue as the string literal `"continue"`.
135
+ // An object is not it, so the runtime would never advance on it; reading it
136
+ // as a way forward would leave the user stuck with no escape.
137
+ expect(hasCompletingAction([button("cta", [{ type: "continue" }])])).toBe(false);
138
+ });
139
+ });
@@ -0,0 +1,48 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { z } from "zod";
3
+ import { deriveElementTypeNames, getKnownElementTypes } from "../screens/elementTypeRegistry";
4
+ import { UIElementSchema } from "../screens/types";
5
+
6
+ /**
7
+ * The type-name derivation is schema-AGNOSTIC on purpose (#209, review
8
+ * finding 2).
9
+ *
10
+ * The strip decides what renders, and what renders is the onboarding-ui
11
+ * package's own re-declared `UIElementSchema` — a different file, in a package
12
+ * joined to this one by a peer-dependency RANGE, so the two versions can
13
+ * legitimately differ in a host app. That package therefore has to derive its
14
+ * OWN capability set with this same mechanism instead of inheriting this
15
+ * package's answer, and these tests pin the mechanism it depends on: give it a
16
+ * union it has never seen, get that union's literals back.
17
+ */
18
+
19
+ const variant = (type: string) =>
20
+ z.object({ id: z.string(), type: z.literal(type), props: z.object({}) });
21
+
22
+ describe("deriveElementTypeNames", () => {
23
+ it("reads the literals of a discriminated union it has never seen", () => {
24
+ const schema = z.discriminatedUnion("type", [variant("Halo"), variant("Sparkle")]);
25
+ expect([...deriveElementTypeNames(schema)].sort()).toEqual(["Halo", "Sparkle"]);
26
+ });
27
+
28
+ it("looks through a z.lazy wrapper, as both packages' real schemas use one", () => {
29
+ const schema = z.lazy(() => z.discriminatedUnion("type", [variant("Halo")]));
30
+ expect([...deriveElementTypeNames(schema)]).toEqual(["Halo"]);
31
+ });
32
+
33
+ it("answers with an empty set — never a partial one — for a schema it cannot read", () => {
34
+ // Empty is the agreed "could not tell" signal every caller reads as "learn
35
+ // nothing". Anything else here would be read as a capability list.
36
+ expect(deriveElementTypeNames(z.string()).size).toBe(0);
37
+ expect(deriveElementTypeNames(undefined).size).toBe(0);
38
+ expect(deriveElementTypeNames({ _zod: { def: "nonsense" } }).size).toBe(0);
39
+ });
40
+
41
+ it("agrees with getKnownElementTypes on this package's own schema", () => {
42
+ // The cached, no-argument accessor must be the same derivation applied to
43
+ // the headless union — otherwise "known" would mean two different things.
44
+ expect([...getKnownElementTypes()].sort()).toEqual(
45
+ [...deriveElementTypeNames(UIElementSchema)].sort()
46
+ );
47
+ });
48
+ });