import { HOST_URL } from "../../config.ts";
import type { I_CommandCode } from "../command_runner.ts";
import { Command } from "./enum.ts";
export const run_command = {
command: Command.run,
aliases: ['start'],
description: 'Runs an application hosted on Viapak',
help_text: [],
execute: async ( { args: [ name, version, ...args ] }: { args: string[] }) => {
if(name.includes('@')) {
[name, version] = name.split('@');
args.unshift(version);
} else if(!version) {
version = 'latest';
}
await runScript(`${HOST_URL}/${name}@${version}`, {
env: Deno.env.toObject(),
args,
});
}
} as I_CommandCode;
const runScript = async (url: string, options?: Deno.CommandOptions) => {
try {
const command = new Deno.Command("deno", {
args: ["run", "-A", url, ...(options?.args ?? [])],
env: options?.env,
stdout: "piped",
stderr: "piped",
});
const process = command.spawn();
const stdoutReader = process.stdout.getReader();
const stderrReader = process.stderr.getReader();
const readStream = async (reader: ReadableStreamDefaultReader<Uint8Array>, type: "stdout" | "stderr") => {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = new TextDecoder().decode(value);
if (type === "stdout") console.log(text);
else console.error(text);
}
};
await Promise.all([
readStream(stdoutReader, "stdout"),
readStream(stderrReader, "stderr"),
]);
const status = await process.status;
if (!status.success) {
throw new Error();
}
} catch (_) {
console.log();
console.error('Viapak > The script did not exit gracefully!');
}
}