import { updatePluginConfigContent } from '@/scripts/shared' import enquirer from 'enquirer' import fse from 'fs-extra' import type { ListrTask } from 'listr' import path from 'path' import type { AddTasksGetter } from '../common' import { allEvents } from './all-events' const eventHandlerTemplate = ({ functionName, eventType, }: { eventType: string functionName: string }) => { const code = /* typescript */ ` import type { PluginRequest, PluginResponse, Event } from '@ones-open/node-types' export const ${functionName} = async (request: PluginRequest>): Promise => { console.log(request.body) return { body: {} } } ` return code.trim() } export const getAddEventTasks = async ({ initialAnswer, pluginConfigContent, currentWorkingDirectory, }: Parameters[0]) => { if (initialAnswer.target !== 'event') { throw new Error('Invalid target type') } const allEventTypes = Object.keys(allEvents) const existedEventKeysSet = new Set( pluginConfigContent.events?.map((event) => event.eventType) || [], ) const selectableEventKeys = allEventTypes.map((key) => { return { name: key, disabled: existedEventKeysSet.has(key) ? 'already added' : undefined, } }) if (selectableEventKeys.filter((item) => !item.disabled).length === 0) { throw new Error('No available events to add') } const { targetEventType } = await enquirer.prompt<{ targetEventType: string }>([ { type: 'autocomplete', name: 'targetEventType', message: 'Please select the event type you want to add:', // Prevents the object from being modified choices: selectableEventKeys, }, ]) const targetEventHandlerFileName = `${targetEventType.split(':').join('-')}` const addEventTasks: ListrTask[] = [ { title: 'Modify plugin.yaml', task: async () => { if (!Array.isArray(pluginConfigContent.events)) { pluginConfigContent.events = [] } pluginConfigContent.events.push({ eventType: targetEventType, function: allEvents[targetEventType].functionName, }) await updatePluginConfigContent(pluginConfigContent) }, }, { title: `Create backend/src/events/${targetEventType}.ts`, task: async () => { if (!(await fse.pathExists(path.join(currentWorkingDirectory, './backend/src/events')))) { await fse.mkdir(path.join(currentWorkingDirectory, './backend/src/events'), { recursive: true, }) } const eventHandlerContent = eventHandlerTemplate({ eventType: targetEventType, functionName: allEvents[targetEventType].functionName, }) await fse.writeFile( path.join( currentWorkingDirectory, `./backend/src/events/${targetEventHandlerFileName}.ts`, ), eventHandlerContent, ) }, }, { title: 'Modify backend/src/index.ts', task: async () => { await fse.writeFile( path.join(currentWorkingDirectory, './backend/src/index.ts'), `export * from './events/${targetEventHandlerFileName}'\n`, { flag: 'a', }, ) }, }, ] return addEventTasks }