"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var css_modules_typescript_loader_exports = {};
__export(css_modules_typescript_loader_exports, {
  default: () => css_modules_typescript_loader_default,
  wrapQuotes: () => wrapQuotes
});
module.exports = __toCommonJS(css_modules_typescript_loader_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_line_diff = __toESM(require("line-diff"));
var import_css = require("../css");
const bannerMessage = "// This file is automatically generated.\n// Please do not change this file!";
const cssModuleExport = "export const cssExports: CssExports;\nexport default cssExports;\n";
const getNoDeclarationFileError = ({ filename }) => new Error(
  `Generated type declaration does not exist. Run webpack and commit the type declaration for '${filename}'`
);
const getTypeMismatchError = ({
  filename,
  expected,
  actual
}) => {
  const diff = new import_line_diff.default(
    enforceLFLineSeparators(actual),
    expected
  ).toString();
  return new Error(
    `Generated type declaration file is outdated. Run webpack and commit the updated type declaration for '${filename}'

${diff}`
  );
};
function wrapQuotes(key) {
  const isValidIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key);
  if (isValidIdentifier) {
    return key;
  }
  return `'${key}'`;
}
const cssModuleToInterface = (cssModuleKeys) => {
  const interfaceFields = cssModuleKeys.sort().map((key) => `  ${wrapQuotes(key)}: string;`).join("\n");
  return `interface CssExports {
${interfaceFields}
}`;
};
const filenameToTypingsFilename = (filename) => {
  const dirName = import_path.default.dirname(filename);
  const baseName = import_path.default.basename(filename);
  return import_path.default.join(dirName, `${baseName}.d.ts`);
};
const enforceLFLineSeparators = (text) => {
  if (text) {
    return text.replace(/\r\n/g, "\n");
  } else {
    return text;
  }
};
const compareText = (contentA, contentB) => {
  return enforceLFLineSeparators(contentA) === enforceLFLineSeparators(contentB);
};
const validModes = ["emit", "verify"];
const isFileNotFound = (err) => err && err.code === "ENOENT";
const makeDoneHandlers = (callback, content, rest) => ({
  failed: (e) => callback(e),
  success: () => callback(null, content, ...rest)
});
const makeFileHandlers = (filename) => ({
  read: (handler) => import_fs.default.readFile(filename, { encoding: "utf-8" }, handler),
  write: (content, handler) => import_fs.default.writeFile(filename, content, { encoding: "utf-8" }, handler)
});
const extractLocalExports = (content) => {
  let localExports = content.split("exports.locals")[1];
  if (!localExports) {
    localExports = content.split("___CSS_LOADER_EXPORT___.locals")[1];
  }
  return localExports;
};
const getCssModuleKeys = (content) => {
  const keyRegex = /"([^\\"]+)":/g;
  let match;
  const cssModuleKeys = [];
  const localExports = extractLocalExports(content);
  while (match = keyRegex.exec(localExports)) {
    if (cssModuleKeys.indexOf(match[1]) < 0) {
      cssModuleKeys.push(match[1]);
    }
  }
  return cssModuleKeys;
};
function css_modules_typescript_loader_default(content, ...rest) {
  const { failed, success } = makeDoneHandlers(this.async(), content, rest);
  const filename = this.resourcePath;
  const { mode = "emit", modules = true } = this.getOptions() || {};
  if (!validModes.includes(mode)) {
    return failed(new Error(`Invalid mode option: ${mode}`));
  }
  if (!(0, import_css.isCssModules)(filename, modules) || (0, import_css.isInNodeModules)(filename)) {
    return success();
  }
  const cssModuleInterfaceFilename = filenameToTypingsFilename(filename);
  const { read, write } = makeFileHandlers(cssModuleInterfaceFilename);
  const cssModuleKeys = this.cssModuleKeys || getCssModuleKeys(content);
  const cssModuleDefinition = `${bannerMessage}
${cssModuleToInterface(
    cssModuleKeys
  )}
${cssModuleExport}`;
  if (mode === "verify") {
    read((err, fileContents) => {
      if (isFileNotFound(err)) {
        return failed(
          getNoDeclarationFileError({
            filename: cssModuleInterfaceFilename
          })
        );
      }
      if (err) {
        return failed(err);
      }
      if (!compareText(cssModuleDefinition, fileContents)) {
        return failed(
          getTypeMismatchError({
            filename: cssModuleInterfaceFilename,
            expected: cssModuleDefinition,
            actual: fileContents
          })
        );
      }
      return success();
    });
  } else {
    read((_, fileContents) => {
      if (!compareText(cssModuleDefinition, fileContents)) {
        write(cssModuleDefinition, (err) => {
          if (err) {
            failed(err);
          } else {
            success();
          }
        });
      } else {
        success();
      }
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  wrapQuotes
});
