|
| 1 | +/*! |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +import { Wizard, WizardOptions } from '../wizards/wizard' |
| 7 | +import { Prompter } from './prompter' |
| 8 | +import { WizardPrompter } from './wizardPrompter' |
| 9 | +import { createHash } from 'crypto' |
| 10 | + |
| 11 | +/** |
| 12 | + * An abstract class that extends the base Wizard class plus the ability to |
| 13 | + * use other wizard classes as prompters |
| 14 | + */ |
| 15 | +export abstract class NestedWizard<T> extends Wizard<T> { |
| 16 | + /** |
| 17 | + * Map to store memoized wizard instances using SHA-256 hashed keys |
| 18 | + */ |
| 19 | + private wizardInstances: Map<string, any> = new Map() |
| 20 | + |
| 21 | + public constructor(options?: WizardOptions<T>) { |
| 22 | + super(options) |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * Creates a prompter for a wizard instance with memoization. |
| 27 | + * |
| 28 | + * @template TWizard - The type of wizard, must extend Wizard<TState> |
| 29 | + * @template TState - The type of state managed by the wizard |
| 30 | + * |
| 31 | + * @param wizardClass - The wizard class constructor |
| 32 | + * @param args - Constructor arguments for the wizard instance |
| 33 | + * |
| 34 | + * @returns A wizard prompter to be used as prompter |
| 35 | + * |
| 36 | + * @example |
| 37 | + * // Create a prompter for SyncWizard |
| 38 | + * const prompter = this.createWizardPrompter<SyncWizard, SyncParams>( |
| 39 | + * SyncWizard, |
| 40 | + * template.uri, |
| 41 | + * syncUrl |
| 42 | + * ) |
| 43 | + * |
| 44 | + * @remarks |
| 45 | + * - Instances are memoized using a SHA-256 hash of the wizard class name and arguments |
| 46 | + * - The same wizard instance is reused for identical constructor parameters for restoring wizard prompter |
| 47 | + * states during back button click event |
| 48 | + */ |
| 49 | + protected createWizardPrompter<TWizard extends Wizard<TState>, TState>( |
| 50 | + wizardClass: new (...args: any[]) => TWizard, |
| 51 | + ...args: ConstructorParameters<new (...args: any[]) => TWizard> |
| 52 | + ): Prompter<TState> { |
| 53 | + const memoizeKey = createHash('sha256') |
| 54 | + .update(wizardClass.name + JSON.stringify(args)) |
| 55 | + .digest('hex') |
| 56 | + |
| 57 | + if (!this.wizardInstances.get(memoizeKey)) { |
| 58 | + this.wizardInstances.set(memoizeKey, new wizardClass(...args)) |
| 59 | + } |
| 60 | + |
| 61 | + return new WizardPrompter(this.wizardInstances.get(memoizeKey)) as Prompter<TState> |
| 62 | + } |
| 63 | +} |
0 commit comments