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

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 (169) hide show
  1. package/README.md +85 -0
  2. package/lib/commonjs/core/VelionOnboarding.js +233 -15
  3. package/lib/commonjs/core/VelionOnboarding.js.map +1 -1
  4. package/lib/commonjs/core/routingCommands.js +62 -0
  5. package/lib/commonjs/core/routingCommands.js.map +1 -0
  6. package/lib/commonjs/core/sessionStateMapper.js +63 -0
  7. package/lib/commonjs/core/sessionStateMapper.js.map +1 -1
  8. package/lib/commonjs/i18n/strings/en.js +1 -0
  9. package/lib/commonjs/i18n/strings/en.js.map +1 -1
  10. package/lib/commonjs/i18n/strings/es.js +1 -0
  11. package/lib/commonjs/i18n/strings/es.js.map +1 -1
  12. package/lib/commonjs/index.js.map +1 -1
  13. package/lib/commonjs/steps/AddressInfoStep.js +30 -18
  14. package/lib/commonjs/steps/AddressInfoStep.js.map +1 -1
  15. package/lib/commonjs/steps/DocumentsOcrStep.js +4 -0
  16. package/lib/commonjs/steps/DocumentsOcrStep.js.map +1 -1
  17. package/lib/commonjs/steps/EmailContactStep.js +5 -0
  18. package/lib/commonjs/steps/EmailContactStep.js.map +1 -1
  19. package/lib/commonjs/steps/EmailOtpStep.js +5 -0
  20. package/lib/commonjs/steps/EmailOtpStep.js.map +1 -1
  21. package/lib/commonjs/steps/HumanBasicInfoStep.js +12 -4
  22. package/lib/commonjs/steps/HumanBasicInfoStep.js.map +1 -1
  23. package/lib/commonjs/steps/HumanExtendedInfoStep.js +15 -8
  24. package/lib/commonjs/steps/HumanExtendedInfoStep.js.map +1 -1
  25. package/lib/commonjs/steps/LegalBasicInfoStep.js +13 -6
  26. package/lib/commonjs/steps/LegalBasicInfoStep.js.map +1 -1
  27. package/lib/commonjs/steps/LegalExtendedInfoStep.js +9 -2
  28. package/lib/commonjs/steps/LegalExtendedInfoStep.js.map +1 -1
  29. package/lib/commonjs/steps/PhoneContactStep.js +5 -0
  30. package/lib/commonjs/steps/PhoneContactStep.js.map +1 -1
  31. package/lib/commonjs/steps/PhoneOtpStep.js +5 -0
  32. package/lib/commonjs/steps/PhoneOtpStep.js.map +1 -1
  33. package/lib/commonjs/steps/SwornDeclarationStep.js +16 -6
  34. package/lib/commonjs/steps/SwornDeclarationStep.js.map +1 -1
  35. package/lib/commonjs/steps/TaxInfoStep.js +10 -3
  36. package/lib/commonjs/steps/TaxInfoStep.js.map +1 -1
  37. package/lib/commonjs/steps/TermsAndConditionsStep.js +7 -0
  38. package/lib/commonjs/steps/TermsAndConditionsStep.js.map +1 -1
  39. package/lib/commonjs/steps/_shared.js +21 -0
  40. package/lib/commonjs/steps/_shared.js.map +1 -1
  41. package/lib/commonjs/types/index.js +20 -1
  42. package/lib/commonjs/types/index.js.map +1 -1
  43. package/lib/commonjs/ui/StepShell.js +10 -2
  44. package/lib/commonjs/ui/StepShell.js.map +1 -1
  45. package/lib/commonjs/ui/VelionOnboardingScreen.js +25 -5
  46. package/lib/commonjs/ui/VelionOnboardingScreen.js.map +1 -1
  47. package/lib/commonjs/ui/icons/StepIcon.js.map +1 -1
  48. package/lib/commonjs/ui/primitives/BackButton.js +75 -0
  49. package/lib/commonjs/ui/primitives/BackButton.js.map +1 -0
  50. package/lib/commonjs/ui/primitives/index.js +7 -0
  51. package/lib/commonjs/ui/primitives/index.js.map +1 -1
  52. package/lib/module/core/VelionOnboarding.js +234 -16
  53. package/lib/module/core/VelionOnboarding.js.map +1 -1
  54. package/lib/module/core/routingCommands.js +57 -0
  55. package/lib/module/core/routingCommands.js.map +1 -0
  56. package/lib/module/core/sessionStateMapper.js +61 -0
  57. package/lib/module/core/sessionStateMapper.js.map +1 -1
  58. package/lib/module/i18n/strings/en.js +1 -0
  59. package/lib/module/i18n/strings/en.js.map +1 -1
  60. package/lib/module/i18n/strings/es.js +1 -0
  61. package/lib/module/i18n/strings/es.js.map +1 -1
  62. package/lib/module/index.js.map +1 -1
  63. package/lib/module/steps/AddressInfoStep.js +31 -19
  64. package/lib/module/steps/AddressInfoStep.js.map +1 -1
  65. package/lib/module/steps/DocumentsOcrStep.js +4 -0
  66. package/lib/module/steps/DocumentsOcrStep.js.map +1 -1
  67. package/lib/module/steps/EmailContactStep.js +5 -0
  68. package/lib/module/steps/EmailContactStep.js.map +1 -1
  69. package/lib/module/steps/EmailOtpStep.js +5 -0
  70. package/lib/module/steps/EmailOtpStep.js.map +1 -1
  71. package/lib/module/steps/HumanBasicInfoStep.js +12 -4
  72. package/lib/module/steps/HumanBasicInfoStep.js.map +1 -1
  73. package/lib/module/steps/HumanExtendedInfoStep.js +16 -9
  74. package/lib/module/steps/HumanExtendedInfoStep.js.map +1 -1
  75. package/lib/module/steps/LegalBasicInfoStep.js +14 -7
  76. package/lib/module/steps/LegalBasicInfoStep.js.map +1 -1
  77. package/lib/module/steps/LegalExtendedInfoStep.js +10 -3
  78. package/lib/module/steps/LegalExtendedInfoStep.js.map +1 -1
  79. package/lib/module/steps/PhoneContactStep.js +5 -0
  80. package/lib/module/steps/PhoneContactStep.js.map +1 -1
  81. package/lib/module/steps/PhoneOtpStep.js +5 -0
  82. package/lib/module/steps/PhoneOtpStep.js.map +1 -1
  83. package/lib/module/steps/SwornDeclarationStep.js +18 -6
  84. package/lib/module/steps/SwornDeclarationStep.js.map +1 -1
  85. package/lib/module/steps/TaxInfoStep.js +11 -4
  86. package/lib/module/steps/TaxInfoStep.js.map +1 -1
  87. package/lib/module/steps/TermsAndConditionsStep.js +7 -0
  88. package/lib/module/steps/TermsAndConditionsStep.js.map +1 -1
  89. package/lib/module/steps/_shared.js +19 -0
  90. package/lib/module/steps/_shared.js.map +1 -1
  91. package/lib/module/types/index.js +21 -1
  92. package/lib/module/types/index.js.map +1 -1
  93. package/lib/module/ui/StepShell.js +10 -2
  94. package/lib/module/ui/StepShell.js.map +1 -1
  95. package/lib/module/ui/VelionOnboardingScreen.js +25 -5
  96. package/lib/module/ui/VelionOnboardingScreen.js.map +1 -1
  97. package/lib/module/ui/icons/StepIcon.js.map +1 -1
  98. package/lib/module/ui/primitives/BackButton.js +71 -0
  99. package/lib/module/ui/primitives/BackButton.js.map +1 -0
  100. package/lib/module/ui/primitives/index.js +1 -0
  101. package/lib/module/ui/primitives/index.js.map +1 -1
  102. package/lib/typescript/core/VelionOnboarding.d.ts +44 -1
  103. package/lib/typescript/core/VelionOnboarding.d.ts.map +1 -1
  104. package/lib/typescript/core/routingCommands.d.ts +39 -0
  105. package/lib/typescript/core/routingCommands.d.ts.map +1 -0
  106. package/lib/typescript/core/sessionStateMapper.d.ts +20 -1
  107. package/lib/typescript/core/sessionStateMapper.d.ts.map +1 -1
  108. package/lib/typescript/i18n/strings/en.d.ts.map +1 -1
  109. package/lib/typescript/i18n/strings/es.d.ts +1 -0
  110. package/lib/typescript/i18n/strings/es.d.ts.map +1 -1
  111. package/lib/typescript/index.d.ts +1 -1
  112. package/lib/typescript/index.d.ts.map +1 -1
  113. package/lib/typescript/steps/AddressInfoStep.d.ts.map +1 -1
  114. package/lib/typescript/steps/DocumentsOcrStep.d.ts.map +1 -1
  115. package/lib/typescript/steps/EmailContactStep.d.ts.map +1 -1
  116. package/lib/typescript/steps/EmailOtpStep.d.ts.map +1 -1
  117. package/lib/typescript/steps/HumanBasicInfoStep.d.ts.map +1 -1
  118. package/lib/typescript/steps/HumanExtendedInfoStep.d.ts.map +1 -1
  119. package/lib/typescript/steps/LegalBasicInfoStep.d.ts.map +1 -1
  120. package/lib/typescript/steps/LegalExtendedInfoStep.d.ts.map +1 -1
  121. package/lib/typescript/steps/PhoneContactStep.d.ts.map +1 -1
  122. package/lib/typescript/steps/PhoneOtpStep.d.ts.map +1 -1
  123. package/lib/typescript/steps/SwornDeclarationStep.d.ts.map +1 -1
  124. package/lib/typescript/steps/TaxInfoStep.d.ts.map +1 -1
  125. package/lib/typescript/steps/TermsAndConditionsStep.d.ts.map +1 -1
  126. package/lib/typescript/steps/_shared.d.ts +11 -0
  127. package/lib/typescript/steps/_shared.d.ts.map +1 -1
  128. package/lib/typescript/steps/types.d.ts +15 -0
  129. package/lib/typescript/steps/types.d.ts.map +1 -1
  130. package/lib/typescript/types/index.d.ts +104 -5
  131. package/lib/typescript/types/index.d.ts.map +1 -1
  132. package/lib/typescript/ui/StepShell.d.ts +11 -1
  133. package/lib/typescript/ui/StepShell.d.ts.map +1 -1
  134. package/lib/typescript/ui/VelionOnboardingScreen.d.ts +9 -2
  135. package/lib/typescript/ui/VelionOnboardingScreen.d.ts.map +1 -1
  136. package/lib/typescript/ui/icons/StepIcon.d.ts +1 -1
  137. package/lib/typescript/ui/icons/StepIcon.d.ts.map +1 -1
  138. package/lib/typescript/ui/primitives/BackButton.d.ts +20 -0
  139. package/lib/typescript/ui/primitives/BackButton.d.ts.map +1 -0
  140. package/lib/typescript/ui/primitives/index.d.ts +1 -0
  141. package/lib/typescript/ui/primitives/index.d.ts.map +1 -1
  142. package/package.json +1 -1
  143. package/src/core/VelionOnboarding.ts +241 -14
  144. package/src/core/routingCommands.ts +63 -0
  145. package/src/core/sessionStateMapper.ts +65 -0
  146. package/src/i18n/strings/en.ts +1 -0
  147. package/src/i18n/strings/es.ts +1 -0
  148. package/src/index.ts +1 -0
  149. package/src/steps/AddressInfoStep.tsx +38 -20
  150. package/src/steps/DocumentsOcrStep.tsx +5 -0
  151. package/src/steps/EmailContactStep.tsx +6 -0
  152. package/src/steps/EmailOtpStep.tsx +6 -0
  153. package/src/steps/HumanBasicInfoStep.tsx +16 -4
  154. package/src/steps/HumanExtendedInfoStep.tsx +18 -9
  155. package/src/steps/LegalBasicInfoStep.tsx +16 -7
  156. package/src/steps/LegalExtendedInfoStep.tsx +16 -3
  157. package/src/steps/PhoneContactStep.tsx +6 -0
  158. package/src/steps/PhoneOtpStep.tsx +6 -0
  159. package/src/steps/SwornDeclarationStep.tsx +23 -6
  160. package/src/steps/TaxInfoStep.tsx +15 -4
  161. package/src/steps/TermsAndConditionsStep.tsx +8 -0
  162. package/src/steps/_shared.ts +25 -0
  163. package/src/steps/types.ts +15 -0
  164. package/src/types/index.ts +103 -3
  165. package/src/ui/StepShell.tsx +17 -0
  166. package/src/ui/VelionOnboardingScreen.tsx +36 -2
  167. package/src/ui/icons/StepIcon.tsx +2 -1
  168. package/src/ui/primitives/BackButton.tsx +65 -0
  169. package/src/ui/primitives/index.ts +1 -0
@@ -22,9 +22,15 @@ import {
22
22
  mapOnboardingDtoToResultWithStatus,
23
23
  isTerminalSessionStatusFromDto,
24
24
  requiresCurrentStepForSessionStatus,
25
+ deriveCanGoBack,
25
26
  } from './sessionStateMapper';
26
27
  import { createSessionEventSource } from '../transport/sse';
27
28
  import { resolveSessionDeclinedCopy } from './sessionDeclinedCopy';
29
+ import {
30
+ parseBackExitCommand,
31
+ parsePreviousStepCommand,
32
+ type PreviousStepCommand,
33
+ } from './routingCommands';
28
34
  import { FingerprintStep } from '../steps/FingerprintStep';
29
35
  import { HumanBasicInfoStep } from '../steps/HumanBasicInfoStep';
30
36
  import { EmailContactStep } from '../steps/EmailContactStep';
@@ -49,6 +55,7 @@ import {
49
55
  type SdkError,
50
56
  type OnboardingStep,
51
57
  type OnboardingResult,
58
+ type OnboardingExit,
52
59
  type OnboardingDtoResponse,
53
60
  type OnboardingSessionEvent,
54
61
  type SessionState,
@@ -80,8 +87,17 @@ interface NextStepCommand {
80
87
  stepConfig?: Record<string, unknown>;
81
88
  /** `NEXT_STEP` advances; `RETRY_STEP` re-runs the same step intentionally. */
82
89
  action: 'NEXT_STEP' | 'RETRY_STEP';
90
+ /** Whether the target step can go back (when the backend sends it on the command). */
91
+ canGoBack?: boolean;
83
92
  }
84
93
 
94
+ /** Result of awaiting an active step module (see {@link VelionOnboarding.awaitModuleOutcome}). */
95
+ type ModuleOutcome =
96
+ | { kind: 'completed' }
97
+ | { kind: 'declined'; event: OnboardingSessionEvent }
98
+ | { kind: 'back'; command: PreviousStepCommand }
99
+ | { kind: 'exit'; step: OnboardingStep | undefined };
100
+
85
101
  const BACKEND_ONLY_ORCHESTRATED_STEPS = new Set<string>(['FACE_MATCH', 'AML_SCREENING']);
86
102
 
87
103
  const DEFAULT_API_URL = 'https://sdk.velion.la/onboarding';
@@ -144,6 +160,8 @@ export interface OrchestratorView {
144
160
  setStepNode?: (node: ReactNode | null) => void;
145
161
  setError?: (err: SdkError) => void;
146
162
  setResult?: (result: OnboardingResult) => void;
163
+ /** Called when the user leaves the flow via back on the first step. */
164
+ setExit?: (exit: OnboardingExit) => void;
147
165
  }
148
166
 
149
167
  /**
@@ -172,6 +190,16 @@ export class VelionOnboarding {
172
190
  private queuedNextStepCommand: NextStepCommand | null = null;
173
191
  private lastSseEventId = '0';
174
192
 
193
+ private previousStepResolve: ((cmd: PreviousStepCommand) => void) | null = null;
194
+ private queuedPreviousStepCommand: PreviousStepCommand | null = null;
195
+ private backExitResolve: ((step: OnboardingStep | undefined) => void) | null = null;
196
+ private queuedBackExitStep: { step: OnboardingStep | undefined } | null = null;
197
+ private backRequestInFlight = false;
198
+
199
+ /** Per-step reversibility (workflow order) cached from the initial GET, used to
200
+ * derive `can_go_back` for steps reached via SSE (which doesn't carry it). */
201
+ private stepReversibility: ReadonlyArray<{ code: OnboardingStep; reversible: boolean }> = [];
202
+
175
203
  private sessionDeclineHandler: ((event: OnboardingSessionEvent) => void) | null = null;
176
204
  private pendingSessionDeclined: OnboardingSessionEvent | null = null;
177
205
  private pendingTerminalEvent: OnboardingSessionEvent | null = null;
@@ -284,6 +312,10 @@ export class VelionOnboarding {
284
312
  this.emitter.removeAllListeners();
285
313
  this.sessionDeclineHandler = null;
286
314
  this.pendingSessionDeclined = null;
315
+ this.previousStepResolve = null;
316
+ this.queuedPreviousStepCommand = null;
317
+ this.backExitResolve = null;
318
+ this.queuedBackExitStep = null;
287
319
  }
288
320
 
289
321
  // ── Initialization ────────────────────────────────────────────────────────
@@ -318,6 +350,9 @@ export class VelionOnboarding {
318
350
  }
319
351
 
320
352
  const sessionState = mapOnboardingDtoToSessionState(dto);
353
+ // Cache the workflow reversibility map so the "back" control can be resolved
354
+ // for steps reached via SSE (which doesn't carry `can_go_back`).
355
+ this.stepReversibility = sessionState.stepReversibility ?? [];
321
356
  this.emitter.emit('session:loaded', sessionState);
322
357
 
323
358
  if (isTerminalSessionStatusFromDto(dto.status)) {
@@ -365,6 +400,10 @@ export class VelionOnboarding {
365
400
  let index = 0;
366
401
  let currentStep = sessionState.currentStep;
367
402
  let currentStepConfig = sessionState.currentStepConfig;
403
+ let currentStepResult = sessionState.currentStepResult;
404
+ let currentCanGoBack = currentStep
405
+ ? this.resolveCanGoBack(sessionState.canGoBack, currentStep)
406
+ : false;
368
407
  const knownStepConfigs = { ...(sessionState.stepConfigs ?? {}) };
369
408
 
370
409
  if (currentStep && isBackendOnlyOrchestratedStep(currentStep)) {
@@ -388,6 +427,8 @@ export class VelionOnboarding {
388
427
  }
389
428
  currentStep = routed.step;
390
429
  currentStepConfig = routed.stepConfig;
430
+ currentStepResult = undefined;
431
+ currentCanGoBack = this.resolveCanGoBack(routed.canGoBack, routed.step);
391
432
  } finally {
392
433
  this.showLoading(null);
393
434
  }
@@ -408,28 +449,59 @@ export class VelionOnboarding {
408
449
  knownStepConfigs[currentStep] = currentStepConfig;
409
450
  }
410
451
 
411
- const module = this.createModule(currentStep, currentStepConfig);
452
+ const module = this.createModule(
453
+ currentStep,
454
+ currentStepConfig,
455
+ currentStepResult,
456
+ currentCanGoBack,
457
+ );
412
458
  this.activeModule = module;
413
459
 
460
+ let outcome: ModuleOutcome;
414
461
  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
- }
462
+ outcome = await this.awaitModuleOutcome(module.run());
427
463
  } catch (err) {
428
464
  module.destroy();
429
465
  this.activeModule = null;
430
466
  throw err;
431
467
  }
432
468
 
469
+ if (await this.consumePendingTerminalEvent()) {
470
+ module.destroy();
471
+ this.activeModule = null;
472
+ return;
473
+ }
474
+ if (outcome.kind === 'declined') {
475
+ module.destroy();
476
+ this.activeModule = null;
477
+ this.endFlowWithSessionDeclined(outcome.event);
478
+ return;
479
+ }
480
+ if (outcome.kind === 'back') {
481
+ // Reverse navigation: tear down the active form and re-enter the loop on
482
+ // the re-opened step with its previous data as prefill. Do NOT advance
483
+ // the index nor emit step:complete — the step was not completed.
484
+ module.destroy();
485
+ this.activeModule = null;
486
+ this.view.setStepNode?.(null);
487
+ const command = outcome.command;
488
+ currentStep = command.step;
489
+ currentStepConfig =
490
+ command.stepConfig ?? knownStepConfigs[command.step];
491
+ currentStepResult = command.stepResult;
492
+ currentCanGoBack = this.resolveCanGoBack(command.canGoBack, command.step);
493
+ this.showLoading(this.localizedLoadingMsg());
494
+ continue;
495
+ }
496
+ if (outcome.kind === 'exit') {
497
+ // Back on the first reversible step: there is no earlier step, so the
498
+ // backend told us to leave. Tear down and hand control back to the host.
499
+ module.destroy();
500
+ this.activeModule = null;
501
+ this.exitFlow(outcome.step);
502
+ return;
503
+ }
504
+
433
505
  module.destroy();
434
506
  this.activeModule = null;
435
507
  this.view.setStepNode?.(null);
@@ -484,7 +556,11 @@ export class VelionOnboarding {
484
556
  }
485
557
  if (!next?.step) break;
486
558
  currentStep = next.step;
487
- currentStepConfig = next.stepConfig;
559
+ currentStepConfig = next.stepConfig ?? knownStepConfigs[next.step];
560
+ // Forward navigation: no prefill. `can_go_back` comes from the command
561
+ // when the backend sends it, else derived from the reversibility map.
562
+ currentStepResult = undefined;
563
+ currentCanGoBack = this.resolveCanGoBack(next.canGoBack, next.step);
488
564
  }
489
565
 
490
566
  this.showLoading(this.localizedFinalizingMsg());
@@ -517,6 +593,8 @@ export class VelionOnboarding {
517
593
  private createModule(
518
594
  step: OnboardingStep,
519
595
  stepConfig: Record<string, unknown> | undefined,
596
+ stepResult?: Record<string, unknown>,
597
+ canGoBack?: boolean,
520
598
  ): StepModule {
521
599
  const deps = {
522
600
  api: this.api,
@@ -526,6 +604,13 @@ export class VelionOnboarding {
526
604
  ui: this.uiHandle,
527
605
  step,
528
606
  ...(stepConfig !== undefined && { stepConfig }),
607
+ ...(stepResult !== undefined && { stepResult }),
608
+ // Reverse navigation: wire the "back" control only when the backend says
609
+ // the user can go back from this step (`can_go_back`). The orchestrator
610
+ // owns the POST + SSE handshake; the step only triggers it.
611
+ ...(canGoBack === true && {
612
+ onBack: () => this.requestBackNavigation(step),
613
+ }),
529
614
  // Map key fallback chain:
530
615
  // 1. `VelionConfig.googleMapsApiKey` (runtime override; takes precedence
531
616
  // so hosts that already inject it via JS keep working).
@@ -663,6 +748,27 @@ export class VelionOnboarding {
663
748
  this.emitter.emit('flow:complete', result);
664
749
  }
665
750
 
751
+ /**
752
+ * Ends the flow because the user backed out of the first reversible step
753
+ * (`ROUTING_COMMAND / BACK_EXIT`). Not a verdict and not an error: the UI is
754
+ * cleared and the host is notified via `onExit` so it can dismiss the SDK.
755
+ */
756
+ private exitFlow(step: OnboardingStep | undefined): void {
757
+ if (this.sessionEnded) return;
758
+ this.sessionEnded = true;
759
+ this.setStatus('EXITED');
760
+ log.info('[Flow] Session exited via back', {
761
+ sessionId: this.config.sessionId,
762
+ step,
763
+ });
764
+ const exit: OnboardingExit = {
765
+ reason: 'BACK_EXIT',
766
+ ...(step !== undefined && { step }),
767
+ };
768
+ this.view.setExit?.(exit);
769
+ this.emitter.emit('flow:exit', exit);
770
+ }
771
+
666
772
  private endFlowWithSessionDeclined(event: OnboardingSessionEvent): void {
667
773
  if (this.sessionEnded) return;
668
774
  this.sessionEnded = true;
@@ -754,6 +860,38 @@ export class VelionOnboarding {
754
860
  }
755
861
  }
756
862
 
863
+ const maybePrevious = parsePreviousStepCommand(event);
864
+ if (maybePrevious) {
865
+ log.info('[Flow] PREVIOUS_STEP received from SSE', {
866
+ step: maybePrevious.step,
867
+ hasStepConfig: maybePrevious.stepConfig !== undefined,
868
+ hasStepResult: maybePrevious.stepResult !== undefined,
869
+ });
870
+ if (this.previousStepResolve) {
871
+ const resolve = this.previousStepResolve;
872
+ this.previousStepResolve = null;
873
+ resolve(maybePrevious);
874
+ } else {
875
+ // Defensive: a PREVIOUS_STEP arrived while no step was waiting for it
876
+ // (e.g. between transitions). Queue it so the next module entry honors it.
877
+ this.queuedPreviousStepCommand = maybePrevious;
878
+ }
879
+ return;
880
+ }
881
+
882
+ const maybeBackExit = parseBackExitCommand(event);
883
+ if (maybeBackExit) {
884
+ log.info('[Flow] BACK_EXIT received from SSE', { step: maybeBackExit.step });
885
+ if (this.backExitResolve) {
886
+ const resolve = this.backExitResolve;
887
+ this.backExitResolve = null;
888
+ resolve(maybeBackExit.step);
889
+ } else {
890
+ this.queuedBackExitStep = { step: maybeBackExit.step };
891
+ }
892
+ return;
893
+ }
894
+
757
895
  const maybeNext = this.extractNextStepCommand(event);
758
896
  if (maybeNext) {
759
897
  log.info('[Flow] ROUTING_COMMAND received from SSE', {
@@ -793,9 +931,47 @@ export class VelionOnboarding {
793
931
  step,
794
932
  action,
795
933
  ...(event.step_config !== undefined && { stepConfig: event.step_config }),
934
+ ...(typeof event.can_go_back === 'boolean' && { canGoBack: event.can_go_back }),
796
935
  };
797
936
  }
798
937
 
938
+ /**
939
+ * Fire-and-forget reverse navigation. POSTs `/sessions/:id/back`; the actual
940
+ * step transition arrives via SSE (`PREVIOUS_STEP`). A `400` (session not
941
+ * IN_PROGRESS) or any other failure is swallowed — the user keeps editing the
942
+ * current step. De-duplicated so rapid taps don't stack requests.
943
+ */
944
+ private requestBackNavigation(fromStep: OnboardingStep): void {
945
+ if (this.status === 'DESTROYED' || this.sessionEnded) return;
946
+ if (this.backRequestInFlight) return;
947
+ this.backRequestInFlight = true;
948
+ log.info('[Flow] Requesting reverse navigation', { fromStep });
949
+ void this.api
950
+ .post(`/sessions/${this.config.sessionId}/back`, { from_step: fromStep })
951
+ .catch((err) => {
952
+ log.warn('[Flow] Back navigation request failed (ignored)', err);
953
+ })
954
+ .finally(() => {
955
+ this.backRequestInFlight = false;
956
+ });
957
+ }
958
+
959
+ /**
960
+ * Derives `can_go_back` for a step from the cached workflow reversibility map.
961
+ * Matches the backend's barrier model: a step can go back when any earlier
962
+ * step is reversible (navigate) or the step itself is the first reversible one
963
+ * (back exits). Fallback only — an explicit `can_go_back` from the backend
964
+ * (GET, or a ROUTING_COMMAND that carries it) always wins.
965
+ */
966
+ private resolveCanGoBack(
967
+ explicit: boolean | undefined,
968
+ step: OnboardingStep,
969
+ ): boolean {
970
+ return typeof explicit === 'boolean'
971
+ ? explicit
972
+ : deriveCanGoBack(step, this.stepReversibility);
973
+ }
974
+
799
975
  // ── Wait helpers ──────────────────────────────────────────────────────────
800
976
 
801
977
  /**
@@ -839,6 +1015,9 @@ export class VelionOnboarding {
839
1015
  ...(state.currentStepConfig !== undefined && {
840
1016
  stepConfig: state.currentStepConfig,
841
1017
  }),
1018
+ ...(state.canGoBack !== undefined && {
1019
+ canGoBack: state.canGoBack,
1020
+ }),
842
1021
  });
843
1022
  return;
844
1023
  }
@@ -898,6 +1077,53 @@ export class VelionOnboarding {
898
1077
  return true;
899
1078
  }
900
1079
 
1080
+ /**
1081
+ * Runs the active step, resolving on the first of:
1082
+ * - `completed` — the module's `run()` resolved (user advanced),
1083
+ * - `declined` — SESSION_DECLINED arrived mid-step,
1084
+ * - `back` — a PREVIOUS_STEP routing command arrived (user tapped back),
1085
+ * - `exit` — a BACK_EXIT routing command arrived (back on the first
1086
+ * reversible step → leave the flow).
1087
+ *
1088
+ * Rejects only if `run()` itself throws. Used in place of the plain decline
1089
+ * race for the step loop so reverse navigation can interrupt an active form.
1090
+ */
1091
+ private awaitModuleOutcome(run: Promise<void>): Promise<ModuleOutcome> {
1092
+ if (this.queuedPreviousStepCommand) {
1093
+ const command = this.queuedPreviousStepCommand;
1094
+ this.queuedPreviousStepCommand = null;
1095
+ return Promise.resolve({ kind: 'back', command });
1096
+ }
1097
+ if (this.queuedBackExitStep) {
1098
+ const { step } = this.queuedBackExitStep;
1099
+ this.queuedBackExitStep = null;
1100
+ return Promise.resolve({ kind: 'exit', step });
1101
+ }
1102
+ return new Promise((resolve, reject) => {
1103
+ let settled = false;
1104
+ const cleanup = (): void => {
1105
+ this.sessionDeclineHandler = null;
1106
+ this.previousStepResolve = null;
1107
+ this.backExitResolve = null;
1108
+ };
1109
+ const settle = (run2: () => void): void => {
1110
+ if (settled) return;
1111
+ settled = true;
1112
+ cleanup();
1113
+ run2();
1114
+ };
1115
+ this.sessionDeclineHandler = (event) =>
1116
+ settle(() => resolve({ kind: 'declined', event }));
1117
+ this.previousStepResolve = (command) =>
1118
+ settle(() => resolve({ kind: 'back', command }));
1119
+ this.backExitResolve = (step) =>
1120
+ settle(() => resolve({ kind: 'exit', step }));
1121
+ run
1122
+ .then(() => settle(() => resolve({ kind: 'completed' })))
1123
+ .catch((err) => settle(() => reject(err)));
1124
+ });
1125
+ }
1126
+
901
1127
  /**
902
1128
  * Race a step's promise against SESSION_DECLINED. If decline arrives first,
903
1129
  * `declined` is true so the caller can short-circuit cleanup.
@@ -940,6 +1166,7 @@ export class VelionOnboarding {
940
1166
  const cb = this.config;
941
1167
  if (cb.onError) this.emitter.on('error', cb.onError);
942
1168
  if (cb.onSuccess) this.emitter.on('flow:complete', cb.onSuccess);
1169
+ if (cb.onExit) this.emitter.on('flow:exit', cb.onExit);
943
1170
  if (cb.onStepChange) {
944
1171
  this.emitter.on('step:change', ({ step, index }) =>
945
1172
  cb.onStepChange?.(step, index),
@@ -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 {
@@ -11,6 +11,7 @@ export const EN: StringsTable = {
11
11
  retry: 'Try again',
12
12
  confirm: 'Confirm',
13
13
  required: 'Required',
14
+ back: 'Back',
14
15
  submissionTitle: 'Something went wrong',
15
16
  submissionFallback:
16
17
  'Sorry, there was an error processing your information. Please try again — your data was not lost.',
@@ -14,6 +14,7 @@ export const ES = {
14
14
  retry: 'Reintentar',
15
15
  confirm: 'Confirmar',
16
16
  required: 'Requerido',
17
+ back: 'Atrás',
17
18
  submissionTitle: 'Hubo un problema',
18
19
  submissionFallback:
19
20
  'Disculpá, hubo un error procesando tu información. Volvé a intentar — tus datos no se perdieron.',
package/src/index.ts CHANGED
@@ -95,6 +95,7 @@ export type {
95
95
  OnboardingStepStatus,
96
96
  OnboardingType,
97
97
  OnboardingResult,
98
+ OnboardingExit,
98
99
  OnboardingSessionEvent,
99
100
  OnboardingDtoResponse,
100
101
  SessionState,