silverbullet/cli/plug_run.ts

59 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-05 00:56:55 +08:00
import { DiskSpacePrimitives } from "../common/spaces/disk_space_primitives.ts";
import { AssetBundle } from "../plugos/asset_bundle/bundle.ts";
2023-08-30 03:17:29 +08:00
import { sleep } from "$sb/lib/async.ts";
2023-08-26 14:31:51 +08:00
import { ServerSystem } from "../server/server_system.ts";
import { AssetBundlePlugSpacePrimitives } from "../common/spaces/asset_bundle_space_primitives.ts";
import { EndpointHook } from "../plugos/hooks/endpoint.ts";
import { LocalShell } from "../server/shell_backend.ts";
2024-01-14 01:07:02 +08:00
import { Hono } from "../server/deps.ts";
import { KvPrimitives } from "../plugos/lib/kv_primitives.ts";
2023-08-12 02:37:13 +08:00
2023-08-05 00:56:55 +08:00
export async function runPlug(
spacePath: string,
2023-08-12 02:37:13 +08:00
functionName: string | undefined,
2023-08-05 00:56:55 +08:00
args: string[] = [],
builtinAssetBundle: AssetBundle,
kvPrimitives: KvPrimitives,
httpServerPort?: number,
httpHostname?: string,
2023-08-05 00:56:55 +08:00
) {
2023-08-12 02:37:13 +08:00
const serverController = new AbortController();
2024-01-14 01:07:02 +08:00
const app = new Hono();
2023-08-26 14:31:51 +08:00
const endpointHook = new EndpointHook("/_/");
2023-08-26 14:31:51 +08:00
const serverSystem = new ServerSystem(
new AssetBundlePlugSpacePrimitives(
new DiskSpacePrimitives(spacePath),
builtinAssetBundle,
),
kvPrimitives,
new LocalShell(spacePath),
false,
2023-08-26 14:31:51 +08:00
);
2023-11-02 19:46:33 +08:00
await serverSystem.init(true);
app.use((context, next) => {
return endpointHook.handleRequest(serverSystem.system!, context, next);
});
if (httpHostname && httpServerPort) {
Deno.serve({
hostname: httpHostname,
port: httpServerPort,
signal: serverController.signal,
}, app.fetch);
}
2023-08-12 02:37:13 +08:00
if (functionName) {
const result = await serverSystem.system.invokeFunction(functionName, args);
2023-08-26 14:31:51 +08:00
await serverSystem.close();
2023-08-12 02:37:13 +08:00
serverController.abort();
return result;
} else {
console.log("Running in server mode, use Ctrl-c to stop");
while (true) {
await sleep(1000);
}
2023-08-05 00:56:55 +08:00
}
}