"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    default: ()=>content_script_wrapper
});
const external_fs_namespaceObject = require("fs");
var external_fs_default = /*#__PURE__*/ __webpack_require__.n(external_fs_namespaceObject);
const external_path_namespaceObject = require("path");
var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
function findUpLocalSync(filename, options) {
    const root = external_path_namespaceObject.parse(options.cwd).root;
    let currentDir = options.cwd;
    while(true){
        const candidate = external_path_namespaceObject.join(currentDir, filename);
        try {
            const stat = external_fs_namespaceObject.statSync(candidate);
            if (stat.isFile()) return candidate;
        } catch  {}
        if (currentDir === root) return;
        currentDir = external_path_namespaceObject.dirname(currentDir);
    }
}
function findNearestPackageJsonSync(manifestPath) {
    try {
        const manifestDir = external_path_namespaceObject.dirname(manifestPath);
        const packageJsonPath = findUpLocalSync('package.json', {
            cwd: manifestDir
        });
        return packageJsonPath || null;
    } catch (error) {
        console.warn('Failed to find package.json:', error);
        return null;
    }
}
const external_schema_utils_namespaceObject = require("schema-utils");
const core_namespaceObject = require("@swc/core");
const schema = {
    type: 'object',
    properties: {
        test: {
            type: 'string'
        },
        manifestPath: {
            type: 'string'
        },
        mode: {
            type: 'string'
        }
    }
};
function getSourceSignature(source) {
    const head = String(source || '').slice(0, 64);
    const tail = String(source || '').slice(-64);
    return `${String(source || '').length}:${head}:${tail}`;
}
function hasDefaultExport(source, resourcePath, compilation) {
    try {
        const ext = external_path_default().extname(resourcePath).toLowerCase();
        const isTS = '.ts' === ext || '.tsx' === ext || '.mts' === ext || '.mtsx' === ext;
        const isJSX = '.jsx' === ext || '.tsx' === ext || '.mjsx' === ext || '.mtsx' === ext;
        const abs = external_path_default().normalize(resourcePath);
        const sig = getSourceSignature(source);
        if (compilation) {
            compilation.__extjsHasDefaultExportCache ??= new Map();
            const cacheKey = `${abs}|${sig}`;
            const cached = compilation.__extjsHasDefaultExportCache.get(cacheKey);
            if ('boolean' == typeof cached) return cached;
        }
        const ast = (0, core_namespaceObject.parseSync)(source, {
            syntax: isTS ? "typescript" : "ecmascript",
            tsx: isTS && isJSX,
            jsx: !isTS && isJSX,
            decorators: true,
            dynamicImport: true,
            importAssertions: true,
            topLevelAwait: true
        });
        const body = Array.isArray(ast?.body) ? ast.body : [];
        for (const item of body)if (item && 'object' == typeof item) {
            if ('ExportDefaultDeclaration' === item.type || 'ExportDefaultExpression' === item.type) {
                if (compilation) compilation.__extjsHasDefaultExportCache?.set(`${abs}|${sig}`, true);
                return true;
            }
            if ('ExportNamedDeclaration' === item.type && Array.isArray(item.specifiers)) {
                for (const s of item.specifiers)if (s && 'object' == typeof s) {
                    if ('ExportDefaultSpecifier' === s.type) return true;
                    if ('ExportSpecifier' === s.type) {
                        const exported = s.exported;
                        if (exported && 'object' == typeof exported && ('Identifier' === exported.type && 'default' === exported.value || 'Ident' === exported.type && 'default' === exported.value || 'Str' === exported.type && 'default' === exported.value)) {
                            if (compilation) compilation.__extjsHasDefaultExportCache?.set(`${abs}|${sig}`, true);
                            return true;
                        }
                    }
                }
            }
        }
        if (compilation) compilation.__extjsHasDefaultExportCache?.set(`${abs}|${sig}`, false);
        return false;
    } catch (e) {
        const fallback = source.includes('export default');
        try {
            compilation?.__extjsHasDefaultExportCache?.set(`${external_path_default().normalize(resourcePath)}|${getSourceSignature(source)}`, fallback);
        } catch (error) {}
        return fallback;
    }
}
function content_script_wrapper(source) {
    const options = this.getOptions();
    const compilation = this._compilation;
    const manifestPath = options.manifestPath;
    const manifestDir = external_path_default().dirname(manifestPath);
    const packageJsonPath = findNearestPackageJsonSync(manifestPath);
    const packageJsonDir = packageJsonPath ? external_path_default().dirname(packageJsonPath) : manifestDir;
    const manifest = JSON.parse(external_fs_default().readFileSync(manifestPath, 'utf-8'));
    const isProd = 'production' === String(options && options.mode || '').toLowerCase();
    (0, external_schema_utils_namespaceObject.validate)(schema, options, {
        name: "scripts:content-script-wrapper",
        baseDataPath: 'options'
    });
    const declaredContentJsAbsEntries = [];
    const contentScripts = Array.isArray(manifest.content_scripts) ? manifest.content_scripts : [];
    for (const cs of contentScripts){
        const jsList = Array.isArray(cs?.js) ? cs.js : [];
        const runAtRaw = 'string' == typeof cs?.run_at ? cs.run_at : 'document_idle';
        const runAt = 'document_start' === runAtRaw || 'document_end' === runAtRaw || 'document_idle' === runAtRaw ? runAtRaw : 'document_idle';
        for (const js of jsList)declaredContentJsAbsEntries.push({
            abs: external_path_default().resolve(manifestDir, js),
            runAt
        });
    }
    const resourceAbsPath = external_path_default().normalize(this.resourcePath);
    const declaredEntry = declaredContentJsAbsEntries.find((entry)=>resourceAbsPath === external_path_default().normalize(entry.abs));
    const isDeclaredContentScript = Boolean(declaredEntry);
    const scriptsDir = external_path_default().resolve(packageJsonDir, "scripts");
    const relToScripts = external_path_default().relative(scriptsDir, resourceAbsPath);
    const isScriptsFolderScript = relToScripts && !relToScripts.startsWith('..') && !external_path_default().isAbsolute(relToScripts);
    const isContentScriptLike = isDeclaredContentScript || isScriptsFolderScript;
    const runAt = declaredEntry?.runAt || 'document_idle';
    if (!isContentScriptLike) return source;
    const resourceQuery = String(this.resourceQuery || '');
    const isInnerWrapperRequest = /\b__extjs_inner=1\b/.test(resourceQuery);
    if (!isInnerWrapperRequest) {
        if (isProd) {
            if (!isContentScriptLike) return source;
            if (!hasDefaultExport(source, this.resourcePath, compilation)) return source;
            if (source.includes('__EXTENSIONJS_MOUNT_WRAPPED__')) return source;
            const replaced = source.replace(/\bexport\s+default\b/, 'const __EXTENSIONJS_default__ =');
            let defaultName;
            {
                const m1 = source.match(/\bexport\s+default\s+function\s+([A-Za-z_$][\w$]*)\s*\(/);
                if (m1) defaultName = m1[1];
                else {
                    const m2 = source.match(/\bexport\s+default\s+([A-Za-z_$][\w$]*)\b/);
                    if (m2) defaultName = m2[1];
                }
            }
            let cleaned = replaced;
            if (defaultName) {
                const callPattern = new RegExp(`(^|\\n|;)\\s*${defaultName}\\s*\\(\\s*\\)\\s*;?\\s*(?=\\n|$)`, 'g');
                const next = cleaned.replace(callPattern, (_m, p1)=>p1 || '\n');
                if (next !== cleaned) {
                    cleaned = next;
                    this.emitWarning?.(new Error(`Removed direct call to ${defaultName}() to prevent double mount; wrapper handles mounting.`));
                }
            }
            const runtimeProdInline = "function __EXTENSIONJS_whenReady(runAt, cb){\n  try {\n    if (typeof document === 'undefined') { cb(); return function(){} }\n    if (runAt === 'document_start') { cb(); return function(){} }\n    var isDone = false;\n    function isReady(){\n      if (runAt === 'document_end') return document.readyState === 'interactive' || document.readyState === 'complete';\n      if (runAt === 'document_idle') return document.readyState !== 'loading';\n      return document.readyState === 'complete';\n    }\n    if (isReady()) { cb(); return function(){} }\n    var onReady = function(){\n      try {\n        if (isDone) return;\n        if (isReady()) { isDone = true; document.removeEventListener('readystatechange', onReady); cb(); }\n      } catch (e) {}\n    };\n    document.addEventListener('readystatechange', onReady);\n    return function(){ try { if (!isDone) document.removeEventListener('readystatechange', onReady); } catch (e) {} };\n  } catch (e) { try { cb(); } catch (_) {} return function(){} }\n}\nfunction __EXTENSIONJS_mount(mount, runAt){\n  var cleanup;\n  var cancelReady = function(){};\n  if (typeof mount !== \"function\") { try { console.warn(\"[extension.js] content script default export must be a function; skipping mount\") } catch (_) {} return function(){} }\n  function apply(){ try { cleanup = mount() } catch (e) { try { console.warn(\"[extension.js] content script default export failed to run\", e) } catch (_) {} } }\n  function unmount(){ try { cancelReady && cancelReady(); } catch (e) {} try { if (typeof cleanup === 'function') cleanup() } catch (e2) {} }\n  cancelReady = __EXTENSIONJS_whenReady(runAt, apply);\n  return unmount;\n}\n";
            const injected = `${runtimeProdInline}${cleaned}\n;/* __EXTENSIONJS_MOUNT_WRAPPED__ */\ntry { __EXTENSIONJS_mount(__EXTENSIONJS_default__, ${JSON.stringify(runAt)}) } catch (error) {}\nexport default __EXTENSIONJS_default__\n`;
            return injected;
        }
        const innerSpecifier = JSON.stringify(this.resourcePath.replace(/\\/g, '/') + '?__extjs_inner=1');
        const proxyCode = [
            "/* extension.js content script proxy */",
            'try {',
            "  if (typeof location === 'object' && location && !String(location.protocol || '').includes('-extension:')) {",
            "    var __extjsProto = (typeof Object === 'function' && Object.getPrototypeOf) ? Object.getPrototypeOf(location) : null;",
            "    if (__extjsProto && typeof __extjsProto.reload === 'function' && !__extjsProto.__extjsReloadPatched) {",
            '      __extjsProto.__extjsReloadPatched = true;',
            '      __extjsProto.__extjsOrigReload = __extjsProto.reload;',
            '      __extjsProto.reload = function(){',
            "        try { console.warn('[extension.js] blocked HMR-triggered location.reload() in content script context to prevent infinite reload loop. Fix the syntax error and HMR will recover on next successful compile.'); } catch (error) {}",
            '      };',
            '    }',
            '  }',
            '} catch (error) {',
            '  // Do nothing',
            '}',
            'try {',
            '  if (typeof __webpack_require__ === "function" || typeof __webpack_require__ === "object") {',
            '    var __extjsHasRuntime = !!(__webpack_require__.webExtRt && __webpack_require__.webExtRt.runtime && typeof __webpack_require__.webExtRt.runtime.getURL === "function");',
            '    if (!__extjsHasRuntime) {',
            '    var __extjsGetBase = function(){',
            '      try {',
            '        if (typeof document === "object" && document && document.documentElement) {',
            '          return document.documentElement.getAttribute("data-extjs-extension-base") || "";',
            '        }',
            '      } catch (e) {}',
            '      return "";',
            '    };',
            '    var __extjsBase = __extjsGetBase();',
            '    if (__extjsBase) {',
            '      __webpack_require__.p = __extjsBase.replace(/\\/+$/, "/");',
            '    }',
            '    var __extjsOrigHmrF = __webpack_require__.hmrF;',
            '    if (typeof __extjsOrigHmrF === "function") {',
            '      __webpack_require__.hmrF = function(){',
            '        var base = __extjsGetBase();',
            '        if (base) {',
            '          __webpack_require__.p = base.replace(/\\/+$/, "/");',
            '        }',
            '        return __extjsOrigHmrF();',
            '      };',
            '    }',
            '    if (!__extjsBase) {',
            '      var __extjsRetries = 0;',
            '      var __extjsUpdateBase = function(){',
            '        var base = __extjsGetBase();',
            '        if (base) {',
            '          __webpack_require__.p = base.replace(/\\/+$/, "/");',
            '        } else if (__extjsRetries++ < 50) {',
            '          setTimeout(__extjsUpdateBase, 100);',
            '        }',
            '      };',
            '      __extjsUpdateBase();',
            '    }',
            '    }',
            '  }',
            '} catch (e) {}',
            'function loadInnerWrappedModule(){',
            `  try { import(/* webpackMode: "eager" */ ${innerSpecifier}).catch(function(e){ console.warn('[extension.js] content script failed to load. waiting for next successful compile', e) }) } catch (e) { console.warn('[extension.js] content script failed to load. waiting for next successful compile', e) }`,
            '}',
            'loadInnerWrappedModule()',
            'try {',
            '  var hotModuleReplacement = (typeof module !== "undefined" && module && module.hot) ? module.hot : null;',
            '  if (hotModuleReplacement) {',
            '    var isExtensionJsDisposed = false;',
            '    if (typeof hotModuleReplacement.dispose === "function") hotModuleReplacement.dispose(function(){ isExtensionJsDisposed = true });',
            '    // Accept updates, but avoid triggering reload from inside accept callback',
            '    // (it can run during disposal and cause "[HMR] unexpected require(...) from disposed module" warnings).',
            '    if (typeof hotModuleReplacement.accept === "function") hotModuleReplacement.accept();',
            '    if (typeof hotModuleReplacement.addStatusHandler === "function") hotModuleReplacement.addStatusHandler(function(status){ if (isExtensionJsDisposed) return; if (status === "idle") loadInnerWrappedModule(); });',
            '  }',
            '} catch (error) {}'
        ].join('\n');
        return proxyCode;
    }
    if (!hasDefaultExport(source, this.resourcePath, compilation)) return source;
    if (source.includes('__EXTENSIONJS_MOUNT_WRAPPED__')) return source;
    const cssImportMatches = Array.from(source.matchAll(/import\s+(?:['\"](?<bare>[^'\"]+\.(css|sass|scss|less))['\"]|(?:(?:.+?)\s+from\s+['\"](?<from>[^'\"]+\.(css|sass|scss|less))['\"]))/g));
    const cssSpecifiers = cssImportMatches.map((m)=>m.groups?.bare || m.groups?.from);
    const vueImportMatches = Array.from(source.matchAll(/import\s+(?:['\"](?<bare>[^'\"]+\.vue)['\"]|(?:(?:.+?)\s+from\s+['\"](?<from>[^'\"]+\.vue)['\"]))/g));
    const vueSpecifiers = vueImportMatches.map((m)=>m.groups?.bare || m.groups?.from);
    const runtimeInline = "function __EXTENSIONJS_whenReady(runAt, cb){\n  try {\n    if (typeof document === 'undefined') { cb(); return function(){} }\n    if (runAt === 'document_start') { cb(); return function(){} }\n    var isDone = false;\n    function isReady(){\n      if (runAt === 'document_end') return document.readyState === 'interactive' || document.readyState === 'complete';\n      if (runAt === 'document_idle') return document.readyState !== 'loading';\n      return document.readyState === 'complete';\n    }\n    if (isReady()) { cb(); return function(){} }\n    var onReady = function(){\n      try {\n        if (isDone) return;\n        if (isReady()) { isDone = true; document.removeEventListener('readystatechange', onReady); cb(); }\n      } catch (e) {}\n    };\n    document.addEventListener('readystatechange', onReady);\n    return function(){ try { if (!isDone) document.removeEventListener('readystatechange', onReady); } catch (e) {} };\n  } catch (e) { try { cb(); } catch (_) {} return function(){} }\n}\nfunction __EXTENSIONJS_mountWithHMR(mount, runAt){\n  var cleanup;\n  var cancelReady = function(){};\n  if (typeof mount !== \"function\") { try { console.warn(\"[extension.js] content script default export must be a function; skipping mount\") } catch (_) {} return function(){} }\n  function apply(){ try { cleanup = mount() } catch (e) { try { console.warn(\"[extension.js] content script default export failed to run\", e) } catch (_) {} } }\n  function unmount(){ try { cancelReady && cancelReady(); } catch (e) {} try { if (typeof cleanup === 'function') cleanup() } catch (e2) {} }\n  function remount(){ unmount(); apply(); }\n  cancelReady = __EXTENSIONJS_whenReady(runAt, apply);\n  if (import.meta.webpackHot) {\n    if (typeof import.meta.webpackHot.accept === \"function\") import.meta.webpackHot.accept();\n    if (typeof import.meta.webpackHot.dispose === \"function\") import.meta.webpackHot.dispose(unmount);\n    if (typeof import.meta.webpackHot.addStatusHandler === \"function\") {\n      import.meta.webpackHot.addStatusHandler(function(s){ if (s==='abort'||s==='fail') { console.warn('[extension.js] HMR status:', s) } });\n    }\n  }\n  try {\n    var hot = (typeof module !== \"undefined\" && module && module.hot) ? module.hot : null;\n    if (hot) {\n      if (typeof hot.accept === \"function\") hot.accept();\n      if (typeof hot.dispose === \"function\") hot.dispose(unmount);\n      if (typeof hot.addStatusHandler === \"function\") {\n        hot.addStatusHandler(function(s){ if (s==='abort'||s==='fail') { console.warn('[extension.js] HMR status:', s) } });\n      }\n    }\n  } catch (e) {}\n  var cssEvt='__EXTENSIONJS_CSS_UPDATE__';\n  var onCss=function(){ remount() };\n  window.addEventListener(cssEvt, onCss);\n  return function(){ window.removeEventListener(cssEvt, onCss); unmount(); };\n}\n";
    if (/\bexport\s+default\s+[A-Za-z_$][\w$]*\s*\(/.test(source) && !/\bexport\s+default\s+function\b/.test(source)) {
        this.emitWarning?.(new Error('Default export appears to be an invocation. Export a function reference instead: `export default function init(){}` or `export default init`.'));
        return source;
    }
    const replaced = source.replace(/\bexport\s+default\b/, 'const __EXTENSIONJS_default__ =');
    let defaultName;
    {
        const m1 = source.match(/\bexport\s+default\s+function\s+([A-Za-z_$][\w$]*)\s*\(/);
        if (m1) defaultName = m1[1];
        else {
            const m2 = source.match(/\bexport\s+default\s+([A-Za-z_$][\w$]*)\b/);
            if (m2) defaultName = m2[1];
        }
    }
    let cleaned = replaced;
    if (defaultName) {
        const callPattern = new RegExp(`(^|\\n|;)\\s*${defaultName}\\s*\\(\\s*\\)\\s*;?\\s*(?=\\n|$)`, 'g');
        const next = cleaned.replace(callPattern, (_m, p1)=>p1 || '\n');
        if (next !== cleaned) {
            cleaned = next;
            this.emitWarning?.(new Error(`Removed direct call to ${defaultName}() to prevent double mount; wrapper handles mounting.`));
        }
    }
    const cssAccepts = cssSpecifiers.length ? `\ntry {\n  if (import.meta.webpackHot) {\n    ${cssSpecifiers.map((s)=>`import.meta.webpackHot.accept(${JSON.stringify(s)}, () => { try { window.dispatchEvent(new CustomEvent('__EXTENSIONJS_CSS_UPDATE__')) } catch (error) {} })`).join('\n    ')}\n  }\n} catch (error) {}\n` : '';
    const vueAccepts = vueSpecifiers.length ? `\ntry {\n  if (import.meta.webpackHot) {\n    ${vueSpecifiers.map((s)=>`import.meta.webpackHot.accept(${JSON.stringify(s)}, () => { try { window.dispatchEvent(new CustomEvent('__EXTENSIONJS_CSS_UPDATE__')) } catch (error) {} })`).join('\n    ')}\n  }\n} catch (error) {}\n` : '';
    const injected = `${runtimeInline}${cleaned}\n;/* __EXTENSIONJS_MOUNT_WRAPPED__ */\ntry { __EXTENSIONJS_mountWithHMR(__EXTENSIONJS_default__, ${JSON.stringify(runAt)}) } catch (error) {}\n${cssAccepts}${vueAccepts}export default __EXTENSIONJS_default__\n`;
    return injected;
}
exports["default"] = __webpack_exports__["default"];
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "default"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
