@velion-la/onboarding-sdk-react-native 1.0.0-beta.5 → 1.0.0-beta.7

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 (182) hide show
  1. package/README.md +85 -0
  2. package/lib/commonjs/core/VelionOnboarding.js +296 -15
  3. package/lib/commonjs/core/VelionOnboarding.js.map +1 -1
  4. package/lib/commonjs/core/retryStepCopy.js +43 -0
  5. package/lib/commonjs/core/retryStepCopy.js.map +1 -0
  6. package/lib/commonjs/core/routingCommands.js +62 -0
  7. package/lib/commonjs/core/routingCommands.js.map +1 -0
  8. package/lib/commonjs/core/sessionStateMapper.js +63 -0
  9. package/lib/commonjs/core/sessionStateMapper.js.map +1 -1
  10. package/lib/commonjs/i18n/strings/en.js +28 -0
  11. package/lib/commonjs/i18n/strings/en.js.map +1 -1
  12. package/lib/commonjs/i18n/strings/es.js +28 -0
  13. package/lib/commonjs/i18n/strings/es.js.map +1 -1
  14. package/lib/commonjs/index.js.map +1 -1
  15. package/lib/commonjs/steps/AddressInfoStep.js +30 -18
  16. package/lib/commonjs/steps/AddressInfoStep.js.map +1 -1
  17. package/lib/commonjs/steps/DocumentsOcrStep.js +4 -0
  18. package/lib/commonjs/steps/DocumentsOcrStep.js.map +1 -1
  19. package/lib/commonjs/steps/EmailContactStep.js +5 -0
  20. package/lib/commonjs/steps/EmailContactStep.js.map +1 -1
  21. package/lib/commonjs/steps/EmailOtpStep.js +5 -0
  22. package/lib/commonjs/steps/EmailOtpStep.js.map +1 -1
  23. package/lib/commonjs/steps/FaceMatchStep.js +16 -13
  24. package/lib/commonjs/steps/FaceMatchStep.js.map +1 -1
  25. package/lib/commonjs/steps/HumanBasicInfoStep.js +12 -4
  26. package/lib/commonjs/steps/HumanBasicInfoStep.js.map +1 -1
  27. package/lib/commonjs/steps/HumanExtendedInfoStep.js +15 -8
  28. package/lib/commonjs/steps/HumanExtendedInfoStep.js.map +1 -1
  29. package/lib/commonjs/steps/LegalBasicInfoStep.js +13 -6
  30. package/lib/commonjs/steps/LegalBasicInfoStep.js.map +1 -1
  31. package/lib/commonjs/steps/LegalExtendedInfoStep.js +9 -2
  32. package/lib/commonjs/steps/LegalExtendedInfoStep.js.map +1 -1
  33. package/lib/commonjs/steps/PhoneContactStep.js +5 -0
  34. package/lib/commonjs/steps/PhoneContactStep.js.map +1 -1
  35. package/lib/commonjs/steps/PhoneOtpStep.js +5 -0
  36. package/lib/commonjs/steps/PhoneOtpStep.js.map +1 -1
  37. package/lib/commonjs/steps/SwornDeclarationStep.js +16 -6
  38. package/lib/commonjs/steps/SwornDeclarationStep.js.map +1 -1
  39. package/lib/commonjs/steps/TaxInfoStep.js +10 -3
  40. package/lib/commonjs/steps/TaxInfoStep.js.map +1 -1
  41. package/lib/commonjs/steps/TermsAndConditionsStep.js +7 -0
  42. package/lib/commonjs/steps/TermsAndConditionsStep.js.map +1 -1
  43. package/lib/commonjs/steps/_shared.js +21 -0
  44. package/lib/commonjs/steps/_shared.js.map +1 -1
  45. package/lib/commonjs/types/index.js +36 -1
  46. package/lib/commonjs/types/index.js.map +1 -1
  47. package/lib/commonjs/ui/StepShell.js +10 -2
  48. package/lib/commonjs/ui/StepShell.js.map +1 -1
  49. package/lib/commonjs/ui/VelionOnboardingScreen.js +25 -5
  50. package/lib/commonjs/ui/VelionOnboardingScreen.js.map +1 -1
  51. package/lib/commonjs/ui/icons/StepIcon.js.map +1 -1
  52. package/lib/commonjs/ui/primitives/BackButton.js +75 -0
  53. package/lib/commonjs/ui/primitives/BackButton.js.map +1 -0
  54. package/lib/commonjs/ui/primitives/index.js +7 -0
  55. package/lib/commonjs/ui/primitives/index.js.map +1 -1
  56. package/lib/module/core/VelionOnboarding.js +297 -16
  57. package/lib/module/core/VelionOnboarding.js.map +1 -1
  58. package/lib/module/core/retryStepCopy.js +39 -0
  59. package/lib/module/core/retryStepCopy.js.map +1 -0
  60. package/lib/module/core/routingCommands.js +57 -0
  61. package/lib/module/core/routingCommands.js.map +1 -0
  62. package/lib/module/core/sessionStateMapper.js +61 -0
  63. package/lib/module/core/sessionStateMapper.js.map +1 -1
  64. package/lib/module/i18n/strings/en.js +28 -0
  65. package/lib/module/i18n/strings/en.js.map +1 -1
  66. package/lib/module/i18n/strings/es.js +28 -0
  67. package/lib/module/i18n/strings/es.js.map +1 -1
  68. package/lib/module/index.js.map +1 -1
  69. package/lib/module/steps/AddressInfoStep.js +31 -19
  70. package/lib/module/steps/AddressInfoStep.js.map +1 -1
  71. package/lib/module/steps/DocumentsOcrStep.js +4 -0
  72. package/lib/module/steps/DocumentsOcrStep.js.map +1 -1
  73. package/lib/module/steps/EmailContactStep.js +5 -0
  74. package/lib/module/steps/EmailContactStep.js.map +1 -1
  75. package/lib/module/steps/EmailOtpStep.js +5 -0
  76. package/lib/module/steps/EmailOtpStep.js.map +1 -1
  77. package/lib/module/steps/FaceMatchStep.js +16 -13
  78. package/lib/module/steps/FaceMatchStep.js.map +1 -1
  79. package/lib/module/steps/HumanBasicInfoStep.js +12 -4
  80. package/lib/module/steps/HumanBasicInfoStep.js.map +1 -1
  81. package/lib/module/steps/HumanExtendedInfoStep.js +16 -9
  82. package/lib/module/steps/HumanExtendedInfoStep.js.map +1 -1
  83. package/lib/module/steps/LegalBasicInfoStep.js +14 -7
  84. package/lib/module/steps/LegalBasicInfoStep.js.map +1 -1
  85. package/lib/module/steps/LegalExtendedInfoStep.js +10 -3
  86. package/lib/module/steps/LegalExtendedInfoStep.js.map +1 -1
  87. package/lib/module/steps/PhoneContactStep.js +5 -0
  88. package/lib/module/steps/PhoneContactStep.js.map +1 -1
  89. package/lib/module/steps/PhoneOtpStep.js +5 -0
  90. package/lib/module/steps/PhoneOtpStep.js.map +1 -1
  91. package/lib/module/steps/SwornDeclarationStep.js +18 -6
  92. package/lib/module/steps/SwornDeclarationStep.js.map +1 -1
  93. package/lib/module/steps/TaxInfoStep.js +11 -4
  94. package/lib/module/steps/TaxInfoStep.js.map +1 -1
  95. package/lib/module/steps/TermsAndConditionsStep.js +7 -0
  96. package/lib/module/steps/TermsAndConditionsStep.js.map +1 -1
  97. package/lib/module/steps/_shared.js +19 -0
  98. package/lib/module/steps/_shared.js.map +1 -1
  99. package/lib/module/types/index.js +38 -1
  100. package/lib/module/types/index.js.map +1 -1
  101. package/lib/module/ui/StepShell.js +10 -2
  102. package/lib/module/ui/StepShell.js.map +1 -1
  103. package/lib/module/ui/VelionOnboardingScreen.js +25 -5
  104. package/lib/module/ui/VelionOnboardingScreen.js.map +1 -1
  105. package/lib/module/ui/icons/StepIcon.js.map +1 -1
  106. package/lib/module/ui/primitives/BackButton.js +71 -0
  107. package/lib/module/ui/primitives/BackButton.js.map +1 -0
  108. package/lib/module/ui/primitives/index.js +1 -0
  109. package/lib/module/ui/primitives/index.js.map +1 -1
  110. package/lib/typescript/core/VelionOnboarding.d.ts +56 -2
  111. package/lib/typescript/core/VelionOnboarding.d.ts.map +1 -1
  112. package/lib/typescript/core/retryStepCopy.d.ts +27 -0
  113. package/lib/typescript/core/retryStepCopy.d.ts.map +1 -0
  114. package/lib/typescript/core/routingCommands.d.ts +39 -0
  115. package/lib/typescript/core/routingCommands.d.ts.map +1 -0
  116. package/lib/typescript/core/sessionStateMapper.d.ts +20 -1
  117. package/lib/typescript/core/sessionStateMapper.d.ts.map +1 -1
  118. package/lib/typescript/i18n/strings/en.d.ts.map +1 -1
  119. package/lib/typescript/i18n/strings/es.d.ts +25 -0
  120. package/lib/typescript/i18n/strings/es.d.ts.map +1 -1
  121. package/lib/typescript/index.d.ts +1 -1
  122. package/lib/typescript/index.d.ts.map +1 -1
  123. package/lib/typescript/steps/AddressInfoStep.d.ts.map +1 -1
  124. package/lib/typescript/steps/DocumentsOcrStep.d.ts.map +1 -1
  125. package/lib/typescript/steps/EmailContactStep.d.ts.map +1 -1
  126. package/lib/typescript/steps/EmailOtpStep.d.ts.map +1 -1
  127. package/lib/typescript/steps/FaceMatchStep.d.ts.map +1 -1
  128. package/lib/typescript/steps/HumanBasicInfoStep.d.ts.map +1 -1
  129. package/lib/typescript/steps/HumanExtendedInfoStep.d.ts.map +1 -1
  130. package/lib/typescript/steps/LegalBasicInfoStep.d.ts.map +1 -1
  131. package/lib/typescript/steps/LegalExtendedInfoStep.d.ts.map +1 -1
  132. package/lib/typescript/steps/PhoneContactStep.d.ts.map +1 -1
  133. package/lib/typescript/steps/PhoneOtpStep.d.ts.map +1 -1
  134. package/lib/typescript/steps/SwornDeclarationStep.d.ts.map +1 -1
  135. package/lib/typescript/steps/TaxInfoStep.d.ts.map +1 -1
  136. package/lib/typescript/steps/TermsAndConditionsStep.d.ts.map +1 -1
  137. package/lib/typescript/steps/_shared.d.ts +11 -0
  138. package/lib/typescript/steps/_shared.d.ts.map +1 -1
  139. package/lib/typescript/steps/types.d.ts +15 -0
  140. package/lib/typescript/steps/types.d.ts.map +1 -1
  141. package/lib/typescript/types/index.d.ts +127 -5
  142. package/lib/typescript/types/index.d.ts.map +1 -1
  143. package/lib/typescript/ui/StepShell.d.ts +11 -1
  144. package/lib/typescript/ui/StepShell.d.ts.map +1 -1
  145. package/lib/typescript/ui/VelionOnboardingScreen.d.ts +9 -2
  146. package/lib/typescript/ui/VelionOnboardingScreen.d.ts.map +1 -1
  147. package/lib/typescript/ui/icons/StepIcon.d.ts +1 -1
  148. package/lib/typescript/ui/icons/StepIcon.d.ts.map +1 -1
  149. package/lib/typescript/ui/primitives/BackButton.d.ts +20 -0
  150. package/lib/typescript/ui/primitives/BackButton.d.ts.map +1 -0
  151. package/lib/typescript/ui/primitives/index.d.ts +1 -0
  152. package/lib/typescript/ui/primitives/index.d.ts.map +1 -1
  153. package/package.json +1 -1
  154. package/src/core/VelionOnboarding.ts +315 -16
  155. package/src/core/retryStepCopy.ts +54 -0
  156. package/src/core/routingCommands.ts +63 -0
  157. package/src/core/sessionStateMapper.ts +65 -0
  158. package/src/i18n/strings/en.ts +33 -0
  159. package/src/i18n/strings/es.ts +33 -0
  160. package/src/index.ts +2 -0
  161. package/src/steps/AddressInfoStep.tsx +38 -20
  162. package/src/steps/DocumentsOcrStep.tsx +5 -0
  163. package/src/steps/EmailContactStep.tsx +6 -0
  164. package/src/steps/EmailOtpStep.tsx +6 -0
  165. package/src/steps/FaceMatchStep.tsx +18 -19
  166. package/src/steps/HumanBasicInfoStep.tsx +16 -4
  167. package/src/steps/HumanExtendedInfoStep.tsx +18 -9
  168. package/src/steps/LegalBasicInfoStep.tsx +16 -7
  169. package/src/steps/LegalExtendedInfoStep.tsx +16 -3
  170. package/src/steps/PhoneContactStep.tsx +6 -0
  171. package/src/steps/PhoneOtpStep.tsx +6 -0
  172. package/src/steps/SwornDeclarationStep.tsx +23 -6
  173. package/src/steps/TaxInfoStep.tsx +15 -4
  174. package/src/steps/TermsAndConditionsStep.tsx +8 -0
  175. package/src/steps/_shared.ts +25 -0
  176. package/src/steps/types.ts +15 -0
  177. package/src/types/index.ts +131 -3
  178. package/src/ui/StepShell.tsx +17 -0
  179. package/src/ui/VelionOnboardingScreen.tsx +36 -2
  180. package/src/ui/icons/StepIcon.tsx +2 -1
  181. package/src/ui/primitives/BackButton.tsx +65 -0
  182. package/src/ui/primitives/index.ts +1 -0
@@ -8,6 +8,8 @@
8
8
  * Invariants:
9
9
  * - SSE dedupe by `event_id` (monotonic)
10
10
  * - Suppress duplicate `NEXT_STEP` for the just-completed step
11
+ * - `RETRY_STEP` shows a retry dialog (Retry re-mounts the step, Cancel exits);
12
+ * once the retry quota is exhausted the backend emits SESSION_DECLINED instead
11
13
  * - 45 s watchdog for terminal SSE event after final step → fallback GET
12
14
  * - SESSION_DECLINED handling races with module.run()
13
15
  */
@@ -22,9 +24,16 @@ import {
22
24
  mapOnboardingDtoToResultWithStatus,
23
25
  isTerminalSessionStatusFromDto,
24
26
  requiresCurrentStepForSessionStatus,
27
+ deriveCanGoBack,
25
28
  } from './sessionStateMapper';
26
29
  import { createSessionEventSource } from '../transport/sse';
27
30
  import { resolveSessionDeclinedCopy } from './sessionDeclinedCopy';
31
+ import { resolveRetryStepCopy } from './retryStepCopy';
32
+ import {
33
+ parseBackExitCommand,
34
+ parsePreviousStepCommand,
35
+ type PreviousStepCommand,
36
+ } from './routingCommands';
28
37
  import { FingerprintStep } from '../steps/FingerprintStep';
29
38
  import { HumanBasicInfoStep } from '../steps/HumanBasicInfoStep';
30
39
  import { EmailContactStep } from '../steps/EmailContactStep';
@@ -49,12 +58,14 @@ import {
49
58
  type SdkError,
50
59
  type OnboardingStep,
51
60
  type OnboardingResult,
61
+ type OnboardingExit,
52
62
  type OnboardingDtoResponse,
53
63
  type OnboardingSessionEvent,
54
64
  type SessionState,
55
65
  } from '../types';
56
66
  import type { StepModule, StepUiHandle } from '../steps/types';
57
- import type { ReactNode } from 'react';
67
+ import { createElement, type ReactNode } from 'react';
68
+ import { RetryDialog } from '../ui/overlays/RetryDialog';
58
69
 
59
70
  // ─────────────────────────────────────────────────────────────────────────────
60
71
  // PUBLIC CONFIG (RN flavor)
@@ -78,10 +89,19 @@ export type VelionConfig = Omit<
78
89
  interface NextStepCommand {
79
90
  step: OnboardingStep;
80
91
  stepConfig?: Record<string, unknown>;
81
- /** `NEXT_STEP` advances; `RETRY_STEP` re-runs the same step intentionally. */
92
+ /** `NEXT_STEP` advances; `RETRY_STEP` re-presents the same step (via a retry dialog). */
82
93
  action: 'NEXT_STEP' | 'RETRY_STEP';
94
+ /** Whether the target step can go back (when the backend sends it on the command). */
95
+ canGoBack?: boolean;
83
96
  }
84
97
 
98
+ /** Result of awaiting an active step module (see {@link VelionOnboarding.awaitModuleOutcome}). */
99
+ type ModuleOutcome =
100
+ | { kind: 'completed' }
101
+ | { kind: 'declined'; event: OnboardingSessionEvent }
102
+ | { kind: 'back'; command: PreviousStepCommand }
103
+ | { kind: 'exit'; step: OnboardingStep | undefined };
104
+
85
105
  const BACKEND_ONLY_ORCHESTRATED_STEPS = new Set<string>(['FACE_MATCH', 'AML_SCREENING']);
86
106
 
87
107
  const DEFAULT_API_URL = 'https://sdk.velion.la/onboarding';
@@ -144,6 +164,8 @@ export interface OrchestratorView {
144
164
  setStepNode?: (node: ReactNode | null) => void;
145
165
  setError?: (err: SdkError) => void;
146
166
  setResult?: (result: OnboardingResult) => void;
167
+ /** Called when the user leaves the flow via back on the first step. */
168
+ setExit?: (exit: OnboardingExit) => void;
147
169
  }
148
170
 
149
171
  /**
@@ -172,6 +194,19 @@ export class VelionOnboarding {
172
194
  private queuedNextStepCommand: NextStepCommand | null = null;
173
195
  private lastSseEventId = '0';
174
196
 
197
+ private previousStepResolve: ((cmd: PreviousStepCommand) => void) | null = null;
198
+ private queuedPreviousStepCommand: PreviousStepCommand | null = null;
199
+ private backExitResolve: ((step: OnboardingStep | undefined) => void) | null = null;
200
+ private queuedBackExitStep: { step: OnboardingStep | undefined } | null = null;
201
+ private backRequestInFlight = false;
202
+
203
+ /** Resolver for the in-flight retry dialog (RETRY_STEP), cleared on destroy. */
204
+ private retryDialogResolve: ((choice: 'retry' | 'cancel') => void) | null = null;
205
+
206
+ /** Per-step reversibility (workflow order) cached from the initial GET, used to
207
+ * derive `can_go_back` for steps reached via SSE (which doesn't carry it). */
208
+ private stepReversibility: ReadonlyArray<{ code: OnboardingStep; reversible: boolean }> = [];
209
+
175
210
  private sessionDeclineHandler: ((event: OnboardingSessionEvent) => void) | null = null;
176
211
  private pendingSessionDeclined: OnboardingSessionEvent | null = null;
177
212
  private pendingTerminalEvent: OnboardingSessionEvent | null = null;
@@ -284,6 +319,11 @@ export class VelionOnboarding {
284
319
  this.emitter.removeAllListeners();
285
320
  this.sessionDeclineHandler = null;
286
321
  this.pendingSessionDeclined = null;
322
+ this.previousStepResolve = null;
323
+ this.queuedPreviousStepCommand = null;
324
+ this.backExitResolve = null;
325
+ this.queuedBackExitStep = null;
326
+ this.retryDialogResolve = null;
287
327
  }
288
328
 
289
329
  // ── Initialization ────────────────────────────────────────────────────────
@@ -318,6 +358,9 @@ export class VelionOnboarding {
318
358
  }
319
359
 
320
360
  const sessionState = mapOnboardingDtoToSessionState(dto);
361
+ // Cache the workflow reversibility map so the "back" control can be resolved
362
+ // for steps reached via SSE (which doesn't carry `can_go_back`).
363
+ this.stepReversibility = sessionState.stepReversibility ?? [];
321
364
  this.emitter.emit('session:loaded', sessionState);
322
365
 
323
366
  if (isTerminalSessionStatusFromDto(dto.status)) {
@@ -365,6 +408,10 @@ export class VelionOnboarding {
365
408
  let index = 0;
366
409
  let currentStep = sessionState.currentStep;
367
410
  let currentStepConfig = sessionState.currentStepConfig;
411
+ let currentStepResult = sessionState.currentStepResult;
412
+ let currentCanGoBack = currentStep
413
+ ? this.resolveCanGoBack(sessionState.canGoBack, currentStep)
414
+ : false;
368
415
  const knownStepConfigs = { ...(sessionState.stepConfigs ?? {}) };
369
416
 
370
417
  if (currentStep && isBackendOnlyOrchestratedStep(currentStep)) {
@@ -388,6 +435,8 @@ export class VelionOnboarding {
388
435
  }
389
436
  currentStep = routed.step;
390
437
  currentStepConfig = routed.stepConfig;
438
+ currentStepResult = undefined;
439
+ currentCanGoBack = this.resolveCanGoBack(routed.canGoBack, routed.step);
391
440
  } finally {
392
441
  this.showLoading(null);
393
442
  }
@@ -408,28 +457,59 @@ export class VelionOnboarding {
408
457
  knownStepConfigs[currentStep] = currentStepConfig;
409
458
  }
410
459
 
411
- const module = this.createModule(currentStep, currentStepConfig);
460
+ const module = this.createModule(
461
+ currentStep,
462
+ currentStepConfig,
463
+ currentStepResult,
464
+ currentCanGoBack,
465
+ );
412
466
  this.activeModule = module;
413
467
 
468
+ let outcome: ModuleOutcome;
414
469
  try {
415
- const runOutcome = await this.withSessionDeclineRace(module.run());
416
- if (await this.consumePendingTerminalEvent()) {
417
- module.destroy();
418
- this.activeModule = null;
419
- return;
420
- }
421
- if (runOutcome.declined) {
422
- module.destroy();
423
- this.activeModule = null;
424
- this.endFlowWithSessionDeclined(runOutcome.event);
425
- return;
426
- }
470
+ outcome = await this.awaitModuleOutcome(module.run());
427
471
  } catch (err) {
428
472
  module.destroy();
429
473
  this.activeModule = null;
430
474
  throw err;
431
475
  }
432
476
 
477
+ if (await this.consumePendingTerminalEvent()) {
478
+ module.destroy();
479
+ this.activeModule = null;
480
+ return;
481
+ }
482
+ if (outcome.kind === 'declined') {
483
+ module.destroy();
484
+ this.activeModule = null;
485
+ this.endFlowWithSessionDeclined(outcome.event);
486
+ return;
487
+ }
488
+ if (outcome.kind === 'back') {
489
+ // Reverse navigation: tear down the active form and re-enter the loop on
490
+ // the re-opened step with its previous data as prefill. Do NOT advance
491
+ // the index nor emit step:complete — the step was not completed.
492
+ module.destroy();
493
+ this.activeModule = null;
494
+ this.view.setStepNode?.(null);
495
+ const command = outcome.command;
496
+ currentStep = command.step;
497
+ currentStepConfig =
498
+ command.stepConfig ?? knownStepConfigs[command.step];
499
+ currentStepResult = command.stepResult;
500
+ currentCanGoBack = this.resolveCanGoBack(command.canGoBack, command.step);
501
+ this.showLoading(this.localizedLoadingMsg());
502
+ continue;
503
+ }
504
+ if (outcome.kind === 'exit') {
505
+ // Back on the first reversible step: there is no earlier step, so the
506
+ // backend told us to leave. Tear down and hand control back to the host.
507
+ module.destroy();
508
+ this.activeModule = null;
509
+ this.exitFlow(outcome.step);
510
+ return;
511
+ }
512
+
433
513
  module.destroy();
434
514
  this.activeModule = null;
435
515
  this.view.setStepNode?.(null);
@@ -483,8 +563,35 @@ export class VelionOnboarding {
483
563
  this.showLoading(null);
484
564
  }
485
565
  if (!next?.step) break;
566
+
567
+ // RETRY_STEP: the step failed but the retry quota is not exhausted. Show a
568
+ // retry dialog before re-presenting the step. "Retry" re-mounts the same
569
+ // step for a fresh submit; "Cancel" exits the flow cleanly (no verdict).
570
+ // When the quota IS exhausted the backend emits SESSION_DECLINED instead,
571
+ // so this dialog never shows for the final attempt.
572
+ if (next.action === 'RETRY_STEP') {
573
+ const choice = await this.presentRetryStepDialog(next.step);
574
+ if (this.sessionEnded || this.status === 'DESTROYED') return;
575
+ if (await this.consumePendingTerminalEvent()) return;
576
+ if (this.pendingSessionDeclined) {
577
+ const ev = this.pendingSessionDeclined;
578
+ this.pendingSessionDeclined = null;
579
+ this.endFlowWithSessionDeclined(ev);
580
+ return;
581
+ }
582
+ if (choice === 'cancel') {
583
+ this.exitFlow(next.step, 'RETRY_CANCELLED');
584
+ return;
585
+ }
586
+ this.showLoading(this.localizedLoadingMsg());
587
+ }
588
+
486
589
  currentStep = next.step;
487
- currentStepConfig = next.stepConfig;
590
+ currentStepConfig = next.stepConfig ?? knownStepConfigs[next.step];
591
+ // Forward navigation: no prefill. `can_go_back` comes from the command
592
+ // when the backend sends it, else derived from the reversibility map.
593
+ currentStepResult = undefined;
594
+ currentCanGoBack = this.resolveCanGoBack(next.canGoBack, next.step);
488
595
  }
489
596
 
490
597
  this.showLoading(this.localizedFinalizingMsg());
@@ -517,6 +624,8 @@ export class VelionOnboarding {
517
624
  private createModule(
518
625
  step: OnboardingStep,
519
626
  stepConfig: Record<string, unknown> | undefined,
627
+ stepResult?: Record<string, unknown>,
628
+ canGoBack?: boolean,
520
629
  ): StepModule {
521
630
  const deps = {
522
631
  api: this.api,
@@ -526,6 +635,13 @@ export class VelionOnboarding {
526
635
  ui: this.uiHandle,
527
636
  step,
528
637
  ...(stepConfig !== undefined && { stepConfig }),
638
+ ...(stepResult !== undefined && { stepResult }),
639
+ // Reverse navigation: wire the "back" control only when the backend says
640
+ // the user can go back from this step (`can_go_back`). The orchestrator
641
+ // owns the POST + SSE handshake; the step only triggers it.
642
+ ...(canGoBack === true && {
643
+ onBack: () => this.requestBackNavigation(step),
644
+ }),
529
645
  // Map key fallback chain:
530
646
  // 1. `VelionConfig.googleMapsApiKey` (runtime override; takes precedence
531
647
  // so hosts that already inject it via JS keep working).
@@ -663,6 +779,68 @@ export class VelionOnboarding {
663
779
  this.emitter.emit('flow:complete', result);
664
780
  }
665
781
 
782
+ /**
783
+ * Ends the flow without a verdict and notifies the host via `onExit`. Not an
784
+ * error: the UI is cleared so the host can dismiss the SDK. Triggered by
785
+ * backing out of the first reversible step (`BACK_EXIT`) or cancelling the
786
+ * retry dialog (`RETRY_CANCELLED`).
787
+ */
788
+ private exitFlow(
789
+ step: OnboardingStep | undefined,
790
+ reason: OnboardingExit['reason'] = 'BACK_EXIT',
791
+ ): void {
792
+ if (this.sessionEnded) return;
793
+ this.sessionEnded = true;
794
+ this.view.setStepNode?.(null);
795
+ this.setStatus('EXITED');
796
+ log.info('[Flow] Session exited', {
797
+ sessionId: this.config.sessionId,
798
+ reason,
799
+ step,
800
+ });
801
+ const exit: OnboardingExit = {
802
+ reason,
803
+ ...(step !== undefined && { step }),
804
+ };
805
+ this.view.setExit?.(exit);
806
+ this.emitter.emit('flow:exit', exit);
807
+ }
808
+
809
+ /**
810
+ * Mounts the retry dialog for a `RETRY_STEP` and resolves with the user's
811
+ * choice. Copy is derived from the step (not the backend `reason`, which is a
812
+ * diagnostic string) and can be overridden per-step via `retryStepTexts`.
813
+ */
814
+ private presentRetryStepDialog(
815
+ step: OnboardingStep,
816
+ ): Promise<'retry' | 'cancel'> {
817
+ const copy = resolveRetryStepCopy(
818
+ this.config.locale,
819
+ this.config.retryStepTexts,
820
+ step,
821
+ );
822
+ log.info('[Flow] Presenting RETRY_STEP dialog', { step });
823
+ return new Promise<'retry' | 'cancel'>((resolve) => {
824
+ const settle = (choice: 'retry' | 'cancel'): void => {
825
+ if (this.retryDialogResolve === null) return;
826
+ this.retryDialogResolve = null;
827
+ this.view.setStepNode?.(null);
828
+ resolve(choice);
829
+ };
830
+ this.retryDialogResolve = resolve;
831
+ this.view.setStepNode?.(
832
+ createElement(RetryDialog, {
833
+ title: copy.title,
834
+ message: copy.message,
835
+ retryLabel: copy.retryLabel,
836
+ cancelLabel: copy.cancelLabel,
837
+ onRetry: () => settle('retry'),
838
+ onCancel: () => settle('cancel'),
839
+ }),
840
+ );
841
+ });
842
+ }
843
+
666
844
  private endFlowWithSessionDeclined(event: OnboardingSessionEvent): void {
667
845
  if (this.sessionEnded) return;
668
846
  this.sessionEnded = true;
@@ -754,6 +932,38 @@ export class VelionOnboarding {
754
932
  }
755
933
  }
756
934
 
935
+ const maybePrevious = parsePreviousStepCommand(event);
936
+ if (maybePrevious) {
937
+ log.info('[Flow] PREVIOUS_STEP received from SSE', {
938
+ step: maybePrevious.step,
939
+ hasStepConfig: maybePrevious.stepConfig !== undefined,
940
+ hasStepResult: maybePrevious.stepResult !== undefined,
941
+ });
942
+ if (this.previousStepResolve) {
943
+ const resolve = this.previousStepResolve;
944
+ this.previousStepResolve = null;
945
+ resolve(maybePrevious);
946
+ } else {
947
+ // Defensive: a PREVIOUS_STEP arrived while no step was waiting for it
948
+ // (e.g. between transitions). Queue it so the next module entry honors it.
949
+ this.queuedPreviousStepCommand = maybePrevious;
950
+ }
951
+ return;
952
+ }
953
+
954
+ const maybeBackExit = parseBackExitCommand(event);
955
+ if (maybeBackExit) {
956
+ log.info('[Flow] BACK_EXIT received from SSE', { step: maybeBackExit.step });
957
+ if (this.backExitResolve) {
958
+ const resolve = this.backExitResolve;
959
+ this.backExitResolve = null;
960
+ resolve(maybeBackExit.step);
961
+ } else {
962
+ this.queuedBackExitStep = { step: maybeBackExit.step };
963
+ }
964
+ return;
965
+ }
966
+
757
967
  const maybeNext = this.extractNextStepCommand(event);
758
968
  if (maybeNext) {
759
969
  log.info('[Flow] ROUTING_COMMAND received from SSE', {
@@ -793,9 +1003,47 @@ export class VelionOnboarding {
793
1003
  step,
794
1004
  action,
795
1005
  ...(event.step_config !== undefined && { stepConfig: event.step_config }),
1006
+ ...(typeof event.can_go_back === 'boolean' && { canGoBack: event.can_go_back }),
796
1007
  };
797
1008
  }
798
1009
 
1010
+ /**
1011
+ * Fire-and-forget reverse navigation. POSTs `/sessions/:id/back`; the actual
1012
+ * step transition arrives via SSE (`PREVIOUS_STEP`). A `400` (session not
1013
+ * IN_PROGRESS) or any other failure is swallowed — the user keeps editing the
1014
+ * current step. De-duplicated so rapid taps don't stack requests.
1015
+ */
1016
+ private requestBackNavigation(fromStep: OnboardingStep): void {
1017
+ if (this.status === 'DESTROYED' || this.sessionEnded) return;
1018
+ if (this.backRequestInFlight) return;
1019
+ this.backRequestInFlight = true;
1020
+ log.info('[Flow] Requesting reverse navigation', { fromStep });
1021
+ void this.api
1022
+ .post(`/sessions/${this.config.sessionId}/back`, { from_step: fromStep })
1023
+ .catch((err) => {
1024
+ log.warn('[Flow] Back navigation request failed (ignored)', err);
1025
+ })
1026
+ .finally(() => {
1027
+ this.backRequestInFlight = false;
1028
+ });
1029
+ }
1030
+
1031
+ /**
1032
+ * Derives `can_go_back` for a step from the cached workflow reversibility map.
1033
+ * Matches the backend's barrier model: a step can go back when any earlier
1034
+ * step is reversible (navigate) or the step itself is the first reversible one
1035
+ * (back exits). Fallback only — an explicit `can_go_back` from the backend
1036
+ * (GET, or a ROUTING_COMMAND that carries it) always wins.
1037
+ */
1038
+ private resolveCanGoBack(
1039
+ explicit: boolean | undefined,
1040
+ step: OnboardingStep,
1041
+ ): boolean {
1042
+ return typeof explicit === 'boolean'
1043
+ ? explicit
1044
+ : deriveCanGoBack(step, this.stepReversibility);
1045
+ }
1046
+
799
1047
  // ── Wait helpers ──────────────────────────────────────────────────────────
800
1048
 
801
1049
  /**
@@ -839,6 +1087,9 @@ export class VelionOnboarding {
839
1087
  ...(state.currentStepConfig !== undefined && {
840
1088
  stepConfig: state.currentStepConfig,
841
1089
  }),
1090
+ ...(state.canGoBack !== undefined && {
1091
+ canGoBack: state.canGoBack,
1092
+ }),
842
1093
  });
843
1094
  return;
844
1095
  }
@@ -898,6 +1149,53 @@ export class VelionOnboarding {
898
1149
  return true;
899
1150
  }
900
1151
 
1152
+ /**
1153
+ * Runs the active step, resolving on the first of:
1154
+ * - `completed` — the module's `run()` resolved (user advanced),
1155
+ * - `declined` — SESSION_DECLINED arrived mid-step,
1156
+ * - `back` — a PREVIOUS_STEP routing command arrived (user tapped back),
1157
+ * - `exit` — a BACK_EXIT routing command arrived (back on the first
1158
+ * reversible step → leave the flow).
1159
+ *
1160
+ * Rejects only if `run()` itself throws. Used in place of the plain decline
1161
+ * race for the step loop so reverse navigation can interrupt an active form.
1162
+ */
1163
+ private awaitModuleOutcome(run: Promise<void>): Promise<ModuleOutcome> {
1164
+ if (this.queuedPreviousStepCommand) {
1165
+ const command = this.queuedPreviousStepCommand;
1166
+ this.queuedPreviousStepCommand = null;
1167
+ return Promise.resolve({ kind: 'back', command });
1168
+ }
1169
+ if (this.queuedBackExitStep) {
1170
+ const { step } = this.queuedBackExitStep;
1171
+ this.queuedBackExitStep = null;
1172
+ return Promise.resolve({ kind: 'exit', step });
1173
+ }
1174
+ return new Promise((resolve, reject) => {
1175
+ let settled = false;
1176
+ const cleanup = (): void => {
1177
+ this.sessionDeclineHandler = null;
1178
+ this.previousStepResolve = null;
1179
+ this.backExitResolve = null;
1180
+ };
1181
+ const settle = (run2: () => void): void => {
1182
+ if (settled) return;
1183
+ settled = true;
1184
+ cleanup();
1185
+ run2();
1186
+ };
1187
+ this.sessionDeclineHandler = (event) =>
1188
+ settle(() => resolve({ kind: 'declined', event }));
1189
+ this.previousStepResolve = (command) =>
1190
+ settle(() => resolve({ kind: 'back', command }));
1191
+ this.backExitResolve = (step) =>
1192
+ settle(() => resolve({ kind: 'exit', step }));
1193
+ run
1194
+ .then(() => settle(() => resolve({ kind: 'completed' })))
1195
+ .catch((err) => settle(() => reject(err)));
1196
+ });
1197
+ }
1198
+
901
1199
  /**
902
1200
  * Race a step's promise against SESSION_DECLINED. If decline arrives first,
903
1201
  * `declined` is true so the caller can short-circuit cleanup.
@@ -940,6 +1238,7 @@ export class VelionOnboarding {
940
1238
  const cb = this.config;
941
1239
  if (cb.onError) this.emitter.on('error', cb.onError);
942
1240
  if (cb.onSuccess) this.emitter.on('flow:complete', cb.onSuccess);
1241
+ if (cb.onExit) this.emitter.on('flow:exit', cb.onExit);
943
1242
  if (cb.onStepChange) {
944
1243
  this.emitter.on('step:change', ({ step, index }) =>
945
1244
  cb.onStepChange?.(step, index),
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @fileoverview Copy resolution for the retry dialog shown on
3
+ * `ROUTING_COMMAND / RETRY_STEP` (a step failed but the retry quota is not yet
4
+ * exhausted, so the backend asks the SDK to re-present it).
5
+ *
6
+ * The backend `reason` is intentionally NOT used here: it is a diagnostic string
7
+ * (e.g. `"STEP_FAILED_RETRY_ALLOWED (attempt 1/3)"`), not user-facing localized
8
+ * copy. The dialog title/message are derived from the step being retried, with a
9
+ * generic fallback, and can be overridden per-step by the host via
10
+ * `VelionConfig.retryStepTexts`.
11
+ */
12
+
13
+ import type { OnboardingStep, VelionRetryStepTexts } from '../types';
14
+ import { getStrings } from '../i18n';
15
+
16
+ export interface ResolvedRetryStepCopy {
17
+ title: string;
18
+ message: string;
19
+ retryLabel: string;
20
+ cancelLabel: string;
21
+ }
22
+
23
+ function isEnglishLocale(locale: string | undefined): boolean {
24
+ return (locale ?? 'es').toLowerCase().startsWith('en');
25
+ }
26
+
27
+ /**
28
+ * Resolves the retry dialog copy for `step`. Precedence for title/message:
29
+ * 1. host override (`retryStepTexts[step][lang]`),
30
+ * 2. SDK per-step default (i18n `retryStep.steps[step]`),
31
+ * 3. generic SDK default (i18n `retryStep.default*`).
32
+ * The retry/cancel button labels always come from the i18n table.
33
+ */
34
+ export function resolveRetryStepCopy(
35
+ locale: string | undefined,
36
+ texts: VelionRetryStepTexts | undefined,
37
+ step: OnboardingStep,
38
+ ): ResolvedRetryStepCopy {
39
+ const t = getStrings(locale);
40
+ const lang = isEnglishLocale(locale) ? 'en' : 'es';
41
+
42
+ const perStepDefault = (
43
+ t.retryStep.steps as Record<string, { title: string; message: string }>
44
+ )[step];
45
+ const override = texts?.[step]?.[lang];
46
+
47
+ return {
48
+ title: override?.title ?? perStepDefault?.title ?? t.retryStep.defaultTitle,
49
+ message:
50
+ override?.message ?? perStepDefault?.message ?? t.retryStep.defaultMessage,
51
+ retryLabel: t.retryStep.retry,
52
+ cancelLabel: t.retryStep.cancel,
53
+ };
54
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @fileoverview Pure parsers for SSE `ROUTING_COMMAND` payloads.
3
+ *
4
+ * Kept free of React Native imports so they can be unit-tested in a plain node
5
+ * environment. The orchestrator owns the side effects (navigation, POSTs); these
6
+ * functions only translate a raw `OnboardingSessionEvent` into a typed command.
7
+ */
8
+
9
+ import type { OnboardingSessionEvent, OnboardingStep } from '../types';
10
+
11
+ /**
12
+ * Reverse-navigation command (`ROUTING_COMMAND / PREVIOUS_STEP`). Carries the
13
+ * re-opened step plus its config and the previously-captured data for prefill.
14
+ */
15
+ export interface PreviousStepCommand {
16
+ step: OnboardingStep;
17
+ stepConfig?: Record<string, unknown>;
18
+ stepResult?: Record<string, unknown>;
19
+ /** Whether the re-opened step can itself go back further (when the backend sends it). */
20
+ canGoBack?: boolean;
21
+ }
22
+
23
+ /**
24
+ * Parses a reverse-navigation command from an SSE event. Returns `null` for any
25
+ * event that is not a `ROUTING_COMMAND` with `action === 'PREVIOUS_STEP'` and a
26
+ * `step_code`. `step_config` (config) and `step_result` (prefill) are forwarded
27
+ * when present.
28
+ */
29
+ export function parsePreviousStepCommand(
30
+ event: OnboardingSessionEvent,
31
+ ): PreviousStepCommand | null {
32
+ if (event.event_type !== 'ROUTING_COMMAND') return null;
33
+ if (event.action !== 'PREVIOUS_STEP') return null;
34
+ const step = event.step_code as OnboardingStep | undefined;
35
+ if (!step) return null;
36
+ return {
37
+ step,
38
+ ...(event.step_config !== undefined && { stepConfig: event.step_config }),
39
+ ...(event.step_result !== undefined && { stepResult: event.step_result }),
40
+ ...(typeof event.can_go_back === 'boolean' && { canGoBack: event.can_go_back }),
41
+ };
42
+ }
43
+
44
+ /** Back-exit command (`ROUTING_COMMAND / BACK_EXIT`): leave the flow entirely. */
45
+ export interface BackExitCommand {
46
+ /** The step the user exited from (`step_code`), when the backend provides it. */
47
+ step?: OnboardingStep;
48
+ }
49
+
50
+ /**
51
+ * Parses a back-exit command from an SSE event. The backend emits this when the
52
+ * user taps "back" on the first reversible step (no earlier step to return to),
53
+ * signalling the SDK to leave the flow. Returns `null` for any other event.
54
+ * `step_code` is forwarded when present but is not required.
55
+ */
56
+ export function parseBackExitCommand(
57
+ event: OnboardingSessionEvent,
58
+ ): BackExitCommand | null {
59
+ if (event.event_type !== 'ROUTING_COMMAND') return null;
60
+ if (event.action !== 'BACK_EXIT') return null;
61
+ const step = event.step_code as OnboardingStep | undefined;
62
+ return step ? { step } : {};
63
+ }
@@ -58,6 +58,32 @@ export function mapOnboardingDtoToSessionState(
58
58
  stepConfigs[currentStep] = currentStepConfig;
59
59
  }
60
60
 
61
+ // Whether the SDK shows the "back" control on the current step. The backend
62
+ // computes this from the workflow graph and exposes it as `can_go_back` — the
63
+ // SDK obeys it instead of a step's intrinsic `reversible` flag.
64
+ const canGoBack =
65
+ typeof dto.can_go_back === 'boolean' ? dto.can_go_back : undefined;
66
+
67
+ // Per-step reversibility in workflow order, so the orchestrator can derive
68
+ // `can_go_back` for steps reached via SSE (which does not carry the flag).
69
+ const stepReversibility = sorted
70
+ .map((s) => {
71
+ const code = s.code as OnboardingStep | undefined;
72
+ if (!code || typeof code !== 'string') return null;
73
+ const maybeConfig = (s as unknown as { config?: Record<string, unknown> })
74
+ .config;
75
+ const reversible = resolveReversibleFlag(s.reversible, maybeConfig) === true;
76
+ return { code, reversible };
77
+ })
78
+ .filter((s): s is { code: OnboardingStep; reversible: boolean } => s !== null);
79
+
80
+ // Prefill: data previously captured for `currentStep`, present when a reverse
81
+ // navigation re-opened a completed step (GET reflects it on `current_step.result`).
82
+ const currentStepResult =
83
+ dto.current_step?.result && typeof dto.current_step.result === 'object'
84
+ ? dto.current_step.result
85
+ : undefined;
86
+
61
87
  const allowedParentOrigins = Array.isArray(dto.allowed_parent_origins)
62
88
  ? dto.allowed_parent_origins.filter(
63
89
  (o): o is string => typeof o === 'string' && o.length > 0,
@@ -67,6 +93,9 @@ export function mapOnboardingDtoToSessionState(
67
93
  const state: SessionState = {
68
94
  ...(currentStep !== undefined && { currentStep }),
69
95
  ...(currentStepConfig !== undefined && { currentStepConfig }),
96
+ ...(canGoBack !== undefined && { canGoBack }),
97
+ ...(stepReversibility.length > 0 && { stepReversibility }),
98
+ ...(currentStepResult !== undefined && { currentStepResult }),
70
99
  ...(Object.keys(stepConfigs).length > 0 && { stepConfigs }),
71
100
  ...(validType !== undefined && { onboardingType: validType }),
72
101
  ...(dto.metadata !== undefined && { metadata: dto.metadata }),
@@ -75,6 +104,42 @@ export function mapOnboardingDtoToSessionState(
75
104
  return state;
76
105
  }
77
106
 
107
+ /**
108
+ * Resolves whether a step is reversible. Prefers an explicit boolean flag
109
+ * (e.g. `current_step.reversible`); otherwise reads the `reversible` key the
110
+ * backend stamps into the step config. Returns `undefined` when neither source
111
+ * carries the flag, so callers can distinguish "not reversible" from "unknown".
112
+ */
113
+ export function resolveReversibleFlag(
114
+ explicit: boolean | undefined,
115
+ config: Record<string, unknown> | undefined,
116
+ ): boolean | undefined {
117
+ if (typeof explicit === 'boolean') return explicit;
118
+ if (config && typeof config.reversible === 'boolean') {
119
+ return config.reversible;
120
+ }
121
+ return undefined;
122
+ }
123
+
124
+ /**
125
+ * Derives `can_go_back` for a step from the workflow reversibility map (used as a
126
+ * fallback when the backend doesn't send `can_go_back` explicitly — e.g. on a
127
+ * step reached via SSE). Matches the backend's barrier model: a step can go back
128
+ * when any earlier step is reversible (navigate to it) or the step itself is the
129
+ * first reversible step (back exits the flow). Returns `false` when the step is
130
+ * not in the cached order.
131
+ */
132
+ export function deriveCanGoBack(
133
+ step: OnboardingStep,
134
+ order: ReadonlyArray<{ code: OnboardingStep; reversible: boolean }>,
135
+ ): boolean {
136
+ const index = order.findIndex((s) => s.code === step);
137
+ if (index < 0) return false;
138
+ const previousReversible = order.slice(0, index).some((s) => s.reversible);
139
+ const currentReversible = order[index]?.reversible === true;
140
+ return previousReversible || currentReversible;
141
+ }
142
+
78
143
  function resolveCurrentStepFromLegacySteps(
79
144
  sorted: Array<{ code: string; status?: string }>,
80
145
  ): OnboardingStep | undefined {