import { getTermios } from './termios.ts'; import { IRuntime, RunTimeType } from './types.ts'; let scrollRuntime: IRuntime | null = null; /** * Kill program, displaying an error message * @param s */ export async function die(s: string | Error): Promise { (await getTermios()).disableRawMode(); console.error(s); (await getRuntime()).exit(); } /** * Determine which Typescript runtime we are operating under */ export function getRuntimeType(): RunTimeType { let runtime = RunTimeType.Unknown; if ('Deno' in globalThis) { runtime = RunTimeType.Deno; } if ('Bun' in globalThis) { runtime = RunTimeType.Bun; } return runtime; } export async function getRuntime(): Promise { if (scrollRuntime === null) { const runtime = getRuntimeType(); const path = `../${runtime}/mod.ts`; const pkg = await import(path); if ('default' in pkg) { scrollRuntime = pkg.default; } } return Promise.resolve(scrollRuntime!); } /** * Import a runtime-specific module * * eg. to load "src/bun/mod.ts", if the runtime is bun, * you can use like so `await importForRuntime('index')`; * * @param path - the path within the runtime module */ export const importForRuntime = async (path: string) => { const runtime = getRuntimeType(); const suffix = '.ts'; const base = `../${runtime}/`; const pathParts = path.split('/') .filter((part) => part !== '' && part !== '.' && part !== suffix) .map((part) => part.replace(suffix, '')); const cleanedPath = pathParts.join('/'); const importPath = base + cleanedPath + suffix; return await import(importPath); }; /** * Import the default export for a runtime-specific module * (this is just a simple wrapper of `importForRuntime`) * * @param path - the path within the runtime module */ export const importDefaultForRuntime = async (path: string) => { const pkg = await importForRuntime(path); if ('default' in pkg) { return pkg.default; } return null; };