var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var server_exports = {};
__export(server_exports, {
  serve: () => serve
});
module.exports = __toCommonJS(server_exports);
var import_replace_all = __toESM(require("@babel/runtime-corejs3/core-js/instance/replace-all"));
var import_node_fs = __toESM(require("node:fs"));
var import_node_path = __toESM(require("node:path"));
var import_chalk = __toESM(require("chalk"));
var import_dotenv_defaults = require("dotenv-defaults");
var import_execa = __toESM(require("execa"));
var import_open = __toESM(require("open"));
var import_smtp_server = require("smtp-server");
var import_api_server = require("@cedarjs/api-server");
var import_fastify_web = require("@cedarjs/fastify-web");
var import_logger = require("./lib/logger");
var import_graphqlProxy = require("./util/graphqlProxy");
var import_project = require("./util/project");
var import_rewriteWebIndexApiPort = require("./util/rewriteWebIndexApiPort");
async function serve({
  open: autoOpen,
  enableWeb
} = {
  open: false,
  enableWeb: false
}) {
  var _context, _context2;
  import_logger.logger.info("Starting Cedar Studio");
  process.env.RWJS_CWD = __dirname;
  const studioStateDirectory = (0, import_project.getStudioStatePath)();
  if (!import_node_fs.default.existsSync(studioStateDirectory)) {
    import_node_fs.default.mkdirSync(studioStateDirectory);
  }
  process.env.RW_STUDIO_DATABASE_URL = `file:${import_node_path.default.resolve(import_node_path.default.join(studioStateDirectory, "prisma.sqlite"))}?connection_limit=1`;
  const prismaSchemaPath = (0, import_replace_all.default)(_context = import_node_path.default.join(__dirname, "../db/schema.prisma")).call(_context, " ", "\\ ");
  import_logger.logger.info("Generating Prisma client");
  await import_execa.default.command(`npx prisma generate --schema ${prismaSchemaPath}`, {
    stdio: "inherit"
  });
  import_logger.logger.info("Migrating local Prisma database");
  await import_execa.default.command(`npx prisma migrate deploy --schema ${prismaSchemaPath}`, {
    stdio: "inherit"
  });
  const prismaSeedPath = (0, import_replace_all.default)(_context2 = import_node_path.default.join(__dirname, "lib", "seed.js")).call(_context2, " ", "\\ ");
  import_logger.logger.info("Running any seeding of the Prisma database");
  await import_execa.default.command(`node ${prismaSeedPath}`, {
    stdio: "inherit"
  });
  const userPaths = (0, import_project.getUserProjectPaths)();
  const userConfig = (0, import_project.getUserProjectConfig)();
  const studioConfig = (0, import_project.getStudioConfig)();
  const apiRootPath = enableWeb ? (0, import_fastify_web.coerceRootPath)(studioConfig.web.apiUrl) : "";
  const webPort = userConfig.studio.basePort;
  const apiPort = enableWeb ? webPort : webPort + 1;
  (0, import_dotenv_defaults.config)({
    path: import_node_path.default.join(userPaths.base, ".env"),
    defaults: import_node_path.default.join(userPaths.base, ".env.defaults"),
    multiline: true
  });
  (0, import_rewriteWebIndexApiPort.rewriteApiPortEnvVar)(apiPort);
  process.argv = [];
  const server = await (0, import_api_server.createServer)({
    apiRootPath
  });
  if (enableWeb) {
    await server.register(import_fastify_web.redwoodFastifyWeb);
  }
  await server.register(import_graphqlProxy.graphqlProxy);
  const {
    startWatchers
  } = await import("./util/fsWatching.js");
  await startWatchers();
  const {
    startConnectionWatching
  } = await import("./util/connectionWatching.js");
  startConnectionWatching();
  const {
    startSpanProcessor
  } = await import("./functions/otel-trace/otel-trace.js");
  startSpanProcessor();
  const {
    handleMail
  } = await import("./util/mail.js");
  const smtpServer = new import_smtp_server.SMTPServer({
    banner: "Cedar Studio SMTP Server",
    authOptional: true,
    hideSTARTTLS: true,
    onData: handleMail
  });
  smtpServer.listen(apiPort + 1, void 0, () => {
    import_logger.logger.info("Listening for mail...");
  });
  server.listen({
    port: apiPort
  });
  server.addHook("onReady", (done) => {
    import_logger.logger.info("Studio is up and running!");
    const prettyUrl = import_chalk.default.green(`http://localhost:${webPort}`);
    import_logger.logger.info(`To access the Studio, visit ${prettyUrl}`);
    if (autoOpen) {
      (0, import_open.default)(`http://localhost:${webPort}`);
    }
    done();
  });
  process.on("exit", () => {
    server.close();
  });
}
if (require.main === module) {
  serve();
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  serve
});
//# sourceMappingURL=server.js.map
