import { removeEnvPrefix } from './chunk-3E4HF4K3.js';
import { reflectType } from './chunk-DUVRJFW3.js';
import { getParsedTypeScriptConfig, getTsconfigFilePath } from './chunk-JRP7TVNX.js';
import { Compiler } from './chunk-GY3CS6YV.js';
import { installPackage } from './chunk-QZAEKS7V.js';
import { getDotenvDefaultTypeDefinition } from './chunk-HRPQF34B.js';
import { writeFile } from './chunk-4SEZDGHZ.js';
import { __name } from './chunk-6AXVLTU5.js';
import { LogLevelLabel } from '@storm-software/config-tools/types';
import { readJsonFile } from '@stryke/fs/read-file';
import { removeFile } from '@stryke/fs/remove-file';
import { hashDirectory } from '@stryke/hash/hash-files';
import { existsSync } from '@stryke/path/exists';
import { joinPaths } from '@stryke/path/join-paths';
import { nanoid } from '@stryke/unique-id/nanoid-client';
import { isString } from '@stryke/type-checks/is-string';
import { isUndefined } from '@stryke/type-checks/is-undefined';
import defu from 'defu';
import { loadEnv as loadEnv$1, loadEnvFile } from '@stryke/env/load-env';
import { loadConfig } from 'c12';
import { parseTypeDefinition } from '@stryke/convert/parse-type-definition';
import { isObject } from '@stryke/type-checks/is-object';
import { isSetString } from '@stryke/type-checks/is-set-string';
import { hash } from '@stryke/hash/hash';
import { getObjectDiff } from '@donedeal0/superdiff';
import { isPackageExists } from '@stryke/fs/package-fns';
import { StormJSON } from '@stryke/json/storm-json';
import { titleCase } from '@stryke/string-format/title-case';
import ts from 'typescript';
import { createDirectory } from '@stryke/fs/helpers';
import { throttle } from '@stryke/helpers/throttle';
import { joinPaths as joinPaths$1, existsSync as existsSync$1, findFilePath } from '@stryke/path/index';
import { createUnimport as createUnimport$1 } from 'unimport';

async function initContext(log, context, hooks) {
  log(LogLevelLabel.TRACE, `Initializing the context for the Storm Stack project.`);
  const packageJsonPath = joinPaths(context.options.projectRoot, "package.json");
  if (!existsSync(packageJsonPath)) {
    throw new Error(`Cannot find a \`package.json\` configuration file in ${context.options.projectRoot}.`);
  }
  context.packageJson = await readJsonFile(packageJsonPath);
  context.options.name ??= context.packageJson?.name;
  const projectJsonPath = joinPaths(context.options.projectRoot, "project.json");
  if (existsSync(projectJsonPath)) {
    context.projectJson = await readJsonFile(projectJsonPath);
    context.options.projectType ??= context.projectJson?.projectType;
    context.options.name ??= context.projectJson?.name;
    if (context.options.name?.startsWith("@") && context.options.name.split("/").filter(Boolean).length > 1) {
      context.options.name = context.options.name.split("/").filter(Boolean)[1];
    }
  }
  const checksum = await hashDirectory(context.options.projectRoot, {
    ignore: [
      "node_modules",
      ".git",
      ".nx",
      ".cache",
      ".storm",
      "tmp"
    ]
  });
  context.meta ??= {
    buildId: nanoid(24),
    releaseId: nanoid(24),
    checksum,
    timestamp: Date.now()
  };
  context.artifactsDir ??= ".storm";
  const metaFilePath = joinPaths(context.options.projectRoot, context.artifactsDir, "meta.json");
  try {
    if (existsSync(metaFilePath)) {
      context.persistedMeta = await readJsonFile(metaFilePath);
    }
  } catch {
    context.persistedMeta = void 0;
    await removeFile(metaFilePath);
  }
  await hooks.callHook("init:context", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occurred while initializing the context for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occurred while initializing the context for the Storm Stack project", {
      cause: error
    });
  });
}
__name(initContext, "initContext");
var loadEnvFiles = /* @__PURE__ */ __name(async (options, cwd, dotenv) => {
  let env = await loadEnv$1(cwd, options.mode);
  if (dotenv.additionalFiles.length > 0) {
    const additionalEnvFiles = await Promise.all(dotenv.additionalFiles.map(async (additionalEnvFile) => loadEnvFile(additionalEnvFile, cwd)));
    for (const additionalEnvFile of additionalEnvFiles) {
      env = defu(additionalEnvFile, env);
    }
  }
  return removeEnvPrefix(env);
}, "loadEnvFiles");
var loadEnvDirectory = /* @__PURE__ */ __name(async (directory, options, dotenv, cacheDir, packageJson, workspaceConfig) => {
  const [envResult, c12Result] = await Promise.all([
    loadEnvFiles(options, directory, dotenv),
    loadConfig({
      cwd: directory,
      name: "storm",
      envName: options.mode,
      defaults: {
        NAME: packageJson.name?.replace(`@${workspaceConfig.namespace}/`, ""),
        MODE: options.mode,
        ORG: workspaceConfig.organization
      },
      globalRc: true,
      packageJson: true,
      dotenv: true,
      jitiOptions: {
        fsCache: joinPaths(cacheDir, "jiti"),
        moduleCache: true
      }
    })
  ]);
  return defu(envResult, c12Result.config, workspaceConfig);
}, "loadEnvDirectory");
var loadEnv = /* @__PURE__ */ __name(async (options, dotenv, cacheDir, configDir, packageJson, workspaceConfig) => {
  const [project, workspace, config] = await Promise.all([
    loadEnvDirectory(options.projectRoot, options, dotenv, cacheDir, packageJson, workspaceConfig),
    loadEnvDirectory(workspaceConfig.workspaceRoot, options, dotenv, cacheDir, packageJson, workspaceConfig),
    loadEnvDirectory(configDir, options, dotenv, cacheDir, packageJson, workspaceConfig)
  ]);
  return defu(project, workspace, config);
}, "loadEnv");
async function reflectDotenvSecrets(log, context, file, name) {
  const secretsType = await reflectType(context, {
    file,
    name
  });
  return (void 0)(secretsType);
}
__name(reflectDotenvSecrets, "reflectDotenvSecrets");
async function reflectDotenvVariables(log, context, file, name) {
  let vars;
  if (file) {
    const varsType = await reflectType(context, {
      file,
      name
    });
    vars = (void 0)(varsType);
  }
  const defaultVarsType = await reflectType(context, getDotenvDefaultTypeDefinition(context));
  const defaultVars = (void 0)(defaultVarsType);
  if (vars) {
    defaultVars.getProperties().forEach((prop) => {
      if (!vars.hasProperty(prop.getName())) {
        vars.addProperty(prop.property);
      }
    });
  } else {
    vars = defaultVars;
  }
  return vars;
}
__name(reflectDotenvVariables, "reflectDotenvVariables");
async function reflectDotenvTypes(log, context) {
  const result = {};
  let params = {
    variables: `${getDotenvDefaultTypeDefinition(context).file}#${getDotenvDefaultTypeDefinition(context).name}`
  };
  if (!context.options.dotenv?.types) {
    log(LogLevelLabel.WARN, "No environment variable type definitions were provided in the `dotenv.types` configuration.");
  } else {
    params = isObject(context.options.dotenv.types) ? context.options.dotenv.types : {
      variables: `${context.options.dotenv.types}#Variables`,
      secrets: `${context.options.dotenv.types}#Secrets`
    };
  }
  result.variables ??= {};
  if (params.variables) {
    result.variables.typeDefinition = parseTypeDefinition(params.variables);
    if (result.variables.typeDefinition?.file && existsSync(joinPaths(context.options.projectRoot, result.variables.typeDefinition.file))) {
      result.variables.reflection = await reflectDotenvVariables(log, context, joinPaths(context.options.projectRoot, result.variables.typeDefinition.file), result.variables.typeDefinition.name);
    } else {
      log(LogLevelLabel.WARN, "Cannot find the `dotenv.types.variables` type definition in the provided configuration.");
      result.variables.reflection = await reflectDotenvVariables(log, context);
    }
  } else {
    log(LogLevelLabel.WARN, "The `dotenv.types.variables` configuration parameter was not provided. Please ensure this is expected.");
    result.variables.reflection = await reflectDotenvVariables(log, context);
  }
  if (params.secrets) {
    result.secrets ??= {};
    result.secrets.typeDefinition = parseTypeDefinition(params.secrets);
    if (!result.secrets.typeDefinition?.file) {
      throw new Error("Invalid type definition for secrets found in `dotenv.types.secrets` of the provided configuration.");
    }
    if (existsSync(joinPaths(context.options.projectRoot, result.secrets.typeDefinition.file))) {
      result.secrets.reflection = await reflectDotenvSecrets(log, context, joinPaths(context.options.projectRoot, result.secrets.typeDefinition.file), result.secrets.typeDefinition.name);
    } else {
      log(LogLevelLabel.WARN, "Cannot find the `dotenv.types.secrets` type definition in the provided configuration.");
    }
  } else {
    log(LogLevelLabel.WARN, "The `dotenv.types.secrets` configuration parameter was not provided. Please ensure this is expected.");
  }
  const varsReflection = (void 0).from(result.variables.reflection);
  let secretsReflection;
  if (result.secrets) {
    secretsReflection = (void 0).from(result.secrets.reflection);
  }
  log(LogLevelLabel.TRACE, `Resolved ${varsReflection.getProperties().length ?? 0} variable and ${secretsReflection?.getProperties().length ?? 0} secret dotenv definitions`);
  return result;
}
__name(reflectDotenvTypes, "reflectDotenvTypes");

// src/init/dotenv/index.ts
async function initDotenv(log, context, hooks) {
  log(LogLevelLabel.TRACE, `Initializing the context for the Storm Stack project.`);
  context.dotenv ??= {};
  context.dotenv.types = await reflectDotenvTypes(log, context);
  context.dotenv.additionalFiles = context.dotenv?.additionalFiles ?? [];
  context.dotenv.replace = Boolean(context.dotenv?.replace ?? context.options.projectType === "application");
  const env = defu(await loadEnv(context.options, context.dotenv, context.envPaths.cache, context.envPaths.config, context.packageJson, context.workspaceConfig), {
    APP_NAME: context.options.name || context.packageJson.name?.replace(`/${context.workspaceConfig.namespace}`, ""),
    APP_VERSION: context.packageJson.version,
    BUILD_ID: context.meta.buildId,
    BUILD_TIMESTAMP: context.meta.timestamp,
    BUILD_CHECKSUM: context.meta.checksum,
    RELEASE_ID: context.meta.releaseId,
    RELEASE_TAG: `${context.options.name}@${context.packageJson.version}`,
    MODE: context.options.mode,
    ORG: context.workspaceConfig.organization,
    ORGANIZATION: context.workspaceConfig.organization,
    PLATFORM: context.options.platform,
    STACKTRACE: context.options.mode === "development",
    ENVIRONMENT: context.options.mode,
    DEVELOPMENT: context.options.mode === "development",
    STAGING: context.options.mode === "staging",
    PRODUCTION: context.options.mode === "production",
    DEBUG: context.options.mode === "development"
  });
  context.dotenv.values = Object.keys(env).reduce((ret, key) => {
    let value = env[key];
    if (isString(value)) {
      value = `"${value.replaceAll('"', "")}"`;
    } else if (!isUndefined(value)) {
      value = String(value);
    }
    ret[key.replaceAll("(", "").replaceAll(")", "")] = value;
    return ret;
  }, env);
  await hooks.callHook("init:dotenv", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occurred while initializing the dotenv configuration for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occurred while initializing the dotenv configuration for the Storm Stack project", {
      cause: error
    });
  });
}
__name(initDotenv, "initDotenv");
function resolveEntry(options, entry) {
  const parsed = parseTypeDefinition(entry);
  const entryFile = parsed.file.replace(options.options.projectRoot, "").replaceAll("\\", "/").replaceAll(/^(?:\.\/)*/g, "");
  return {
    file: joinPaths(options.options.projectRoot, options.artifactsDir, `entry-${hash({
      file: entryFile,
      name: parsed.name
    }, {
      maxLength: 24
    }).replaceAll("-", "0").replaceAll("_", "1")}.ts`),
    name: parsed.name
  };
}
__name(resolveEntry, "resolveEntry");

// src/init/entry/index.ts
async function initEntry(log, context, hooks) {
  log(LogLevelLabel.TRACE, `Initializing the entry points for the Storm Stack project.`);
  if (context.options.projectType === "application" && context.options.entry) {
    if (isSetString(context.options.entry)) {
      context.entry = [
        {
          ...resolveEntry(context, context.options.entry),
          input: parseTypeDefinition(context.options.entry)
        }
      ];
    } else if (Array.isArray(context.options.entry) && context.options.entry.filter(Boolean).length > 0) {
      context.entry = context.options.entry.map((entry) => ({
        ...resolveEntry(context, entry),
        input: parseTypeDefinition(entry)
      })).filter(Boolean);
    }
  }
  await hooks.callHook("init:entry", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occurred while initializing the entry points for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occurred while initializing the entry points for the Storm Stack project", {
      cause: error
    });
  });
}
__name(initEntry, "initEntry");

// src/init/installs/node.ts
function getNodeDeps(context) {
  const result = {
    "@types/node": "devDependency"
  };
  if (context.options.projectType === "application") {
    result["@stryke/env"] = "dependency";
    result.unctx = "dependency";
  }
  return result;
}
__name(getNodeDeps, "getNodeDeps");

// src/init/installs/shared.ts
function getSharedDeps(context) {
  const result = {
    "@stryke/types": "devDependency",
    "@storm-stack/types": "devDependency"
  };
  if (context.options.projectType === "application") {
    result["@stryke/type-checks"] = "dependency";
    result["@stryke/json"] = "dependency";
    result["@stryke/url"] = "dependency";
    result["@stryke/http"] = "dependency";
    result.unstorage = "dependency";
  }
  return result;
}
__name(getSharedDeps, "getSharedDeps");

// src/init/installs/index.ts
async function initInstalls(log, context, hooks) {
  log(LogLevelLabel.TRACE, `Checking and installing missing project dependencies.`);
  context.installs = getSharedDeps(context);
  if (context.options.platform === "node") {
    const installs = getNodeDeps(context);
    context.installs = Object.keys(installs).reduce((ret, key) => {
      if (installs[key] && ret[key] !== "dependency") {
        ret[key] = installs[key];
      }
      return ret;
    }, context.installs);
  }
  await hooks.callHook("init:installs", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occured while installing project dependencies: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while installing project dependencies", {
      cause: error
    });
  });
  log(LogLevelLabel.TRACE, `The following packages must be installed as dependencies: ${Object.keys(context.installs).map((key) => `${key} (${context.installs[key]})`).join(", ")}`);
  for (const [key, value] of Object.entries(context.installs)) {
    await installPackage(log, context, key, value === "devDependency");
  }
}
__name(initInstalls, "initInstalls");
async function getTsconfigChanges(context) {
  const tsconfig = await getParsedTypeScriptConfig(context);
  const tsconfigJson = await readJsonFile(getTsconfigFilePath(context));
  tsconfigJson.compilerOptions ??= {};
  if (tsconfigJson.reflection !== true) {
    tsconfigJson.reflection = true;
  }
  if (tsconfig.options.experimentalDecorators !== true) {
    tsconfigJson.compilerOptions.experimentalDecorators = true;
  }
  if (tsconfig.options.emitDecoratorMetadata !== true) {
    tsconfigJson.compilerOptions.emitDecoratorMetadata = true;
  }
  if (!tsconfig.options.lib?.some((lib) => lib.toLowerCase() !== "esnext" && lib.toLowerCase() !== "es2021" && lib.toLowerCase() !== "es2022" && lib.toLowerCase() !== "es2023")) {
    tsconfigJson.compilerOptions.lib ??= [];
    tsconfigJson.compilerOptions.lib.push("esnext");
  }
  if (tsconfig.options.module !== ts.ModuleKind.ESNext) {
    tsconfigJson.compilerOptions.module = "ESNext";
  }
  if (!tsconfig.options.target || ![
    ts.ScriptTarget.ESNext,
    ts.ScriptTarget.ES2024,
    ts.ScriptTarget.ES2023,
    ts.ScriptTarget.ES2022,
    ts.ScriptTarget.ES2021
  ].includes(tsconfig.options.target)) {
    tsconfigJson.compilerOptions.target = "ESNext";
  }
  if (tsconfig.options.moduleResolution !== ts.ModuleResolutionKind.Bundler) {
    tsconfigJson.compilerOptions.moduleResolution = "Bundler";
  }
  if (tsconfig.options.moduleDetection !== ts.ModuleDetectionKind.Force) {
    tsconfigJson.compilerOptions.moduleDetection = "force";
  }
  if (tsconfig.options.allowSyntheticDefaultImports !== true) {
    tsconfigJson.compilerOptions.allowSyntheticDefaultImports = true;
  }
  if (tsconfig.options.noImplicitOverride !== true) {
    tsconfigJson.compilerOptions.noImplicitOverride = true;
  }
  if (tsconfig.options.noUncheckedIndexedAccess !== true) {
    tsconfigJson.compilerOptions.noUncheckedIndexedAccess = true;
  }
  if (tsconfig.options.skipLibCheck !== true) {
    tsconfigJson.compilerOptions.skipLibCheck = true;
  }
  if (tsconfig.options.resolveJsonModule !== true) {
    tsconfigJson.compilerOptions.resolveJsonModule = true;
  }
  if (tsconfig.options.isolatedModules !== true) {
    tsconfigJson.compilerOptions.isolatedModules = true;
  }
  if (tsconfig.options.verbatimModuleSyntax !== false) {
    tsconfigJson.compilerOptions.verbatimModuleSyntax = false;
  }
  if (tsconfig.options.allowJs !== true) {
    tsconfigJson.compilerOptions.allowJs = true;
  }
  if (tsconfig.options.esModuleInterop !== true) {
    tsconfigJson.compilerOptions.esModuleInterop = true;
  }
  if (tsconfig.options.declaration !== true) {
    tsconfigJson.compilerOptions.declaration = true;
  }
  if (context.options.platform === "browser") {
    if (tsconfig.options.jsx !== ts.JsxEmit.ReactJSX) {
      tsconfigJson.compilerOptions.jsx = "react-jsx";
    }
    if (!tsconfig.options.lib?.some((lib) => lib.toLowerCase() !== "dom")) {
      tsconfigJson.compilerOptions.lib ??= [];
      tsconfigJson.compilerOptions.lib.push("dom");
    }
    if (!tsconfig.options.lib?.some((lib) => lib.toLowerCase() !== "dom.iterable")) {
      tsconfigJson.compilerOptions.lib ??= [];
      tsconfigJson.compilerOptions.lib.push("dom.iterable");
    }
  } else if (context.options.platform === "node") {
    if (!tsconfig.options.types?.some((type) => type.toLowerCase() === "node" || type.toLowerCase() === "@types/node")) {
      tsconfigJson.compilerOptions.types ??= [];
      tsconfigJson.compilerOptions.types.push("node");
    }
  }
  return tsconfigJson;
}
__name(getTsconfigChanges, "getTsconfigChanges");

// src/init/tsconfig/index.ts
async function initTsconfig(log, context, hooks) {
  log(LogLevelLabel.TRACE, "Initializing TypeScript configuration for the Storm Stack project.");
  if (!isPackageExists("typescript")) {
    throw new Error('The TypeScript package is not installed. Please install the package using the command: "npm install typescript --save-dev"');
  }
  const originalTsconfigJson = await readJsonFile(context.options.tsconfig);
  const json = await getTsconfigChanges(context);
  if (!json.include?.some((filterPattern) => filterPattern.includes(joinPaths(context.artifactsDir, "**/*.ts")))) {
    json.include ??= [];
    json.include.push(joinPaths(context.artifactsDir, "**/*.ts"));
  }
  await writeFile(log, context.options.tsconfig, StormJSON.stringify(json));
  await hooks.callHook("init:tsconfig", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occured while resolving the TypeScript options: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while resolving the TypeScript options", {
      cause: error
    });
  });
  const result = getObjectDiff(originalTsconfigJson, await readJsonFile(context.options.tsconfig), {
    ignoreArrayOrder: true,
    showOnly: {
      statuses: [
        "added",
        "deleted",
        "updated"
      ],
      granularity: "deep"
    }
  });
  const changes = [];
  const getChanges = /* @__PURE__ */ __name((difference, property) => {
    if (difference.status === "added" || difference.status === "deleted" || difference.status === "updated") {
      if (difference.diff) {
        for (const diff of difference.diff) {
          getChanges(diff, property ? `${property}.${difference.property}` : difference.property);
        }
      } else {
        changes.push({
          field: property ? `${property}.${difference.property}` : difference.property,
          status: difference.status,
          previous: difference.status === "added" ? "---" : StormJSON.stringify(difference.previousValue),
          current: difference.status === "deleted" ? "---" : StormJSON.stringify(difference.currentValue)
        });
      }
    }
  }, "getChanges");
  for (const diff of result.diff) {
    getChanges(diff);
  }
  if (changes.length > 0) {
    log(LogLevelLabel.WARN, `Updating the following configuration values in the "tsconfig.json" file:

  ${changes.map((change, i) => `${i + 1}. ${titleCase(change.status)} the ${change.field} field:
   - Previous: ${change.previous}
   - Current: ${change.current}
  `).join("\n")}
  `);
  }
  context.tsconfig = await getParsedTypeScriptConfig(context);
  if (!context.tsconfig) {
    throw new Error("Failed to parse the TypeScript configuration file.");
  }
}
__name(initTsconfig, "initTsconfig");
var lastImportsDump;
function createUnimport(log, context) {
  log(LogLevelLabel.TRACE, "Creating Unimport context with Storm Stack presets");
  const unimport = createUnimport$1({
    commentsDisable: [
      "@unimport-disable",
      "@imports-disable",
      "@storm-disable",
      "@storm-ignore"
    ],
    commentsDebug: [
      "@unimport-debug",
      "@imports-debug",
      "@storm-debug"
    ],
    injectAtEnd: true,
    presets: context.unimportPresets
  });
  async function dumpImports() {
    log(LogLevelLabel.TRACE, "Dumping import file...");
    const items = await unimport.getImports();
    const importDumpFile = joinPaths$1(context.options.projectRoot, context.artifactsDir, "imports-dump.json");
    if (!existsSync$1(findFilePath(importDumpFile))) {
      await createDirectory(findFilePath(importDumpFile));
    }
    log(LogLevelLabel.TRACE, `Writing imports-dump JSON file: ${importDumpFile}`);
    const content = StormJSON.stringify(items);
    if (content.trim() !== lastImportsDump?.trim()) {
      lastImportsDump = content;
      await writeFile(log, importDumpFile, content);
    }
  }
  __name(dumpImports, "dumpImports");
  const dumpImportsThrottled = throttle(dumpImports, 500);
  async function injectImports(source) {
    const result = await unimport.injectImports(source.code, source.id);
    if (!source.code.hasChanged()) {
      return source;
    }
    await dumpImportsThrottled();
    return {
      ...source,
      code: result.s
    };
  }
  __name(injectImports, "injectImports");
  return {
    ...unimport,
    dumpImports: dumpImportsThrottled,
    injectImports
  };
}
__name(createUnimport, "createUnimport");

// src/init/unimport/index.ts
async function initUnimport(log, context, hooks) {
  log(LogLevelLabel.TRACE, `Initializing Unimport for the Storm Stack project.`);
  const runtimeDir = joinPaths(context.artifactsDir, "runtime");
  context.unimportPresets = [
    {
      imports: [
        "StormJSON"
      ],
      from: "@stryke/json"
    },
    {
      imports: [
        "StormURL"
      ],
      from: "@stryke/url"
    },
    {
      imports: [
        "parseCookie",
        "parseSetCookie",
        "serializeCookie",
        "splitSetCookieString"
      ],
      from: "@stryke/http"
    },
    {
      imports: [
        "StormError",
        "createStormError",
        "isStormError",
        "getErrorFromUnknown"
      ],
      from: joinPaths(runtimeDir, "error")
    },
    {
      imports: [
        "StormRequest"
      ],
      from: joinPaths(runtimeDir, "request")
    },
    {
      imports: [
        "StormResponse"
      ],
      from: joinPaths(runtimeDir, "response")
    },
    {
      imports: [
        "StormLog"
      ],
      from: joinPaths(runtimeDir, "log")
    },
    {
      imports: [
        "uniqueId",
        "getRandom"
      ],
      from: joinPaths(runtimeDir, "id")
    },
    {
      imports: [
        "storage"
      ],
      from: joinPaths(runtimeDir, "storage")
    }
  ];
  if (context.options.platform === "node") {
    context.unimportPresets.push({
      imports: [
        "builder"
      ],
      from: joinPaths(runtimeDir, "app")
    });
    context.unimportPresets.push({
      imports: [
        "envPaths",
        "getBuildInfo",
        "getRuntimeInfo",
        "useStorm",
        "STORM_ASYNC_CONTEXT"
      ].filter(Boolean),
      from: joinPaths(runtimeDir, "context")
    });
    context.unimportPresets.push({
      imports: [
        "StormEvent"
      ],
      from: joinPaths(runtimeDir, "event")
    });
  }
  await hooks.callHook("init:unimport", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occured while initializing Unimport for the Storm Stack project configuration: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while initializing Unimport for the Storm Stack project configuration", {
      cause: error
    });
  });
  context.unimport = createUnimport(log, context);
  await context.unimport.init();
}
__name(initUnimport, "initUnimport");

// src/init/index.ts
async function init(log, context, hooks) {
  await hooks.callHook("init:begin", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occured while starting initialization for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while starting initialization for the Storm Stack project", {
      cause: error
    });
  });
  await initContext(log, context, hooks);
  await initInstalls(log, context, hooks);
  await initTsconfig(log, context, hooks);
  await initUnimport(log, context, hooks);
  const handlePreTransform = /* @__PURE__ */ __name(async (context2, sourceFile) => {
    await hooks.callHook("build:pre-transform", context2, sourceFile).catch((error) => {
      log(LogLevelLabel.ERROR, `An error occured while pre-transforming the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
      throw new Error("An error occured while pre-transforming the Storm Stack project", {
        cause: error
      });
    });
  }, "handlePreTransform");
  const handleTransform = /* @__PURE__ */ __name(async (context2, sourceFile) => {
    await hooks.callHook("build:transform", context2, sourceFile).catch((error) => {
      log(LogLevelLabel.ERROR, `An error occured while transforming the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
      throw new Error("An error occured while transforming the Storm Stack project", {
        cause: error
      });
    });
  }, "handleTransform");
  const handlePostTransform = /* @__PURE__ */ __name(async (context2, sourceFile) => {
    await hooks.callHook("build:post-transform", context2, sourceFile).catch((error) => {
      log(LogLevelLabel.ERROR, `An error occured while post-transforming the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
      throw new Error("An error occured while post-transforming the Storm Stack project", {
        cause: error
      });
    });
  }, "handlePostTransform");
  context.compiler = new Compiler(context, {
    onPreTransform: handlePreTransform,
    onTransform: handleTransform,
    onPostTransform: handlePostTransform
  });
  await initDotenv(log, context, hooks);
  await initEntry(log, context, hooks);
  await hooks.callHook("init:complete", context).catch((error) => {
    log(LogLevelLabel.ERROR, `An error occured while finishing initialization for the Storm Stack project: ${error.message} 
${error.stack ?? ""}`);
    throw new Error("An error occured while finishing initialization for the Storm Stack project", {
      cause: error
    });
  });
}
__name(init, "init");

export { init };
//# sourceMappingURL=chunk-SVE2Q6ZT.js.map
//# sourceMappingURL=chunk-SVE2Q6ZT.js.map