/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const t = require('@babel/types');

const IMPORT_META_URL_MEMBER_EXPRESSION = t.memberExpression(
  t.memberExpression(t.identifier('import'), t.identifier('meta')),
  t.identifier('url')
);

/**
 * Appends calls to our own instrumentable import methods, providing access to
 * the imported modules.
 * ```
 * import x from 'mod';
 * // becomes:
 * import x from 'mod';
 * ContrastMethods.__importDefault(x, 'mod', import.meta.url);
 *
 * import * as x from 'mod';
 * // becomes:
 * import x from 'mod';
 * ContrastMethods.__importNamespace(x, 'mod', import.meta.url);
 *
 * import { foo, bar as baz } from 'mod';;
 * // becomes
 * ContrastMethods.__import(foo, 'foo', 'mod', import.meta.url);
 * ContrastMethods.__import(baz, 'bar', 'mod', import.meta.url);
 * ```
 * @param {import('@babel/traverse').NodePath<import('@babel/types').ImportDeclaration>} path
 * @param {import('.').State} state
 */
module.exports = function ImportDeclaration(path, state) {
  const { source, specifiers } = path.node;

  path.insertAfter(
    specifiers.map((importSpec) => {
      const spec = state.specs.find(({ type }) => type === importSpec.type);

      if (!spec || !state.callees[spec.name]) return;

      const args = [importSpec.local];

      if (t.isImportSpecifier(importSpec)) {
        args.push(
          t.isIdentifier(importSpec.imported)
            ? t.stringLiteral(importSpec.imported.name)
            : importSpec.imported
        );
      }

      args.push(source);
      args.push(IMPORT_META_URL_MEMBER_EXPRESSION);

      return t.callExpression(state.callees[spec.name], args);
    })
  );
};
