File size: 1,211 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { PRIVATE_STEPS } from '../declarative-flow/internals/steps';
import type { FlowV1, StepperStep } from '../declarative-flow/internals/types';

function useInjectUserStepIfNeededForV1( flow: FlowV1 ): readonly StepperStep[] {
	const steps = flow.useSteps();
	return injectUserStepInSteps( steps ) as readonly StepperStep[];
}

export function injectUserStepInSteps< T extends readonly StepperStep[] >(
	steps: T
): T | [ ...T, typeof PRIVATE_STEPS.USER ] {
	const firstAuthWalledStep = steps.findIndex( ( step ) => step.requiresLoggedInUser );

	if ( firstAuthWalledStep === -1 ) {
		return steps;
	}

	// For logged-out users, we will redirect steps that require auth to the user step,
	// and then redirect back to the original steps after auth.
	// Therefore, we must avoid placing the user step as the first step,
	// as it would prevent us from knowing which step to redirect back to.
	return [ ...steps, PRIVATE_STEPS.USER ] as const;
}

/**
 * @deprecated should be removed once #97999 is merged and all flows are migrated to V2.
 */
export function enhanceFlowWithAuth( flow: FlowV1 ): FlowV1 {
	return {
		...flow,
		useSteps: () => useInjectUserStepIfNeededForV1( flow ) as StepperStep[],
	};
}