import { type BlipClient, BlipError, type Command, type CommandMethods, type Message, type MessageTypes, MultiSender, Node, type Sender, } from '../../index.ts' import { isReason } from '../../types/reason.ts' import { startChannel } from './communication.ts' export class PluginSender implements Sender { public readonly channel constructor() { this.channel = startChannel() } public async sendMessage(message: Message) { await this.sendCommand({ id: message.id, to: 'postmaster@scheduler.msging.net', uri: '/schedules', method: 'set', type: 'application/vnd.iris.schedule+json', resource: { message, when: new Date().toISOString(), }, }) } public async sendCommand(command: Command): Promise { const destination = this.getRealm() === 'desk' ? undefined : command.to && Node.from(command.to).domain?.endsWith('msging.net') ? 'MessagingHubService' : 'BlipService' try { return await this.channel.post('sendCommand', { command, destination }) } catch (err) { if (isReason(err)) { throw new BlipError(command.uri, err) } else if (BlipError.isFailedCommandResponse(err)) { throw BlipError.commandResponseToBlipError(command.uri, err) } throw err } } public static check(blipClient: BlipClient): PluginSender { const isPluginSender = blipClient.sender instanceof PluginSender if (isPluginSender) { return blipClient.sender } if (blipClient.sender instanceof MultiSender) { const pluginSender = blipClient.sender.findSender(PluginSender) if (pluginSender) { return pluginSender } } throw new Error('This command is only allowed for plugin senders') } public static getRealm(blipClient: BlipClient): 'portal' | 'desk' { return PluginSender.check(blipClient).getRealm() } private getRealm(): 'portal' | 'desk' { return this.channel.isDesk ? 'desk' : 'portal' } }