index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import fs from "fs/promises";
  2. import { AppPath } from "./path";
  3. import { Log } from "../util/log";
  4. import { Context } from "../util/context";
  5. import { Config } from "./config";
  6. export namespace App {
  7. const log = Log.create({ service: "app" });
  8. export type Info = Awaited<ReturnType<typeof create>>;
  9. const ctx = Context.create<Info>("app");
  10. async function create(input: { directory: string }) {
  11. const dataDir = AppPath.data(input.directory);
  12. await fs.mkdir(dataDir, { recursive: true });
  13. await Log.file(input.directory);
  14. log.info("creating");
  15. const config = await Config.load(input.directory);
  16. log.info("created", { path: dataDir });
  17. const services = new Map<any, any>();
  18. const result = {
  19. get services() {
  20. return services;
  21. },
  22. get config() {
  23. return config;
  24. },
  25. get root() {
  26. return input.directory;
  27. },
  28. service<T extends (app: any) => any>(service: any, init: T) {},
  29. };
  30. return result;
  31. }
  32. export function state<T extends (app: Info) => any>(key: any, init: T) {
  33. return () => {
  34. const app = ctx.use();
  35. const services = app.services;
  36. if (!services.has(key)) {
  37. log.info("registering service", { name: key });
  38. services.set(key, init(app));
  39. }
  40. return services.get(key) as ReturnType<T>;
  41. };
  42. }
  43. export async function use() {
  44. return ctx.use();
  45. }
  46. export async function provide<T extends (app: Info) => any>(
  47. input: { directory: string },
  48. cb: T,
  49. ) {
  50. const app = await create(input);
  51. return ctx.provide(app, () => cb(app));
  52. }
  53. }