scroll/src/common/runtime.ts

205 lines
4.9 KiB
JavaScript
Raw Normal View History

2024-07-05 15:51:30 -04:00
/**
* Functions/Methods that depend on the current runtime to function
*/
import process from 'node:process';
import Ansi from './ansi.ts';
import { IRuntime, ITerminalSize, ITestBase } from './types.ts';
2023-11-29 16:09:58 -05:00
import { noop } from './fns.ts';
import {
defaultTerminalSize,
SCROLL_LOG_FILE_PREFIX,
SCROLL_LOG_FILE_SUFFIX,
} from './config.ts';
2023-11-29 16:09:58 -05:00
export type { IFileIO, IRuntime, ITerminal } from './types.ts';
2023-11-29 14:55:57 -05:00
/**
* Which Typescript runtime is currently being used
*/
export enum RunTimeType {
Bun = 'bun',
Deno = 'deno',
2024-07-05 15:51:30 -04:00
Tsx = 'tsx',
Unknown = 'common',
}
2024-07-05 15:51:30 -04:00
/**
* The label for type/severity of the log entry
*/
export enum LogLevel {
Debug = 'Debug',
Info = 'Info',
Notice = 'Notice',
Warning = 'Warning',
Error = 'Error',
}
2023-11-29 14:55:57 -05:00
let scrollRuntime: IRuntime | null = null;
// ----------------------------------------------------------------------------
// Misc runtime functions
// ----------------------------------------------------------------------------
2023-11-01 15:05:31 -04:00
/**
* Get the size of the terminal window via ANSI codes
* @see https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html#window-size-the-hard-way
*/
async function _getTerminalSizeFromAnsi(): Promise<ITerminalSize> {
const { term } = await getRuntime();
// Tell the cursor to move to Row 999 and Column 999
// Since this command specifically doesn't go off the screen
// When we ask where the cursor is, we should get the size of the screen
await term.writeStdout(
Ansi.moveCursorForward(999) + Ansi.moveCursorDown(999),
);
// Ask where the cursor is
await term.writeStdout(Ansi.GetCursorLocation);
// Get the first chunk from stdin
// The response is \x1b[(rows);(cols)R..
const chunk = await term.readStdinRaw();
if (chunk === null) {
return defaultTerminalSize;
}
const rawCode = (new TextDecoder()).decode(chunk);
const res = rawCode.trim().replace(/^.\[([0-9]+;[0-9]+)R$/, '$1');
const [srows, scols] = res.split(';');
const rows = parseInt(srows, 10) ?? 24;
const cols = parseInt(scols, 10) ?? 80;
// Clear the screen
await term.writeStdout(Ansi.ClearScreen + Ansi.ResetCursor);
return {
rows,
cols,
};
}
/**
* Basic logging -
*/
export function log(
s: unknown,
level: LogLevel = LogLevel.Notice,
data?: any,
): void {
2023-11-29 16:09:58 -05:00
getRuntime().then(({ file }) => {
const rawS = JSON.stringify(s, null, 2);
const rawData = JSON.stringify(data, null, 2);
const output = (typeof data !== 'undefined')
? `${rawS}\n${rawData}\n\n`
: `${rawS}\n`;
const outputFile =
`${SCROLL_LOG_FILE_PREFIX}-${level.toLowerCase()}${SCROLL_LOG_FILE_SUFFIX}`;
file.appendFile(outputFile, output).then(noop);
2023-11-29 16:09:58 -05:00
});
2023-11-24 08:31:51 -05:00
}
export const logDebug = (s: unknown, data?: any) =>
log(s, LogLevel.Debug, data);
export const logInfo = (s: unknown, data?: any) => log(s, LogLevel.Info, data);
export const logNotice = (s: unknown, data?: any) =>
log(s, LogLevel.Notice, data);
export const logWarning = (s: unknown, data?: any) =>
log(s, LogLevel.Warning, data);
export const logError = (s: unknown, data?: any) =>
log(s, LogLevel.Warning, data);
2023-11-16 16:00:03 -05:00
/**
* Kill program, displaying an error message
* @param s
*/
2023-11-16 13:00:02 -05:00
export function die(s: string | Error): void {
2023-11-29 16:09:58 -05:00
logError(s);
process.stdin.setRawMode(false);
console.error(s);
getRuntime().then((r) => r.exit());
2023-11-02 13:06:48 -04:00
}
2023-11-01 15:05:31 -04:00
/**
* Determine which Typescript runtime we are operating under
*/
2023-11-16 16:00:03 -05:00
export function runtimeType(): RunTimeType {
2024-07-05 15:51:30 -04:00
let runtime = RunTimeType.Tsx;
2023-11-01 15:05:31 -04:00
if ('Deno' in globalThis) {
runtime = RunTimeType.Deno;
2023-11-01 15:05:31 -04:00
}
if ('Bun' in globalThis) {
runtime = RunTimeType.Bun;
2023-11-01 15:05:31 -04:00
}
return runtime;
}
2023-11-16 13:00:02 -05:00
/**
* Get the adapter object for the current Runtime
*/
export async function getRuntime(): Promise<IRuntime> {
if (scrollRuntime === null) {
2023-11-16 16:00:03 -05:00
const runtime = runtimeType();
const path = `../${runtime}/mod.ts`;
const pkg = await import(path);
if ('default' in pkg) {
scrollRuntime = pkg.default;
}
2024-07-02 14:50:21 -04:00
if (scrollRuntime !== null) {
return Promise.resolve(scrollRuntime);
}
return Promise.reject('Missing default import');
}
2024-07-02 14:50:21 -04:00
return Promise.resolve(scrollRuntime);
}
2023-11-01 15:05:31 -04:00
2023-11-16 16:00:03 -05:00
/**
* Get the common test interface object
*/
export async function getTestRunner(): Promise<ITestBase> {
const runtime = runtimeType();
const path = `../${runtime}/test_base.ts`;
const pkg = await import(path);
if ('default' in pkg) {
return pkg.default;
}
return pkg;
}
2023-11-01 15:05:31 -04:00
/**
* Import a runtime-specific module
*
2023-11-16 16:00:03 -05:00
* e.g. to load "src/bun/mod.ts", if the runtime is bun,
2023-11-01 15:05:31 -04:00
* you can use like so `await importForRuntime('index')`;
*
* @param path - the path within the runtime module
*/
export const importForRuntime = async (path: string) => {
2023-11-16 16:00:03 -05:00
const runtime = runtimeType();
2023-11-01 15:25:52 -04:00
const suffix = '.ts';
2023-11-01 15:05:31 -04:00
const base = `../${runtime}/`;
2023-11-29 14:55:57 -05:00
const pathParts = path
.split('/')
2023-11-01 15:05:31 -04:00
.filter((part) => part !== '' && part !== '.' && part !== suffix)
.map((part) => part.replace(suffix, ''));
const cleanedPath = pathParts.join('/');
const importPath = base + cleanedPath + suffix;
2023-11-16 16:00:03 -05:00
const pkg = await import(importPath);
2023-11-03 11:59:58 -04:00
if ('default' in pkg) {
return pkg.default;
}
2023-11-16 16:00:03 -05:00
return pkg;
2023-11-03 11:59:58 -04:00
};