/*
	MIT License http://www.opensource.org/licenses/mit-license.php
*/

"use strict";

const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");

/** @typedef {import("../Compilation")} Compilation */

class PublicPathRuntimeModule extends RuntimeModule {
	constructor() {
		super("publicPath");
	}

	/**
	 * @returns {string} runtime code
	 */
	generate() {
		const publicPath = this.compilation.outputOptions.publicPath || "auto";
		if (publicPath === "auto") {
			return `${RuntimeGlobals.publicPath} = (() => {
				if ("currentScript" in document) {
					return document.currentScript.src.replace(/[^\\/]+$/, "");
				} else if ("_getCurrentScript" in document) {
					return document._getCurrentScript().src.replace(/[^\\/]+$/, "");
				} else {
					return ${JSON.stringify(
						this.compilation.getPath(
							this.compilation.outputOptions.publicPath || "",
							{
								hash: this.compilation.hash || "XXXX"
							}
						)
					)};
				}
			})();`;
		} else {
			return `${RuntimeGlobals.publicPath} = ${JSON.stringify(
				this.compilation.getPath(publicPath || "", {
					hash: this.compilation.hash || "XXXX"
				})
			)};`;
		}
	}
}

module.exports = PublicPathRuntimeModule;

@@ -798,200 +798,165 @@
 %09%09%09%09
-return $%7BJSON.stringify(%0A%09%09%09%09%09%09this.compilation.getPath(%0A%09%09%09%09%09%09%09this.compilation.outputOptions.publicPath %7C%7C %22%22,%0A%09%09%09%09%09%09%09%7B%0A%09%09%09%09%09%09%09%09hash: this.compilation.hash %7C%7C %22XXXX%22%0A%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09)%0A%09%09%09%09%09)%7D
+throw new Error(%22Webpack: Auto public path is not supported in modules or when 'document.currentScript' is unavailable. Set 'publicPath' config explicitly.%22)
 ;%0A%09%09

throw error in fallback case to inform users.