export class Cli {
constructor(public author: string) {}
fetch = async (req: Request) => {
const url = new URL(req.url);
const [name, ...args] = url.pathname.slice(1).split("/");
if (!name) {
return new Response("Not Found", { status: 404 });
}
const esmUrl = `https://esm.town/v/${this.author}/${name}`;
const { output, code } = await this.run(esmUrl, { args });
if (code !== 0) {
return new Response(output, { status: 500 });
}
return new Response(output, { status: 200 });
};
run = async (url: string, options: {
args: string[];
}) => {
const { default: runFn } = await import(url);
if (typeof runFn !== "function") {
throw new Error("Val should have a default export that is a function");
}
const logs: string[] = [];
globalThis.console = new Proxy(console, {
get(target, key) {
const real = target[key];
if (typeof real === "function" && typeof key === "string") {
const fn = function(...args: any[]) {
logs.push(args.join(" "));
return real.call(this, ...args);
};
return fn;
}
},
});
try {
await runFn(options.args);
return { output: logs.join("\n"), code: 0 };
} catch (err) {
return { output: logs.join("\n"), code: 1 };
}
};
}
export function createCli(author: string) {
return new Cli(author);
}