@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
@@ -42,9 +42,112 @@ function isEmpty(v: unknown): boolean {
42
42
  return false;
43
43
  }
44
44
 
45
+ // A condition's right-hand side may reference other variables with `{{name}}`,
46
+ // which is what lets a condition compare two variables instead of a variable
47
+ // against an authored literal. `RepeatElement` documents exactly this shape to
48
+ // make `Repeat` subsume a `Match` — `{ variable: "item.sign", operator: "eq",
49
+ // value: "{{zodiacSign}}" }` — and without interpolation here that comparison
50
+ // tests against the 14-character literal and never matches.
51
+ //
52
+ // References resolve to the variable's raw value stringified, matching
53
+ // `Image mode:"expression"` (machine identifiers, not display labels); the map
54
+ // reaching this function is already flat primitives. An unknown reference
55
+ // resolves to the empty string rather than throwing, so a gate on a variable
56
+ // that has not been written yet simply does not match.
57
+ const REF = /\{\{([^}]+?)\}\}/g;
58
+
59
+ function interpolateRefs(value: unknown, variables: Record<string, unknown>): unknown {
60
+ if (Array.isArray(value)) return value.map((v) => interpolateRefs(v, variables));
61
+ if (typeof value !== "string" || !value.includes("{{")) return value;
62
+ return value.replace(REF, (_, key: string) => {
63
+ const resolved = variables[key.trim()];
64
+ return resolved === undefined || resolved === null ? "" : String(resolved);
65
+ });
66
+ }
67
+
68
+ // "No member" vs "a member that is empty". An unresolved `{{ref}}` interpolates
69
+ // to the empty string (`interpolateRefs`), and it reaches the comparison in both
70
+ // right-hand-side shapes identically — bare, or as the single member of the array
71
+ // Studio's condition editor emits. Keeping it as a member would make an
72
+ // empty-string variable a member of a list nobody has written (`in` matches,
73
+ // `not_in` does not — the opposite of the same gate written bare), and an
74
+ // empty-string variable is reachable: `InputElement` stores "" on clear and
75
+ // `Input.defaultValue: ""` is overlaid into the variable map. Nothing authorable
76
+ // is lost — Studio's value field drops empty members (`filter(Boolean)`), and
77
+ // `is_empty` is the operator for "the variable is blank".
78
+ function isAbsentMember(member: unknown): boolean {
79
+ return isNullish(member) || member === "";
80
+ }
81
+
82
+ // The membership operators (`in` / `not_in`, and `contains` against an array
83
+ // variable) need a real list and used to answer a CONSTANT without one —
84
+ // `in` false for every row, `not_in` true for every row, no warning (#225).
85
+ //
86
+ // Two right-hand-side shapes reach them without being `Array.isArray`, and both
87
+ // are the natural way to author a membership test now that a `{{ref}}` on the
88
+ // right-hand side resolves (#217):
89
+ //
90
+ // value: "{{selected}}" a reference to a multi-select variable, whose flat
91
+ // value is a JSON-encoded string ('["a","b"]' — see
92
+ // `decodeArrayValue`), so the ref interpolates to a
93
+ // string and `Array.isArray` is false.
94
+ // value: ["{{selected}}"] what Studio's condition editor emits: it splits the
95
+ // value field on commas, so the reference lands as
96
+ // the single member of a one-member array. That one
97
+ // IS an array, and used to reach the comparison as a
98
+ // list holding one JSON string — equally constant.
99
+ //
100
+ // So a member list is built by decoding the value itself AND each of its
101
+ // members, flattening one level. Only one level: nothing authorable nests
102
+ // deeper, and a deep flatten would silently merge a shape nobody wrote.
103
+ //
104
+ // `value: []` keeps its documented constants (`in` false / `not_in` true) — an
105
+ // empty Studio value field yields it, and an empty list legitimately has no
106
+ // members. So does a reference that resolves to nothing: an unresolved `{{ref}}`
107
+ // interpolates to the empty string (see `interpolateRefs`), and "not written
108
+ // yet" means "no members", not "a member that is the empty string".
109
+ //
110
+ // Anything else scalar (`in` against `"male"`) is an authoring mistake with no
111
+ // correct answer. It reads as a ONE-member list — the only reading that is not a
112
+ // silent constant, and what `in: "male"` plainly means — and warns, because the
113
+ // evaluator returns `boolean` and `renderWhen` has no third state, so a warning
114
+ // is the loudest a runtime can be. No Studio-authored payload can produce this
115
+ // shape (its editor always emits an array), so nothing that evaluates correctly
116
+ // today changes.
117
+ function toMemberList(value: unknown, operator: string): unknown[] {
118
+ const decoded = decodeArrayValue(value);
119
+ if (Array.isArray(decoded)) {
120
+ return decoded
121
+ .flatMap((member) => {
122
+ const inner = decodeArrayValue(member);
123
+ return Array.isArray(inner) ? inner : [inner];
124
+ })
125
+ .filter((member) => !isAbsentMember(member));
126
+ }
127
+ if (isAbsentMember(decoded)) return [];
128
+ console.warn(
129
+ `[onboarding] condition operator "${operator}" needs a list on its right-hand side, ` +
130
+ `got ${typeof decoded} ${JSON.stringify(decoded)}. Treating it as a single-member list. ` +
131
+ `Author an array (or a {{ref}} to a multi-select variable) instead.`
132
+ );
133
+ return [decoded];
134
+ }
135
+
136
+ // Members compare stringified. A decoded JSON array keeps its members typed, and
137
+ // `Repeat` keeps a numeric row field numeric on purpose (`repeatScope.buildRowFlat`,
138
+ // so `gt` compares numerically), so `1` and `"1"` have to be the same member —
139
+ // otherwise `not_in(1, [1, 2])` is true. Shared with the `contains` array branch,
140
+ // which coerced neither side, so the two operators would otherwise disagree about
141
+ // the same data.
142
+ function includesMember(members: unknown[], target: unknown): boolean {
143
+ const needle = String(target);
144
+ return members.some((member) => String(member) === needle);
145
+ }
146
+
45
147
  export function evaluateLeaf(condition: LeafCondition, variables: Record<string, unknown>): boolean {
46
148
  const raw = decodeArrayValue(variables[condition.variable]);
47
- const { operator, value } = condition;
149
+ const { operator } = condition;
150
+ const value = interpolateRefs(condition.value, variables) as typeof condition.value;
48
151
 
49
152
  switch (operator) {
50
153
  case "eq":
@@ -61,12 +164,12 @@ export function evaluateLeaf(condition: LeafCondition, variables: Record<string,
61
164
  return coerceToNumber(raw) <= coerceToNumber(value);
62
165
  case "contains":
63
166
  return Array.isArray(raw)
64
- ? raw.includes(value)
167
+ ? includesMember(raw, value)
65
168
  : String(raw).includes(String(value));
66
169
  case "in":
67
- return Array.isArray(value) ? value.includes(String(raw)) : false;
170
+ return includesMember(toMemberList(value, operator), raw);
68
171
  case "not_in":
69
- return Array.isArray(value) ? !value.includes(String(raw)) : true;
172
+ return !includesMember(toMemberList(value, operator), raw);
70
173
  case "is_empty":
71
174
  return isEmpty(raw);
72
175
  case "is_not_empty":
package/src/index.ts CHANGED
@@ -102,6 +102,29 @@ export {
102
102
  formatUnknownElementKeys,
103
103
  } from "./screens/unknownKeys";
104
104
  export type { UnknownElementKey } from "./screens/unknownKeys";
105
+ // Forward compatibility for element TYPES (#209): an element type published
106
+ // after this app shipped is OMITTED rather than failing the whole screen.
107
+ // `KNOWN_ELEMENT_TYPES` is the capability list of what this build can render.
108
+ export {
109
+ KNOWN_ELEMENT_TYPES,
110
+ dropUnknownElementTypes,
111
+ dropUnknownElementTypesInStep,
112
+ collectUnknownElementTypes,
113
+ collectUnknownElementTypesInSteps,
114
+ formatUnknownElementTypes,
115
+ } from "./screens/unknownElementTypes";
116
+ export type { UnknownElementType } from "./screens/unknownElementTypes";
117
+ // The whole render-boundary decision in one pure call: what to parse, what to
118
+ // log, and whether the renderer must supply its own way off the screen — a
119
+ // ComposableScreen authors its CTA INSIDE the element tree, so a strip can take
120
+ // it and leave a screen nobody can leave. `deriveElementTypeNames` is how a
121
+ // rendering package keys the strip on ITS OWN element union instead of this
122
+ // one's: what draws has to decide what is kept, and the two packages' installed
123
+ // versions can differ.
124
+ export { resolveRenderableStep } from "./screens/resolveRenderableStep";
125
+ export type { RenderableStep } from "./screens/resolveRenderableStep";
126
+ export { hasCompletingAction } from "./screens/completingActions";
127
+ export { deriveElementTypeNames } from "./screens/elementTypeRegistry";
105
128
  // Hooks and providers
106
129
  export * from "./infra";
107
130
  // Navigation adapter (dependency-injected navigation)
@@ -121,6 +121,10 @@ interface OnboardingProviderProps {
121
121
  */
122
122
  client?: OnboardingStudioClient;
123
123
  locale?: string;
124
+ /**
125
+ * Static audience params (build-time facts). Merged under the user-property
126
+ * store and read once, when the onboarding is served — see `useAudienceParams`.
127
+ */
124
128
  customAudienceParams?: Record<string, any>;
125
129
  /**
126
130
  * Map of named handlers invokable from ComposableScreen Button `actions`
@@ -162,39 +166,70 @@ interface OnboardingProviderProps {
162
166
  productRefs?: ProductRef[];
163
167
  }
164
168
 
169
+ /**
170
+ * The audience params this onboarding is served with: the `customAudienceParams`
171
+ * prop merged with the user-property store, resolved ONCE when the store is
172
+ * ready and then pinned for the life of the provider. `null` while hydrating.
173
+ *
174
+ * Audience resolution happens at serve time and a served onboarding is frozen:
175
+ * a `setUserProperty` during the flow does not change these, so it cannot
176
+ * re-key the query, refetch, or swap the onboarding under the user. It applies
177
+ * to the next serve (next mount / launch). `PaywallProvider` deliberately keeps
178
+ * following the store — a paywall is served later, at `register(moment)`.
179
+ *
180
+ * So the two CAN resolve against different properties for the same user: a
181
+ * property written mid-flow reaches a paywall served afterwards (including a
182
+ * paywall step later in this same onboarding) but not the onboarding around it.
183
+ * That is intended, not a gap — it is the "set the property, then register the
184
+ * moment" model — and both still read ONE store; they differ only in when they
185
+ * read it.
186
+ */
187
+ const useAudienceParams = (
188
+ customAudienceParams: Record<string, any>
189
+ ): Record<string, string> | null => {
190
+ const { properties, status } = useUserProperties();
191
+ // State rather than a ref: a pin taken in a render React later discards is
192
+ // discarded with it, so the served params always come from a committed render.
193
+ const [pinned, setPinned] = useState<Record<string, string> | null>(null);
194
+ if (pinned === null && status === "ready") {
195
+ const resolved = resolveEffectiveParams(customAudienceParams, properties);
196
+ setPinned(resolved);
197
+ return resolved;
198
+ }
199
+ return pinned;
200
+ };
201
+
165
202
  interface OnboardingDataGateProps {
166
203
  client: OnboardingStudioClient;
167
204
  locale: string;
168
- customAudienceParams: Record<string, any>;
205
+ /** From `useAudienceParams`; `null` disables the query until the store is ready. */
206
+ audienceParams: Record<string, string> | null;
169
207
  setOnboarding: (onboarding: Onboarding<OnboardingStepType>) => void;
170
208
  fontsFallback?: React.ReactNode;
171
209
  children: React.ReactNode;
172
210
  }
173
211
 
212
+ /**
213
+ * Fetches the onboarding and holds the subtree until it is there. The query is
214
+ * disabled while `audienceParams` is `null` (store still hydrating); the gate
215
+ * shows `fontsFallback` meanwhile, as it already does while the payload loads.
216
+ */
174
217
  const OnboardingDataGate = ({
175
218
  client,
176
219
  locale,
177
- customAudienceParams,
220
+ audienceParams,
178
221
  setOnboarding,
179
222
  fontsFallback,
180
223
  children,
181
224
  }: OnboardingDataGateProps) => {
182
- // Same merge the paywall provider does, for the same reason: one store feeds
183
- // both waterfalls, so an onboarding audience and a paywall audience can no
184
- // longer disagree about the same user. See `resolveEffectiveParams`.
185
- const { properties, status: propertiesStatus } = useUserProperties();
186
- const params = useMemo(
187
- () => resolveEffectiveParams(customAudienceParams, properties),
188
- [customAudienceParams, properties]
189
- );
190
-
191
225
  const { data, error } = useQuery<Onboarding<OnboardingStepType>>({
192
- ...getOnboardingQuery<OnboardingStepType>(client, locale, params, setOnboarding),
193
- // Held until the store hydrates — otherwise the first fetch of a cold launch
194
- // is audience-matched against an empty property map. This gate renders
195
- // `fontsFallback`, the state this gate already shows while the payload
196
- // loads, so nothing new appears on screen.
197
- enabled: propertiesStatus === "ready",
226
+ ...getOnboardingQuery<OnboardingStepType>(
227
+ client,
228
+ locale,
229
+ audienceParams ?? {},
230
+ setOnboarding
231
+ ),
232
+ enabled: audienceParams !== null,
198
233
  });
199
234
 
200
235
  // Background asset preload: once the payload is available, warm every remote
@@ -220,7 +255,11 @@ const OnboardingDataGate = ({
220
255
  }, [data]);
221
256
 
222
257
  if (error) throw error;
223
- if (!data) return <>{fontsFallback ?? null}</>;
258
+ // Both checks, not just `!data`: a disabled query still returns cached data for
259
+ // its key, and the unpinned key (`{}`) is also a legitimate pinned one. Holding
260
+ // on `audienceParams` makes "children mount only once the params are pinned"
261
+ // structural, so nothing below can ever fetch under un-pinned params.
262
+ if (audienceParams === null || !data) return <>{fontsFallback ?? null}</>;
224
263
 
225
264
  return (
226
265
  <FontLoaderGate fonts={data.fonts} fallback={fontsFallback}>
@@ -252,6 +291,12 @@ export const OnboardingProvider = ({
252
291
  const client = resolveProviderClient(clientProp, OnboardingStudio.getClient());
253
292
  if (!client) throw new Error(MISSING_CLIENT_MESSAGE);
254
293
 
294
+ // Resolved here, once, and handed to BOTH the context (read by the step hooks)
295
+ // and the data gate — so they build the same query. Resolving in the gate
296
+ // alone, as before, left the hooks with the raw prop: a second fetch under a
297
+ // different key, resolved without the user's properties, was what rendered.
298
+ const audienceParams = useAudienceParams(customAudienceParams);
299
+
255
300
  const [activeStep, setActiveStep] = useState({
256
301
  number: 0,
257
302
  displayProgressHeader: false,
@@ -340,7 +385,9 @@ export const OnboardingProvider = ({
340
385
  setHeaderHeight,
341
386
  client,
342
387
  locale,
343
- customAudienceParams,
388
+ // The raw prop is never observed: the data gate holds `children` until
389
+ // the params are pinned, and everything reading this context is a child.
390
+ customAudienceParams: audienceParams ?? customAudienceParams,
344
391
  onboarding,
345
392
  setOnboarding,
346
393
  variables,
@@ -355,7 +402,7 @@ export const OnboardingProvider = ({
355
402
  <OnboardingDataGate
356
403
  client={client}
357
404
  locale={locale}
358
- customAudienceParams={customAudienceParams}
405
+ audienceParams={audienceParams}
359
406
  setOnboarding={setOnboarding}
360
407
  fontsFallback={fontsFallback}
361
408
  >
@@ -782,6 +782,84 @@ export const onboardingExample = {
782
782
  marginVertical: 4,
783
783
  },
784
784
  },
785
+ // Expression stdlib demo. Every function runs at PRESS time (the
786
+ // engine's only call site is a `setVariable` action), so a
787
+ // computed date or an assembled sentence is written into a
788
+ // variable here and then plainly interpolated by the Texts below.
789
+ {
790
+ id: "stdlib-compute",
791
+ type: "Button",
792
+ props: {
793
+ label: "Compute my plan",
794
+ variant: "outlined",
795
+ marginVertical: 8,
796
+ actions: [
797
+ {
798
+ type: "setVariable",
799
+ name: "goalDate",
800
+ // `"now"` is the same sentinel DatePicker accepts, and the
801
+ // format spec is the DatePicker `format` prop vocabulary.
802
+ value: 'format(addDays("now", 90), "medium")',
803
+ valueMode: "expression",
804
+ },
805
+ {
806
+ type: "setVariable",
807
+ name: "goalSentence",
808
+ // Grammatical listing over the CheckboxGroup member labels.
809
+ value: "list({{goals}})",
810
+ valueMode: "expression",
811
+ },
812
+ {
813
+ type: "setVariable",
814
+ name: "goalCount",
815
+ value: 'count({{goals}}) + " " + plural(count({{goals}}), "goal", "goals")',
816
+ valueMode: "expression",
817
+ },
818
+ {
819
+ type: "setVariable",
820
+ name: "weeklyPace",
821
+ // Rounds to nearest — not trunc — and holds the result
822
+ // inside an inclusive range. Over the slider's
823
+ // 0..1 / step-0.1 grid the reachable outputs are
824
+ // 1,1,1,1,2,2,2,3,3,3,3 — a 4/3/4 split, the most even
825
+ // available for eleven positions across three values, so
826
+ // no stretch of the slider is inert.
827
+ //
828
+ // The multiplier is chosen so the RAW value overshoots
829
+ // the bounds a little and not a lot: raw runs
830
+ // 0,0,1,1,2,2,2,3,3,4,4, so `clamp` is OBSERVABLE at both
831
+ // ends (0 -> 1 twice, 4 -> 3 twice). That is the whole
832
+ // constraint — an expression whose raw range already sits
833
+ // inside 1..3, like `round(1 + {{intensity}} * 2)`, makes
834
+ // clamp change no value at all and demonstrates an inert
835
+ // function; one that overshoots hard, like `* 5`, returns
836
+ // 3 at six of the eleven positions and leaves the upper
837
+ // half of the slider dead.
838
+ //
839
+ // What this shape does not cover: no reachable position
840
+ // lands on an exact .5 tie, so round-half-up is pinned in
841
+ // `expression.test.ts` rather than here. A trunc
842
+ // regression is still caught at 0.4 (1.6 -> 2, not 1) and
843
+ // 0.7 (2.8 -> 3, not 2).
844
+ value: "clamp(round({{intensity}} * 4), 1, 3)",
845
+ valueMode: "expression",
846
+ },
847
+ ],
848
+ },
849
+ },
850
+ {
851
+ id: "stdlib-display",
852
+ type: "Text",
853
+ props: {
854
+ content:
855
+ "{{goalCount}}: {{goalSentence}} — by {{goalDate}}, {{weeklyPace}}x / week",
856
+ mode: "expression",
857
+ fontSize: 14,
858
+ textAlign: "center",
859
+ opacity: 0.6,
860
+ marginVertical: 4,
861
+ },
862
+ },
785
863
  {
786
864
  id: "hero-date-picker",
787
865
  type: "DatePicker",
@@ -0,0 +1,108 @@
1
+ /**
2
+ * "Can the user still get off this screen?" — the guard the unknown-element
3
+ * strip needs (#209).
4
+ *
5
+ * A ComposableScreen's CTA is authored INSIDE the element tree.
6
+ * `ComposableScreenRenderer` passes no `button` to `OnboardingTemplate`, so
7
+ * `runActions` — reached only from something the user can press in that tree —
8
+ * is the single path to `onContinue`. Drop the element that happens to be the
9
+ * screen's root container and the payload still parses, to `elements: []`: a
10
+ * blank screen with no CTA, and on a `displayProgressHeader: false` step no back
11
+ * chevron either. Stripping would then have replaced a throw that at least
12
+ * reached `componentDidCatch` with a silent dead end, which is worse.
13
+ *
14
+ * So the renderer asks this before it renders a stripped tree, and supplies its
15
+ * own escape when the answer is no — the same choice the two existing
16
+ * boundaries make: an unknown *step* type renders a Continue button
17
+ * (`OnboardingPage`), and a paywall whose elements fail to parse calls
18
+ * `onContinue()` "so the user is not trapped" (`Pages/Paywall/Renderer`).
19
+ *
20
+ * WHAT COUNTS. `runActions` calls `onContinue` for exactly two actions —
21
+ * `"continue"` and `{type:"dismiss"}` — so those two, wherever a press can
22
+ * reach them, are the whole definition. Everything else (`setVariable`,
23
+ * `presentPaywall`, `custom`) leaves the user on the screen as far as this SDK
24
+ * can tell, and is not counted.
25
+ *
26
+ * The walk deliberately errs toward "no": an unrecognised action shape, or a
27
+ * `continue` somewhere the runtime would not actually run it, reads as no way
28
+ * forward. A redundant escape CTA on an already-degraded screen is a cosmetic
29
+ * cost; a missed one is the trap this exists to close.
30
+ *
31
+ * NOT CONSIDERED: `renderWhen`. A CTA the author gated behind a condition may
32
+ * be hidden at runtime, but that is authored intent evaluated against live
33
+ * variables, not something a static payload walk can or should second-guess.
34
+ */
35
+
36
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
37
+ typeof v === "object" && v !== null && !Array.isArray(v);
38
+
39
+ /**
40
+ * Element types whose renderer owns its own press handling, so the generic
41
+ * `onPress` from `BaseBoxProps` is never wired for them.
42
+ *
43
+ * Mirrors `PRESS_HANDLED_TYPES` in `renderElement.tsx` — the UI package cannot
44
+ * be imported here, so the two lists are held equal by a source-level test in
45
+ * `packages/onboarding-ui/src/UI/Runtime/__tests__/unknownElementTypes.test.ts`.
46
+ * Counting an ignored `onPress` as a way forward would leave a user trapped on a
47
+ * screen whose only remaining "CTA" the runtime never dispatches.
48
+ */
49
+ const PRESS_HANDLED_TYPES: ReadonlySet<string> = new Set([
50
+ "Button",
51
+ "RadioGroup",
52
+ "CheckboxGroup",
53
+ "DatePicker",
54
+ "Input",
55
+ "WheelPicker",
56
+ "DrawingPad",
57
+ "Slider",
58
+ ]);
59
+
60
+ /**
61
+ * One action, or any action nested in one of its branch lists
62
+ * (`purchase.onSuccess`, `restore.onNothingToRestore`, …), completes the screen.
63
+ *
64
+ * Branch lists are found by shape rather than by name, so a branch added to
65
+ * `purchase`/`restore` later is covered without a change here.
66
+ */
67
+ const isCompletingAction = (action: unknown): boolean => {
68
+ // `ButtonActionSchema` declares continue as the string literal, not an
69
+ // object: `{type:"continue"}` is not an action the runtime runs.
70
+ if (action === "continue") return true;
71
+ if (!isRecord(action)) return false;
72
+ if (action.type === "dismiss") return true;
73
+ return Object.values(action).some(
74
+ (value) => Array.isArray(value) && value.some(isCompletingAction)
75
+ );
76
+ };
77
+
78
+ const nodeCanComplete = (node: unknown): boolean => {
79
+ if (!isRecord(node)) return false;
80
+ const props = isRecord(node.props) ? node.props : undefined;
81
+ if (props) {
82
+ if (props.actions != null) {
83
+ // `Button` reads `actions ?? (action === "continue" ? …)`, so a present
84
+ // `actions` shadows the deprecated shorthand — even when it is empty.
85
+ if (Array.isArray(props.actions) && props.actions.some(isCompletingAction)) return true;
86
+ } else if (props.action === "continue") {
87
+ return true;
88
+ }
89
+ if (
90
+ Array.isArray(props.onPress) &&
91
+ !PRESS_HANDLED_TYPES.has(String(node.type)) &&
92
+ props.onPress.some(isCompletingAction)
93
+ ) {
94
+ return true;
95
+ }
96
+ }
97
+ return Array.isArray(node.children) && node.children.some(nodeCanComplete);
98
+ };
99
+
100
+ /**
101
+ * Whether anything in this element tree can complete the screen.
102
+ *
103
+ * Pure, linear, and total: any malformed input (non-array, `null` nodes,
104
+ * non-record props) answers `false` rather than throwing, because it runs on a
105
+ * payload that has not been parsed yet.
106
+ */
107
+ export const hasCompletingAction = (elements: unknown): boolean =>
108
+ Array.isArray(elements) && elements.some(nodeCanComplete);
@@ -0,0 +1,88 @@
1
+ import { UIElementSchema } from "./types";
2
+
3
+ /**
4
+ * The element `type` names this SDK build knows, and the key sets each of them
5
+ * accepts — read off `UIElementSchema` itself at runtime rather than hardcoded,
6
+ * so nothing here can drift as elements are added.
7
+ *
8
+ * Two consumers, deliberately sharing one derivation: `unknownKeys.ts` (which
9
+ * keys it needs) and `unknownElementTypes.ts` (which *types* exist at all).
10
+ * They used to be able to disagree about what "known" means, which for a
11
+ * forward-compatibility strip is not a cosmetic risk: a type the strip thinks
12
+ * is unknown is a type the app silently refuses to render.
13
+ */
14
+ export type ElementKeySets = { topLevel: Set<string>; props: Set<string> };
15
+
16
+ const zdef = (schema: any): any => schema?._zod?.def ?? schema?._def;
17
+
18
+ // Every string literal a `type` field can hold. Variants use `z.literal("X")`;
19
+ // a `z.union([literal, literal])` is tolerated for robustness.
20
+ const literalsOf = (schema: any): string[] => {
21
+ const def = zdef(schema);
22
+ if (!def) return [];
23
+ if (def.type === "literal") {
24
+ const values = def.values ?? (def.value !== undefined ? [def.value] : []);
25
+ return values.filter((v: unknown): v is string => typeof v === "string");
26
+ }
27
+ if (def.type === "union") return (def.options ?? []).flatMap(literalsOf);
28
+ return [];
29
+ };
30
+
31
+ /**
32
+ * The derivation itself, over ANY element union — this package's, or another
33
+ * package's re-declared mirror of it.
34
+ *
35
+ * Kept schema-agnostic because the onboarding-ui package has to derive its own
36
+ * capability set rather than inherit this one's: it re-declares its own
37
+ * `UIElementSchema`, that mirror is what actually parses and renders an element
38
+ * tree, and the peer-dependency range between the two packages lets a host
39
+ * resolve different versions of them. Sharing the mechanism but not the answer
40
+ * is the point — one place that knows how to read a discriminated union, two
41
+ * honest answers about two schemas.
42
+ */
43
+ const buildElementRegistry = (schema: unknown): Map<string, ElementKeySets> => {
44
+ const built = new Map<string, ElementKeySets>();
45
+ try {
46
+ const lazyDef = zdef(schema);
47
+ const union = typeof lazyDef?.getter === "function" ? lazyDef.getter() : schema;
48
+ const options = zdef(union)?.options ?? [];
49
+ for (const option of options) {
50
+ const shape = zdef(option)?.shape;
51
+ if (!shape) continue;
52
+ const propsShape = zdef(shape.props)?.shape ?? {};
53
+ const keySets: ElementKeySets = {
54
+ topLevel: new Set(Object.keys(shape)),
55
+ props: new Set(Object.keys(propsShape)),
56
+ };
57
+ for (const typeName of literalsOf(shape.type)) built.set(typeName, keySets);
58
+ }
59
+ } catch {
60
+ // fall through to whatever was built before the failure
61
+ }
62
+ return built;
63
+ };
64
+
65
+ /**
66
+ * Every element `type` a given element union declares. EMPTY means "could not
67
+ * tell" — zod internals moved, or this is not an element union — and every
68
+ * caller must read it as "learn nothing" rather than "reject everything", which
69
+ * would blank every screen in every app.
70
+ */
71
+ export const deriveElementTypeNames = (schema: unknown): ReadonlySet<string> =>
72
+ new Set(buildElementRegistry(schema).keys());
73
+
74
+ let registry: Map<string, ElementKeySets> | null = null;
75
+
76
+ /**
77
+ * Built once, lazily, from THIS package's schema. Any shape change in zod's
78
+ * internals degrades to an EMPTY registry, read as "learn nothing" — this is a
79
+ * diagnostic and a forward-compat aid, it must never be able to break rendering.
80
+ */
81
+ export const getElementRegistry = (): Map<string, ElementKeySets> => {
82
+ if (registry) return registry;
83
+ registry = buildElementRegistry(UIElementSchema);
84
+ return registry;
85
+ };
86
+
87
+ /** Every element `type` this build can parse. Empty means "could not tell". */
88
+ export const getKnownElementTypes = (): ReadonlySet<string> => new Set(getElementRegistry().keys());
@@ -0,0 +1,59 @@
1
+ import { hasCompletingAction } from "./completingActions";
2
+ import {
3
+ collectUnknownElementTypes,
4
+ dropUnknownElementTypesInStep,
5
+ type UnknownElementType,
6
+ } from "./unknownElementTypes";
7
+
8
+ /**
9
+ * The whole render-boundary decision for element-type forward compatibility
10
+ * (#209): what to parse, what to log, and whether the renderer must supply its
11
+ * own way off the screen.
12
+ *
13
+ * It lives here rather than in the renderer because the onboarding-ui package's
14
+ * vitest runs in plain Node and cannot import `react-native` — logic decided
15
+ * there is only assertable at source level, and the escape decision is the part
16
+ * of this feature that must not be wrong.
17
+ */
18
+ export type RenderableStep<T> = {
19
+ /**
20
+ * The step to parse and render. The SAME reference as the input when nothing
21
+ * was stripped, so the common path allocates nothing and stays `useMemo`-stable.
22
+ */
23
+ step: T;
24
+ /** The elements omitted, for the log. Empty when nothing was stripped. */
25
+ omitted: UnknownElementType[];
26
+ /**
27
+ * The strip left nothing in the tree that can complete the screen, so the
28
+ * renderer must supply an escape of its own — otherwise the user sits on a
29
+ * screen with no CTA and, on a `displayProgressHeader: false` step, no back
30
+ * chevron: the dead end #209 exists to close, re-created silently.
31
+ *
32
+ * Only ever true when something WAS stripped. An authored screen with no way
33
+ * forward is an authoring bug (and the host may advance it another way, e.g. a
34
+ * custom action that navigates); injecting a CTA into shipped screens that
35
+ * have nothing to do with an unknown element type is not this feature's call.
36
+ */
37
+ needsEscape: boolean;
38
+ };
39
+
40
+ /**
41
+ * @param step A step as fetched, unparsed.
42
+ * @param known The element types the CALLER can render — the renderer's own
43
+ * capability, not this package's schema. The two are separate packages with a
44
+ * peer-dependency range between them, so their versions can legitimately
45
+ * differ, and it is what draws that must decide what is kept. An empty set
46
+ * means "could not tell" and strips nothing.
47
+ */
48
+ export const resolveRenderableStep = <T>(step: T, known?: ReadonlySet<string>): RenderableStep<T> => {
49
+ const renderable = dropUnknownElementTypesInStep(step, known);
50
+ if (renderable === step) return { step, omitted: [], needsEscape: false };
51
+
52
+ const authoredElements = (step as { payload?: { elements?: unknown } })?.payload?.elements;
53
+ const renderableElements = (renderable as { payload?: { elements?: unknown } })?.payload?.elements;
54
+ return {
55
+ step: renderable,
56
+ omitted: collectUnknownElementTypes(authoredElements, "elements", known),
57
+ needsEscape: !hasCompletingAction(renderableElements),
58
+ };
59
+ };