#!/usr/bin/env node
import T from "@fastify/static";
import w from "fastify";
import j from "open";
import a from "path";
import { fileURLToPath as k } from "url";
import { jsonStringifyTwoSpaces as S } from "@p-lc/shared";
import c from "fs";
import { isObject as h } from "lodash-uni";
const y = process.cwd();
console.log(`cwd: ${y}`);
const e = a.join(y, "package.json");
c.existsSync(e) || (console.log(`The package.json file does not exists. ${e}`), process.exit(-1));
const u = "lc-types", f = "lc-types.json";
async function E(t) {
  t.get("/load-lc-types", async (o, n) => {
    n.type("application/json").code(200);
    const r = await l(), s = {
      code: 0,
      data: J(r)
    }, i = m(r);
    return i ? {
      code: 0,
      data: await g(i)
    } : s;
  }), t.post("/save-lc-types", async (o, n) => {
    n.type("application/json").code(200);
    const r = o.body, s = await l();
    if (!s) return { code: -1 };
    P(r, s);
    let i = m(s);
    return i || (d(e, {
      ...s,
      [u]: f
    }), i = a.join(
      e,
      "..",
      f
    )), await d(i, r), {
      code: 0
    };
  });
}
async function l() {
  if (!c.existsSync(e)) return;
  const t = await g(e);
  if (h(t)) return t;
}
async function g(t) {
  const o = await c.promises.readFile(t, "utf-8");
  return JSON.parse(o);
}
async function d(t, o) {
  await c.promises.writeFile(t, S(o) + `
`);
}
function J(t) {
  return P(
    {
      pkgName: "",
      pkgVersion: "",
      name: "Package display name",
      components: []
    },
    t
  );
}
function P(t, o) {
  return {
    ...t,
    pkgName: o?.name,
    pkgVersion: o?.version
  };
}
function m(t) {
  if (!t) return;
  const o = t[u];
  if (o)
    return a.join(e, "..", o);
}
const p = w();
p.register(T, {
  root: a.join(k(import.meta.url), "../../editor"),
  prefix: "/editor"
});
p.register(E, { prefix: "/apis" });
p.listen({ port: 7392 }, (t, o) => {
  if (t) throw t;
  const n = `${o}/editor/`;
  console.log(`Editor address: ${n}`), j(n);
});
//# sourceMappingURL=index.mjs.map
