// src/prebuild.ts
import { mkdir } from "fs/promises";
import { join as join2 } from "path";

// src/feature/function/prebuild.ts
import { days, seconds, toDays, toSeconds } from "@awsless/duration";
import { mebibytes, toMebibytes } from "@awsless/size";
import { aws } from "@terraforge/aws";
import { Output, findInputDeps, resolveInputs } from "@terraforge/core";
import { pascalCase } from "change-case";
import { writeFile } from "fs/promises";
import { join } from "path";

// src/feature/function/build/typescript/rolldown.ts
import { createHash } from "crypto";
import { rolldown } from "rolldown";
import { importAsString } from "rollup-plugin-string-import";

// src/cli/ui/style.ts
import chalk from "chalk";
var color = {
  primary: chalk.bold.hex("#FF9000"),
  // primary: chalk.bold.magentaBright,
  // title: chalk.white,
  normal: chalk.reset.white,
  label: chalk.reset.white.bold,
  dim: chalk.dim,
  line: chalk.black,
  // link: chalk.cyan,
  info: chalk.blue,
  success: chalk.green,
  warning: chalk.yellow,
  error: chalk.red,
  attr: chalk.yellow
  // cursor: chalk.bgWhite.blackBright,
};

// src/cli/debug.ts
var queue = [];
var debugError = (error) => {
  queue.push({
    date: /* @__PURE__ */ new Date(),
    type: color.error.dim("error"),
    message: typeof error === "string" ? error : error instanceof Error ? color.error(error.message || "") : JSON.stringify(error)
  });
};

// src/feature/function/build/typescript/rolldown.ts
var bundleTypeScriptWithRolldown = async ({
  format = "esm",
  minify = true,
  file,
  nativeDir,
  external,
  importAsString: importAsStringList
}) => {
  const bundle = await rolldown({
    input: file,
    platform: "node",
    external: (importee) => {
      return importee.startsWith("@aws-sdk") || importee.startsWith("aws-sdk") || external?.includes(importee);
    },
    onwarn: (error) => {
      debugError(error.message);
    },
    treeshake: {
      moduleSideEffects: (id) => file === id
    },
    plugins: [
      // nodeResolve({ preferBuiltins: true }),
      // nativeDir
      // 	? natives({
      // 			copyTo: nativeDir,
      // 			targetEsm: format === 'esm',
      // 			sourcemap: true,
      // 		})
      // 	: undefined,
      importAsStringList ? importAsString({
        include: importAsStringList
      }) : void 0
    ]
  });
  const ext = format === "esm" ? "mjs" : "js";
  const result = await bundle.generate({
    format,
    sourcemap: "hidden",
    exports: "auto",
    entryFileNames: `index.${ext}`,
    chunkFileNames: `[name].${ext}`,
    minify
  });
  const hash = createHash("sha1");
  const files = [];
  for (const item of result.output) {
    if (item.type !== "chunk") {
      continue;
    }
    const code = Buffer.from(item.code, "utf8");
    const map = item.map ? Buffer.from(item.map.toString(), "utf8") : void 0;
    hash.update(code);
    files.push({
      name: item.fileName,
      code,
      map
    });
  }
  return {
    hash: hash.digest("hex"),
    files
  };
};

// src/feature/function/build/zip.ts
import { createReadStream } from "fs";
import JSZip from "jszip";
var zipFiles = (files) => {
  const zip = new JSZip();
  for (const file of files) {
    if ("path" in file) {
      zip.file(file.name, createReadStream(file.path));
    } else {
      zip.file(file.name, file.code);
    }
  }
  return zip.generateAsync({
    type: "nodebuffer",
    compression: "DEFLATE",
    compressionOptions: {
      level: 9
    }
  });
};

// src/feature/function/prebuild.ts
var prebuild = async (file, output, external = []) => {
  const bundle = await bundleTypeScriptWithRolldown({
    file,
    minify: true,
    external
  });
  const archive = await zipFiles(bundle.files);
  await writeFile(join(output, "HASH"), bundle.hash);
  await writeFile(join(output, "bundle.zip"), archive);
};

// src/prebuild.ts
var cwd = join2(process.cwd(), "./dist");
var builds = {
  rpc: "../src/feature/rpc/server/handle.ts",
  image: "../src/feature/image/server/handle.ts",
  icon: "../src/feature/icon/server/handle.ts",
  "on-failure": "../src/feature/on-failure/server/handle.ts",
  "on-error-log": "../src/feature/on-error-log/server/handle.ts"
};
for (const [name, file] of Object.entries(builds)) {
  const output = join2(cwd, "prebuild", name);
  await mkdir(output, { recursive: true });
  await prebuild(join2(cwd, file), output, ["sharp"]);
}
