a fun bot for the hc slack
at main 1.3 kB view raw
1import { parse } from "yaml"; 2 3type template = "app.startup"; 4 5interface data { 6 environment?: string; 7} 8 9const file = await Bun.file("src/libs/templates.yaml").text(); 10const templatesRaw = parse(file); 11 12function flatten(obj: Record<string, unknown>, prefix = "") { 13 let result: Record<string, unknown> = {}; 14 15 for (const key in obj) { 16 if (typeof obj[key] === "object" && Array.isArray(obj[key]) === false) { 17 result = { 18 ...result, 19 ...flatten( 20 obj[key] as Record<string, unknown>, 21 `${prefix}${key}.`, 22 ), 23 }; 24 } else { 25 result[`${prefix}${key}`] = obj[key]; 26 } 27 } 28 29 return result; 30} 31 32const templates = flatten(templatesRaw); 33 34export function t(template: template, data: data) { 35 return t_format(t_fetch(template), data); 36} 37 38export function t_fetch(template: template) { 39 return Array.isArray(templates[template]) 40 ? (randomChoice(templates[template]) as string) 41 : (templates[template] as string); 42} 43 44export function t_format(template: string, data: data) { 45 return template.replace( 46 /\${(.*?)}/g, 47 (_, key) => data[key as keyof data] ?? "", 48 ); 49} 50 51export function randomChoice<T>(arr: T[]): T { 52 if (arr.length === 0) { 53 throw new Error("Cannot get random choice from empty array"); 54 } 55 return arr[Math.floor(Math.random() * arr.length)] as T; 56}