'use strict';

var node_fs = require('node:fs');
var node_module = require('node:module');
var path = require('node:path');
var node_url = require('node:url');
var wasm = require('vite-plugin-wasm');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopNamespaceDefault(e) {
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);

const WASM_GLUE = ["@vultisig/lib-dkls", "@vultisig/lib-schnorr", "@vultisig/lib-mldsa"];
const ADDITIONAL_WASM_EXCLUDES = ["7z-wasm"];
const sdkPackageJson = node_url.fileURLToPath(new URL("../../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
const requireFromSdk = node_module.createRequire(sdkPackageJson);
const DEFAULT_ALIASES = {
  crypto: requireFromSdk.resolve("crypto-browserify"),
  "node:crypto": requireFromSdk.resolve("crypto-browserify"),
  stream: requireFromSdk.resolve("stream-browserify"),
  "node:stream": requireFromSdk.resolve("stream-browserify"),
  buffer: requireFromSdk.resolve("buffer/"),
  "node:buffer": requireFromSdk.resolve("buffer/"),
  util: requireFromSdk.resolve("util/"),
  "node:util": requireFromSdk.resolve("util/"),
  path: requireFromSdk.resolve("path-browserify"),
  "node:path": requireFromSdk.resolve("path-browserify"),
  events: requireFromSdk.resolve("events/"),
  "node:events": requireFromSdk.resolve("events/"),
  process: requireFromSdk.resolve("process/browser"),
  "node:process": requireFromSdk.resolve("process/browser"),
  "node-fetch": "isomorphic-fetch"
};
const DEFAULT_OPT_INCLUDE = ["buffer", "process", "crypto-browserify", "stream-browserify", "events"];
const nodePolyfillsPackageDir = path__namespace.dirname(path__namespace.dirname(requireFromSdk.resolve("vite-plugin-node-polyfills")));
const BUFFER_SHIM_FILE = path__namespace.join(nodePolyfillsPackageDir, "shims/buffer/dist/index.js");
const PROCESS_SHIM_FILE = path__namespace.join(nodePolyfillsPackageDir, "shims/process/dist/index.js");
const GLOBAL_SHIM_FILE = path__namespace.join(nodePolyfillsPackageDir, "shims/global/dist/index.js");
function vultisig(userOptions = {}) {
  const {
    sevenZipWasm = true,
    walletCoreWasm = true,
    nodePolyfills: useNodePolyfills = false,
    shimResolver: useShimResolver = true,
    aliases: userAliases = {},
    optimizeDeps: userOptimize = {},
    defineGlobal = true,
    browserGlobals = true,
    debug = false
  } = userOptions;
  let configRoot = process.cwd();
  let command = "build";
  let sevenZipWasmFile;
  let walletCoreWasmFile;
  const mergedAliases = { ...DEFAULT_ALIASES, ...userAliases };
  const excludeList = [...WASM_GLUE, ...ADDITIONAL_WASM_EXCLUDES, ...userOptimize.exclude ?? []];
  const includeList = [...DEFAULT_OPT_INCLUDE, ...userOptimize.include ?? []];
  const resolveSevenZipWasmFile = () => {
    if (sevenZipWasmFile) return sevenZipWasmFile;
    const requireFromRoot = node_module.createRequire(path__namespace.join(configRoot, "package.json"));
    const resolvers = [requireFromRoot, requireFromSdk];
    for (const resolver of resolvers) {
      try {
        const pkgDir = path__namespace.dirname(resolver.resolve("7z-wasm/package.json"));
        const file = path__namespace.join(pkgDir, "7zz.wasm");
        if (node_fs.existsSync(file)) {
          sevenZipWasmFile = file;
          return file;
        }
      } catch {
      }
    }
    return void 0;
  };
  const resolveWalletCoreWasmFile = () => {
    if (walletCoreWasmFile) return walletCoreWasmFile;
    const requireFromRoot = node_module.createRequire(path__namespace.join(configRoot, "package.json"));
    const resolvers = [requireFromRoot, requireFromSdk];
    for (const resolver of resolvers) {
      try {
        const pkgDir = path__namespace.dirname(resolver.resolve("@trustwallet/wallet-core/package.json"));
        const file = path__namespace.join(pkgDir, "dist/lib/wallet-core.wasm");
        if (node_fs.existsSync(file)) {
          walletCoreWasmFile = file;
          return file;
        }
      } catch {
      }
    }
    return void 0;
  };
  const serveWasmFile = (res, file) => {
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/wasm");
    res.setHeader("Cache-Control", "no-cache");
    res.end(node_fs.readFileSync(file));
  };
  const configPlugin = {
    name: "vultisig-sdk:config",
    enforce: "pre",
    config() {
      return {
        resolve: {
          alias: { ...mergedAliases }
        },
        define: defineGlobal ? { global: "globalThis", "process.env": "{}", "process.env.NODE_DEBUG": '""' } : {},
        optimizeDeps: {
          ...userOptimize,
          include: includeList,
          exclude: excludeList
        }
      };
    }
  };
  const browserGlobalsPlugin = {
    name: "vultisig-sdk:browser-globals",
    enforce: "pre",
    transformIndexHtml() {
      if (!browserGlobals) return [];
      return [
        {
          tag: "script",
          children: [
            "globalThis.process ??= {}",
            "globalThis.process.env ??= {}",
            "globalThis.process.browser ??= true",
            'globalThis.process.version ??= ""',
            "globalThis.process.versions ??= {}",
            "globalThis.process.nextTick ??= ((callback, ...args) => queueMicrotask(() => callback(...args)))"
          ].join("\n"),
          injectTo: "head-prepend"
        }
      ];
    }
  };
  const shimPlugin = {
    name: "vultisig-sdk:polyfill-shim-resolver",
    enforce: "pre",
    resolveId(id) {
      if (!useShimResolver) return null;
      if (id === "vite-plugin-node-polyfills/shims/buffer") {
        return BUFFER_SHIM_FILE;
      }
      if (id === "vite-plugin-node-polyfills/shims/process") {
        return PROCESS_SHIM_FILE;
      }
      if (id === "vite-plugin-node-polyfills/shims/global") {
        return GLOBAL_SHIM_FILE;
      }
      return null;
    }
  };
  const wasmAssetsPlugin = {
    name: "vultisig-sdk:wasm-assets",
    enforce: "pre",
    configResolved(c) {
      configRoot = c.root;
      command = c.command;
    },
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        const url = req.url?.split("?")[0] ?? "";
        if (sevenZipWasm && url === "/7zz.wasm") {
          const file = resolveSevenZipWasmFile();
          if (!file) {
            process.stderr.write("[vultisig-sdk] Failed to resolve 7z-wasm/7zz.wasm for dev server\n");
            res.statusCode = 404;
            res.end("7zz.wasm not found");
            return;
          }
          if (debug) {
            process.stderr.write(`[vultisig-sdk] Serving 7zz.wasm from ${file}
`);
          }
          serveWasmFile(res, file);
          return;
        }
        if (walletCoreWasm && url.endsWith("/wallet-core.wasm")) {
          const file = resolveWalletCoreWasmFile();
          if (!file) {
            process.stderr.write(
              "[vultisig-sdk] Failed to resolve @trustwallet/wallet-core/dist/lib/wallet-core.wasm for dev server\n"
            );
            res.statusCode = 404;
            res.end("wallet-core.wasm not found");
            return;
          }
          if (debug) {
            process.stderr.write(`[vultisig-sdk] Serving wallet-core.wasm from ${file}
`);
          }
          serveWasmFile(res, file);
          return;
        }
        next();
        return;
      });
    },
    buildStart() {
      if (command !== "build") return;
      if (sevenZipWasm) {
        const file = resolveSevenZipWasmFile();
        if (!file) {
          this.error(
            "[vultisig-sdk] Failed to resolve 7z-wasm/7zz.wasm. Set `sevenZipWasm: false` only if you host `/7zz.wasm` yourself."
          );
        }
        this.emitFile({
          type: "asset",
          fileName: "7zz.wasm",
          source: node_fs.readFileSync(file)
        });
        if (debug) {
          process.stderr.write(`[vultisig-sdk] Emitted 7zz.wasm from ${file}
`);
        }
      }
      if (!walletCoreWasm) return;
      const walletCoreFile = resolveWalletCoreWasmFile();
      if (!walletCoreFile) {
        this.error(
          "[vultisig-sdk] Failed to resolve @trustwallet/wallet-core/dist/lib/wallet-core.wasm. Set `walletCoreWasm: false` only if you host it yourself."
        );
      }
      this.emitFile({
        type: "asset",
        fileName: "assets/wallet-core.wasm",
        source: node_fs.readFileSync(walletCoreFile)
      });
      if (debug) {
        process.stderr.write(`[vultisig-sdk] Emitted wallet-core.wasm from ${walletCoreFile}
`);
      }
    }
  };
  const out = [configPlugin, browserGlobalsPlugin, wasm()];
  if (useShimResolver) out.push(shimPlugin);
  if (useNodePolyfills) {
    const { nodePolyfills: nodePolyfillsFactory } = requireFromSdk("vite-plugin-node-polyfills");
    out.push(
      nodePolyfillsFactory({
        exclude: ["fs"],
        globals: { Buffer: true, global: true, process: true },
        protocolImports: true
      })
    );
  }
  out.push(wasmAssetsPlugin);
  return out;
}

module.exports = vultisig;
//# sourceMappingURL=index.cjs.map
