"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _AssetsRetryPlugin_retryOptions;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetsRetryPlugin = void 0;
const utils_1 = require("@modern-js/utils");
// @ts-expect-error
const webpack_sources_1 = require("webpack-sources");
const utils_2 = require("../utils");
const util_1 = require("./util");
const path_1 = __importDefault(require("path"));
const url_1 = require("../url");
class AssetsRetryPlugin {
    constructor(options) {
        _AssetsRetryPlugin_retryOptions.set(this, void 0);
        const { distDir, HtmlPlugin, inlineScript = true, ...retryOptions } = options;
        this.name = 'AssetsRetryPlugin';
        __classPrivateFieldSet(this, _AssetsRetryPlugin_retryOptions, retryOptions, "f");
        this.distDir = distDir;
        this.HtmlPlugin = HtmlPlugin;
        this.inlineScript = inlineScript;
        this.scriptPath = '';
    }
    async getRetryCode() {
        const { default: serialize } = await Promise.resolve().then(() => __importStar(require('../../compiled/serialize-javascript')));
        const runtimeFilePath = (0, utils_2.getSharedPkgCompiledPath)('assetsRetry.js');
        const runtimeCode = await utils_1.fs.readFile(runtimeFilePath, 'utf-8');
        return `(function(){${runtimeCode};init(${serialize(__classPrivateFieldGet(this, _AssetsRetryPlugin_retryOptions, "f"))});})()`;
    }
    async getScriptPath() {
        if (!this.scriptPath) {
            const version = await (0, util_1.getBuilderVersion)();
            this.scriptPath = path_1.default.join(this.distDir, `assets-retry.${version}.js`);
        }
        return this.scriptPath;
    }
    apply(compiler) {
        if (!this.inlineScript) {
            compiler.hooks.thisCompilation.tap(this.name, (compilation) => {
                compilation.hooks.processAssets.tapPromise({
                    name: this.name,
                    stage: util_1.COMPILATION_PROCESS_STAGE.PROCESS_ASSETS_STAGE_PRE_PROCESS,
                }, async (assets) => {
                    const scriptPath = await this.getScriptPath();
                    assets[scriptPath] = new webpack_sources_1.RawSource(await this.getRetryCode(), false);
                });
            });
        }
        compiler.hooks.compilation.tap(this.name, compilation => {
            this.HtmlPlugin.getHooks(compilation).afterTemplateExecution.tapPromise(this.name, async (data) => {
                const scriptTag = (0, util_1.generateScriptTag)();
                if (this.inlineScript) {
                    data.headTags.unshift({
                        ...scriptTag,
                        innerHTML: await this.getRetryCode(),
                    });
                }
                else {
                    const publicPath = (0, util_1.getPublicPathFromCompiler)(compiler);
                    const url = (0, url_1.withPublicPath)(await this.getScriptPath(), publicPath);
                    data.headTags.unshift({
                        ...scriptTag,
                        attributes: {
                            ...scriptTag.attributes,
                            src: url,
                        },
                    });
                }
                return data;
            });
        });
    }
}
exports.AssetsRetryPlugin = AssetsRetryPlugin;
_AssetsRetryPlugin_retryOptions = new WeakMap();
