'use strict';

const node_path = require('node:path');
const node_fs = require('node:fs');
const compiler = require('vue/compiler-sfc');
const vue = require('vue');
const serverRenderer = require('vue/server-renderer');
const moduleFromString = require('module-from-string');
const index = require('./shared/vue-email.f0fc4372.cjs');
require('@flowko/tw-to-css');

function _interopNamespaceCompat(e) {
  if (e && typeof e === 'object' && 'default' in e) return e;
  const n = Object.create(null);
  if (e) {
    for (const k in e) {
      n[k] = e[k];
    }
  }
  n.default = e;
  return n;
}

const compiler__namespace = /*#__PURE__*/_interopNamespaceCompat(compiler);

function isObject(item) {
  return !!item && typeof item === "object" && !Array.isArray(item);
}
function deepmerge(target, ...sources) {
  if (!sources.length)
    return target;
  const source = sources.shift();
  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key])
          Object.assign(target, { [key]: {} });
        deepmerge(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }
  return deepmerge(target, ...sources);
}
function createInitConfig(options) {
  const config = deepmerge(
    {
      verbose: true,
      options: options.options
    },
    options
  );
  return config;
}

let enabled = true;
// Support both browser and node environments
const globalVar = typeof self !== 'undefined'
    ? self
    : typeof window !== 'undefined'
        ? window
        : typeof global !== 'undefined'
            ? global
            : {};
/**
 * Detect how much colors the current terminal supports
 */
let supportLevel = 0 /* none */;
if (globalVar.process && globalVar.process.env && globalVar.process.stdout) {
    const { FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, COLORTERM } = globalVar.process.env;
    if (NODE_DISABLE_COLORS || NO_COLOR || FORCE_COLOR === '0') {
        enabled = false;
    }
    else if (FORCE_COLOR === '1' ||
        FORCE_COLOR === '2' ||
        FORCE_COLOR === '3') {
        enabled = true;
    }
    else if (TERM === 'dumb') {
        enabled = false;
    }
    else if ('CI' in globalVar.process.env &&
        [
            'TRAVIS',
            'CIRCLECI',
            'APPVEYOR',
            'GITLAB_CI',
            'GITHUB_ACTIONS',
            'BUILDKITE',
            'DRONE',
        ].some(vendor => vendor in globalVar.process.env)) {
        enabled = true;
    }
    else {
        enabled = process.stdout.isTTY;
    }
    if (enabled) {
        // Windows supports 24bit True Colors since Windows 10 revision #14931,
        // see https://devblogs.microsoft.com/commandline/24-bit-color-in-the-windows-console/
        if (process.platform === 'win32') {
            supportLevel = 3 /* trueColor */;
        }
        else {
            if (COLORTERM && (COLORTERM === 'truecolor' || COLORTERM === '24bit')) {
                supportLevel = 3 /* trueColor */;
            }
            else if (TERM && (TERM.endsWith('-256color') || TERM.endsWith('256'))) {
                supportLevel = 2 /* ansi256 */;
            }
            else {
                supportLevel = 1 /* ansi */;
            }
        }
    }
}
let options = {
    enabled,
    supportLevel,
};
function kolorist(start, end, level = 1 /* ansi */) {
    const open = `\x1b[${start}m`;
    const close = `\x1b[${end}m`;
    const regex = new RegExp(`\\x1b\\[${end}m`, 'g');
    return (str) => {
        return options.enabled && options.supportLevel >= level
            ? open + ('' + str).replace(regex, open) + close
            : '' + str;
    };
}
const bold = kolorist(1, 22);
const blue = kolorist(34, 39);
const lightGreen = kolorist(92, 39);

const scriptIdentifier = "_sfc_main";
async function templateRender(name, source, options, config) {
  const output = compile(name, source, config?.verbose);
  const component = moduleFromString.importFromStringSync(output, {
    transformOptions: { loader: "ts" }
  }).default;
  if (config?.verbose) {
    console.warn(`${lightGreen("\u{1F48C}")} ${bold(blue("Generating output"))}`);
  }
  const app = vue.createApp(component, options?.props);
  app.use(index.VueEmailPlugin, config?.options);
  const markup = await serverRenderer.renderToString(app);
  const doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
  const doc = `${doctype}${replaceString(markup)}`;
  if (config?.verbose) {
    console.warn(`${lightGreen("\u{1F389}")} ${bold(blue("Rendering template"))} ${bold(lightGreen(name))}`);
  }
  return doc;
}
function compile(filename, source, verbose = false) {
  let styles = null;
  if (verbose) {
    console.warn(`${lightGreen("\u{1F6A7}")} ${bold(blue("Compiling"))} ${bold(lightGreen(filename))} ${bold(blue("file"))}`);
  }
  const { descriptor, errors } = compiler__namespace.parse(source, {
    filename
  });
  if (errors.length) {
    throw new Error(errors.join("\n"));
  }
  const script = compiler__namespace.compileScript(descriptor, {
    id: descriptor.filename,
    genDefaultAs: scriptIdentifier
  });
  if (descriptor.styles.length) {
    styles = compiler__namespace.compileStyle({
      id: descriptor.filename,
      filename,
      source: descriptor.styles[0].content,
      scoped: descriptor.styles.some((s) => s.scoped)
    });
  }
  const template = compiler__namespace.compileTemplate({
    filename,
    id: descriptor.filename,
    source: descriptor.template.content,
    compilerOptions: {
      bindingMetadata: script.bindings
    }
  });
  const output = `
  ${template.code}

  ${script.content}
  ${styles ? `const styles = \`${styles.code}\`` : ""}
  ${scriptIdentifier}.render = render
  ${styles ? `${scriptIdentifier}.style = styles` : ""}
  export default _sfc_main
  `;
  return output;
}
function replaceString(str) {
  if (!str || typeof str !== "string")
    return str;
  return str.replace(/ data-v-inspector="[^"]*"/g, "").replace(/<!--\[-->/g, "").replace(/<!--]-->/g, "").replace(/<template>/g, "").replace(/<template[^>]*>/g, "").replace(/<\/template>/g, "");
}

const config = (dir, config2 = {}) => {
  const defaultConfig = createInitConfig(config2);
  return {
    render: (name, options) => {
      const path = dir ? node_path.resolve(dir, name) : name;
      const source = readFile(path);
      return templateRender(name, source, options, defaultConfig);
    }
  };
};
function readFile(path) {
  return node_fs.readFileSync(path, "utf-8").toString();
}

exports.config = config;
exports.templateRender = templateRender;
