import-html-entry
Advanced tools
Comparing version 1.14.3 to 1.14.4
139
esm/index.js
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } | ||
/** | ||
@@ -12,2 +9,3 @@ * @author Kuitos | ||
*/ | ||
import processTpl, { genLinkReplaceSymbol, genScriptReplaceSymbol } from './process-tpl'; | ||
@@ -18,12 +16,10 @@ import { defaultGetPublicPath, evalCode, getGlobalProp, getInlineCode, noteGlobalProps, readResAsString, requestIdleCallback } from './utils'; | ||
var embedHTMLCache = {}; | ||
if (!window.fetch) { | ||
throw new Error('[import-html-entry] Here is no "fetch" on the window env, you need to polyfill it'); | ||
} | ||
var defaultFetch = window.fetch.bind(window); | ||
function defaultGetTemplate(tpl) { | ||
return tpl; | ||
} | ||
/** | ||
@@ -36,8 +32,6 @@ * convert external css link to inline style for performance optimization | ||
*/ | ||
function getEmbedHTML(template, styles) { | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var _opts$fetch = opts.fetch, | ||
fetch = _opts$fetch === void 0 ? defaultFetch : _opts$fetch; | ||
fetch = _opts$fetch === void 0 ? defaultFetch : _opts$fetch; | ||
var embedHTML = template; | ||
@@ -52,25 +46,25 @@ return _getExternalStyleSheets(styles, fetch).then(function (styleSheets) { | ||
} | ||
var isInlineCode = function isInlineCode(code) { | ||
return code.startsWith('<'); | ||
}; | ||
function getExecutableScript(scriptSrc, scriptText) { | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var proxy = opts.proxy, | ||
strictGlobal = opts.strictGlobal, | ||
_opts$scopedGlobalVar = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar === void 0 ? [] : _opts$scopedGlobalVar; | ||
var sourceUrl = isInlineCode(scriptSrc) ? '' : "//# sourceURL=".concat(scriptSrc, "\n"); // 将 scopedGlobalVariables 拼接成函数声明,用于缓存全局变量,避免每次使用时都走一遍代理 | ||
strictGlobal = opts.strictGlobal, | ||
_opts$scopedGlobalVar = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar === void 0 ? [] : _opts$scopedGlobalVar; | ||
var sourceUrl = isInlineCode(scriptSrc) ? '' : "//# sourceURL=".concat(scriptSrc, "\n"); | ||
var scopedGlobalVariableFnParameters = scopedGlobalVariables.length ? scopedGlobalVariables.join(',') : ''; // 通过这种方式获取全局 window,因为 script 也是在全局作用域下运行的,所以我们通过 window.proxy 绑定时也必须确保绑定到全局 window 上 | ||
// 将 scopedGlobalVariables 拼接成函数声明,用于缓存全局变量,避免每次使用时都走一遍代理 | ||
var scopedGlobalVariableFnParameters = scopedGlobalVariables.length ? scopedGlobalVariables.join(',') : ''; | ||
// 通过这种方式获取全局 window,因为 script 也是在全局作用域下运行的,所以我们通过 window.proxy 绑定时也必须确保绑定到全局 window 上 | ||
// 否则在嵌套场景下, window.proxy 设置的是内层应用的 window,而代码其实是在全局作用域运行的,会导致闭包里的 window.proxy 取的是最外层的微应用的 proxy | ||
var globalWindow = (0, eval)('window'); | ||
globalWindow.proxy = proxy; // TODO 通过 strictGlobal 方式切换 with 闭包,待 with 方式坑趟平后再合并 | ||
globalWindow.proxy = proxy; | ||
// TODO 通过 strictGlobal 方式切换 with 闭包,待 with 方式坑趟平后再合并 | ||
return strictGlobal ? scopedGlobalVariableFnParameters ? ";with(window.proxy){(function(".concat(scopedGlobalVariableFnParameters, "){;").concat(scriptText, "\n").concat(sourceUrl, "}).bind(window)(").concat(scopedGlobalVariableFnParameters, ")};") : ";(function(window, self, globalThis){with(window){;".concat(scriptText, "\n").concat(sourceUrl, "}}).bind(window.proxy)(window.proxy, window.proxy, window.proxy);") : ";(function(window, self, globalThis){;".concat(scriptText, "\n").concat(sourceUrl, "}).bind(window.proxy)(window.proxy, window.proxy, window.proxy);"); | ||
} // for prefetch | ||
} | ||
// for prefetch | ||
function _getExternalStyleSheets(styles) { | ||
@@ -89,11 +83,9 @@ var fetch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultFetch; | ||
})); | ||
} // for prefetch | ||
} | ||
// for prefetch | ||
export { _getExternalStyleSheets as getExternalStyleSheets }; | ||
function _getExternalScripts(scripts) { | ||
var fetch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultFetch; | ||
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; | ||
var fetchScript = function fetchScript(scriptUrl) { | ||
@@ -104,6 +96,4 @@ return scriptCache[scriptUrl] || (scriptCache[scriptUrl] = fetch(scriptUrl).then(function (response) { | ||
if (response.status >= 400) { | ||
errorCallback(); | ||
throw new Error("".concat(scriptUrl, " load failed with status ").concat(response.status)); | ||
} | ||
return response.text(); | ||
@@ -115,3 +105,2 @@ })["catch"](function (e) { | ||
}; | ||
return Promise.all(scripts.map(function (script) { | ||
@@ -129,4 +118,3 @@ if (typeof script === 'string') { | ||
var src = script.src, | ||
async = script.async; | ||
async = script.async; | ||
if (async) { | ||
@@ -143,3 +131,2 @@ return { | ||
} | ||
return fetchScript(src); | ||
@@ -149,5 +136,3 @@ } | ||
} | ||
export { _getExternalScripts as getExternalScripts }; | ||
function throwNonBlockingError(error, msg) { | ||
@@ -159,4 +144,4 @@ setTimeout(function () { | ||
} | ||
var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; | ||
var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; | ||
/** | ||
@@ -170,3 +155,2 @@ * FIXME to consistent with browser behavior, we should only provide callback way to invoke success and error event | ||
*/ | ||
function _execScripts(entry, scripts) { | ||
@@ -176,14 +160,14 @@ var proxy = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window; | ||
var _opts$fetch2 = opts.fetch, | ||
fetch = _opts$fetch2 === void 0 ? defaultFetch : _opts$fetch2, | ||
_opts$strictGlobal = opts.strictGlobal, | ||
strictGlobal = _opts$strictGlobal === void 0 ? false : _opts$strictGlobal, | ||
success = opts.success, | ||
_opts$error = opts.error, | ||
error = _opts$error === void 0 ? function () {} : _opts$error, | ||
_opts$beforeExec = opts.beforeExec, | ||
beforeExec = _opts$beforeExec === void 0 ? function () {} : _opts$beforeExec, | ||
_opts$afterExec = opts.afterExec, | ||
afterExec = _opts$afterExec === void 0 ? function () {} : _opts$afterExec, | ||
_opts$scopedGlobalVar2 = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar2 === void 0 ? [] : _opts$scopedGlobalVar2; | ||
fetch = _opts$fetch2 === void 0 ? defaultFetch : _opts$fetch2, | ||
_opts$strictGlobal = opts.strictGlobal, | ||
strictGlobal = _opts$strictGlobal === void 0 ? false : _opts$strictGlobal, | ||
success = opts.success, | ||
_opts$error = opts.error, | ||
error = _opts$error === void 0 ? function () {} : _opts$error, | ||
_opts$beforeExec = opts.beforeExec, | ||
beforeExec = _opts$beforeExec === void 0 ? function () {} : _opts$beforeExec, | ||
_opts$afterExec = opts.afterExec, | ||
afterExec = _opts$afterExec === void 0 ? function () {} : _opts$afterExec, | ||
_opts$scopedGlobalVar2 = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar2 === void 0 ? [] : _opts$scopedGlobalVar2; | ||
return _getExternalScripts(scripts, fetch, error).then(function (scriptsText) { | ||
@@ -200,14 +184,10 @@ var geval = function geval(scriptSrc, inlineScript) { | ||
}; | ||
function exec(scriptSrc, inlineScript, resolve) { | ||
var markName = "Evaluating script ".concat(scriptSrc); | ||
var measureName = "Evaluating Time Consuming: ".concat(scriptSrc); | ||
if (process.env.NODE_ENV === 'development' && supportsUserTiming) { | ||
performance.mark(markName); | ||
} | ||
if (scriptSrc === entry) { | ||
noteGlobalProps(strictGlobal ? proxy : window); | ||
try { | ||
@@ -241,3 +221,2 @@ // bind window.proxy to change `this` reference in script | ||
} | ||
if (process.env.NODE_ENV === 'development' && supportsUserTiming) { | ||
@@ -249,3 +228,2 @@ performance.measure(measureName, markName); | ||
} | ||
function schedule(i, resolvePromise) { | ||
@@ -255,4 +233,4 @@ if (i < scripts.length) { | ||
var inlineScript = scriptsText[i]; | ||
exec(scriptSrc, inlineScript, resolvePromise); // resolve the promise while the last script executed and entry not provided | ||
exec(scriptSrc, inlineScript, resolvePromise); | ||
// resolve the promise while the last script executed and entry not provided | ||
if (!entry && i === scripts.length - 1) { | ||
@@ -265,3 +243,2 @@ resolvePromise(); | ||
} | ||
return new Promise(function (resolve) { | ||
@@ -272,3 +249,2 @@ return schedule(0, success || resolve); | ||
} | ||
export { _execScripts as execScripts }; | ||
@@ -281,4 +257,5 @@ export default function importHTML(url) { | ||
var getTemplate = defaultGetTemplate; | ||
var postProcessTemplate = opts.postProcessTemplate; // compatible with the legacy importHTML api | ||
var postProcessTemplate = opts.postProcessTemplate; | ||
// compatible with the legacy importHTML api | ||
if (typeof opts === 'function') { | ||
@@ -298,7 +275,5 @@ fetch = opts; | ||
} | ||
getPublicPath = opts.getPublicPath || opts.getDomain || defaultGetPublicPath; | ||
getTemplate = opts.getTemplate || defaultGetTemplate; | ||
} | ||
return embedHTMLCache[url] || (embedHTMLCache[url] = fetch(url).then(function (response) { | ||
@@ -308,9 +283,7 @@ return readResAsString(response, autoDecodeResponse); | ||
var assetPublicPath = getPublicPath(url); | ||
var _processTpl = processTpl(getTemplate(html), assetPublicPath, postProcessTemplate), | ||
template = _processTpl.template, | ||
scripts = _processTpl.scripts, | ||
entry = _processTpl.entry, | ||
styles = _processTpl.styles; | ||
template = _processTpl.template, | ||
scripts = _processTpl.scripts, | ||
entry = _processTpl.entry, | ||
styles = _processTpl.styles; | ||
return getEmbedHTML(template, styles, { | ||
@@ -330,7 +303,5 @@ fetch: fetch | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
if (!scripts.length) { | ||
return Promise.resolve(); | ||
} | ||
return _execScripts(entry, scripts, proxy, _objectSpread({ | ||
@@ -348,13 +319,12 @@ fetch: fetch, | ||
var _opts$fetch3 = opts.fetch, | ||
fetch = _opts$fetch3 === void 0 ? defaultFetch : _opts$fetch3, | ||
_opts$getTemplate = opts.getTemplate, | ||
getTemplate = _opts$getTemplate === void 0 ? defaultGetTemplate : _opts$getTemplate, | ||
postProcessTemplate = opts.postProcessTemplate; | ||
fetch = _opts$fetch3 === void 0 ? defaultFetch : _opts$fetch3, | ||
_opts$getTemplate = opts.getTemplate, | ||
getTemplate = _opts$getTemplate === void 0 ? defaultGetTemplate : _opts$getTemplate, | ||
postProcessTemplate = opts.postProcessTemplate; | ||
var getPublicPath = opts.getPublicPath || opts.getDomain || defaultGetPublicPath; | ||
if (!entry) { | ||
throw new SyntaxError('entry should not be empty!'); | ||
} // html entry | ||
} | ||
// html entry | ||
if (typeof entry === 'string') { | ||
@@ -367,13 +337,12 @@ return importHTML(entry, { | ||
}); | ||
} // config entry | ||
} | ||
// config entry | ||
if (Array.isArray(entry.scripts) || Array.isArray(entry.styles)) { | ||
var _entry$scripts = entry.scripts, | ||
scripts = _entry$scripts === void 0 ? [] : _entry$scripts, | ||
_entry$styles = entry.styles, | ||
styles = _entry$styles === void 0 ? [] : _entry$styles, | ||
_entry$html = entry.html, | ||
html = _entry$html === void 0 ? '' : _entry$html; | ||
scripts = _entry$scripts === void 0 ? [] : _entry$scripts, | ||
_entry$styles = entry.styles, | ||
styles = _entry$styles === void 0 ? [] : _entry$styles, | ||
_entry$html = entry.html, | ||
html = _entry$html === void 0 ? '' : _entry$html; | ||
var getHTMLWithStylePlaceholder = function getHTMLWithStylePlaceholder(tpl) { | ||
@@ -384,3 +353,2 @@ return styles.reduceRight(function (html, styleSrc) { | ||
}; | ||
var getHTMLWithScriptPlaceholder = function getHTMLWithScriptPlaceholder(tpl) { | ||
@@ -391,3 +359,2 @@ return scripts.reduce(function (html, scriptSrc) { | ||
}; | ||
return getEmbedHTML(getTemplate(getHTMLWithScriptPlaceholder(getHTMLWithStylePlaceholder(html))), styles, { | ||
@@ -407,7 +374,5 @@ fetch: fetch | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
if (!scripts.length) { | ||
return Promise.resolve(); | ||
} | ||
return _execScripts(scripts[scripts.length - 1], scripts, proxy, _objectSpread({ | ||
@@ -414,0 +379,0 @@ fetch: fetch, |
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; | ||
/** | ||
@@ -8,3 +7,3 @@ * @author Kuitos | ||
*/ | ||
import { getInlineCode, isModuleScriptSupported } from './utils'; | ||
import { getInlineCode, isModuleScriptSupported, parseUrl } from './utils'; | ||
var ALL_SCRIPT_REGEX = /(<script[\s\S]*?>)[\s\S]*?<\/script>/gi; | ||
@@ -29,11 +28,8 @@ var SCRIPT_TAG_REGEX = /<(script)\s+((?!type=('|")text\/ng\x2Dtemplate\3)[\s\S])*?>[\s\S]*?<\/\1>/i; | ||
var SCRIPT_IGNORE_REGEX = /<script(\s+|\s+[\s\S]+\s+)ignore(\s*|\s+[\s\S]*|=[\s\S]*)>/i; | ||
function hasProtocol(url) { | ||
return url.startsWith('//') || url.startsWith('http://') || url.startsWith('https://'); | ||
} | ||
function getEntirePath(path, baseURI) { | ||
return new URL(path, baseURI).toString(); | ||
} | ||
function isValidJavaScriptType(type) { | ||
@@ -43,3 +39,2 @@ var handleTypes = ['text/javascript', 'module', 'application/javascript', 'text/ecmascript', 'application/ecmascript']; | ||
} | ||
export var genLinkReplaceSymbol = function genLinkReplaceSymbol(linkHref) { | ||
@@ -60,2 +55,3 @@ var preloadOrPrefetch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; | ||
}; | ||
/** | ||
@@ -73,3 +69,2 @@ * parse the script link from the template | ||
*/ | ||
export default function processTpl(tpl, baseURI, postProcessTemplate) { | ||
@@ -81,6 +76,6 @@ var scripts = []; | ||
var template = tpl | ||
/* | ||
remove html comment first | ||
*/ | ||
.replace(HTML_COMMENT_REGEX, '').replace(LINK_TAG_REGEX, function (match) { | ||
*/.replace(HTML_COMMENT_REGEX, '').replace(LINK_TAG_REGEX, function (match) { | ||
/* | ||
@@ -90,19 +85,15 @@ change the css link | ||
var styleType = !!match.match(STYLE_TYPE_REGEX); | ||
if (styleType) { | ||
var styleHref = match.match(STYLE_HREF_REGEX); | ||
var styleIgnore = match.match(LINK_IGNORE_REGEX); | ||
if (styleHref) { | ||
var href = styleHref && styleHref[2]; | ||
var newHref = href; | ||
if (href && !hasProtocol(href)) { | ||
newHref = getEntirePath(href, baseURI); | ||
} | ||
if (styleIgnore) { | ||
return genIgnoreAssetReplaceSymbol(newHref); | ||
} | ||
newHref = parseUrl(newHref); | ||
styles.push(newHref); | ||
@@ -112,13 +103,9 @@ return genLinkReplaceSymbol(newHref); | ||
} | ||
var preloadOrPrefetchType = match.match(LINK_PRELOAD_OR_PREFETCH_REGEX) && match.match(LINK_HREF_REGEX) && !match.match(LINK_AS_FONT); | ||
if (preloadOrPrefetchType) { | ||
var _match$match = match.match(LINK_HREF_REGEX), | ||
_match$match2 = _slicedToArray(_match$match, 3), | ||
linkHref = _match$match2[2]; | ||
_match$match2 = _slicedToArray(_match$match, 3), | ||
linkHref = _match$match2[2]; | ||
return genLinkReplaceSymbol(linkHref, true); | ||
} | ||
return match; | ||
@@ -129,16 +116,15 @@ }).replace(STYLE_TAG_REGEX, function (match) { | ||
} | ||
return match; | ||
}).replace(ALL_SCRIPT_REGEX, function (match, scriptTag) { | ||
var scriptIgnore = scriptTag.match(SCRIPT_IGNORE_REGEX); | ||
var moduleScriptIgnore = moduleSupport && !!scriptTag.match(SCRIPT_NO_MODULE_REGEX) || !moduleSupport && !!scriptTag.match(SCRIPT_MODULE_REGEX); // in order to keep the exec order of all javascripts | ||
var moduleScriptIgnore = moduleSupport && !!scriptTag.match(SCRIPT_NO_MODULE_REGEX) || !moduleSupport && !!scriptTag.match(SCRIPT_MODULE_REGEX); | ||
// in order to keep the exec order of all javascripts | ||
var matchedScriptTypeMatch = scriptTag.match(SCRIPT_TYPE_REGEX); | ||
var matchedScriptType = matchedScriptTypeMatch && matchedScriptTypeMatch[2]; | ||
if (!isValidJavaScriptType(matchedScriptType)) { | ||
return match; | ||
} // if it is a external script | ||
} | ||
// if it is a external script | ||
if (SCRIPT_TAG_REGEX.test(match) && scriptTag.match(SCRIPT_SRC_REGEX)) { | ||
@@ -148,6 +134,6 @@ /* | ||
*/ | ||
var matchedScriptEntry = scriptTag.match(SCRIPT_ENTRY_REGEX); | ||
var matchedScriptSrcMatch = scriptTag.match(SCRIPT_SRC_REGEX); | ||
var matchedScriptSrc = matchedScriptSrcMatch && matchedScriptSrcMatch[2]; | ||
if (entry && matchedScriptEntry) { | ||
@@ -160,16 +146,13 @@ throw new SyntaxError('You should not set multiply entry script!'); | ||
} | ||
entry = entry || matchedScriptEntry && matchedScriptSrc; | ||
} | ||
if (scriptIgnore) { | ||
return genIgnoreAssetReplaceSymbol(matchedScriptSrc || 'js file'); | ||
} | ||
if (moduleScriptIgnore) { | ||
return genModuleScriptReplaceSymbol(matchedScriptSrc || 'js file', moduleSupport); | ||
} | ||
if (matchedScriptSrc) { | ||
var asyncScript = !!scriptTag.match(SCRIPT_ASYNC_REGEX); | ||
matchedScriptSrc = parseUrl(matchedScriptSrc); | ||
scripts.push(asyncScript ? { | ||
@@ -181,3 +164,2 @@ async: true, | ||
} | ||
return match; | ||
@@ -188,18 +170,16 @@ } else { | ||
} | ||
if (moduleScriptIgnore) { | ||
return genModuleScriptReplaceSymbol('js file', moduleSupport); | ||
} // if it is an inline script | ||
} | ||
// if it is an inline script | ||
var code = getInlineCode(match); | ||
var code = getInlineCode(match); // remove script blocks when all of these lines are comments. | ||
// remove script blocks when all of these lines are comments. | ||
var isPureCommentBlock = code.split(/[\r\n]+/).every(function (line) { | ||
return !line.trim() || line.trim().startsWith('//'); | ||
}); | ||
if (!isPureCommentBlock) { | ||
scripts.push(match); | ||
} | ||
return inlineScriptReplaceSymbol; | ||
@@ -219,8 +199,6 @@ } | ||
}; | ||
if (typeof postProcessTemplate === 'function') { | ||
tplResult = postProcessTemplate(tplResult); | ||
} | ||
return tplResult; | ||
} |
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; | ||
import _typeof from "@babel/runtime/helpers/esm/typeof"; | ||
/** | ||
@@ -10,7 +9,6 @@ * @author Kuitos | ||
*/ | ||
var isIE11 = typeof navigator !== 'undefined' && navigator.userAgent.indexOf('Trident') !== -1; | ||
function shouldSkipProperty(global, p) { | ||
if (!global.hasOwnProperty(p) || !isNaN(p) && p < global.length) return true; | ||
if (isIE11) { | ||
@@ -26,5 +24,5 @@ // https://github.com/kuitos/import-html-entry/pull/32,最小化 try 范围 | ||
} | ||
} // safari unpredictably lists some new globals first or second in object order | ||
} | ||
// safari unpredictably lists some new globals first or second in object order | ||
var firstGlobalProp, secondGlobalProp, lastGlobalProp; | ||
@@ -35,9 +33,8 @@ export function getGlobalProp(global) { | ||
var hasIframe = false; | ||
for (var p in global) { | ||
if (shouldSkipProperty(global, p)) continue; // 遍历 iframe,检查 window 上的属性值是否是 iframe,是则跳过后面的 first 和 second 判断 | ||
if (shouldSkipProperty(global, p)) continue; | ||
// 遍历 iframe,检查 window 上的属性值是否是 iframe,是则跳过后面的 first 和 second 判断 | ||
for (var i = 0; i < window.frames.length && !hasIframe; i++) { | ||
var frame = window.frames[i]; | ||
if (frame === global[p]) { | ||
@@ -48,3 +45,2 @@ hasIframe = true; | ||
} | ||
if (!hasIframe && (cnt === 0 && p !== firstGlobalProp || cnt === 1 && p !== secondGlobalProp)) return p; | ||
@@ -54,3 +50,2 @@ cnt++; | ||
} | ||
if (lastProp !== lastGlobalProp) return lastProp; | ||
@@ -62,3 +57,2 @@ } | ||
firstGlobalProp = secondGlobalProp = undefined; | ||
for (var p in global) { | ||
@@ -69,3 +63,2 @@ if (shouldSkipProperty(global, p)) continue; | ||
} | ||
return lastGlobalProp; | ||
@@ -82,10 +75,8 @@ } | ||
} | ||
try { | ||
var _URL = new URL(entry, location.href), | ||
origin = _URL.origin, | ||
pathname = _URL.pathname; | ||
var paths = pathname.split('/'); // 移除最后一个元素 | ||
origin = _URL.origin, | ||
pathname = _URL.pathname; | ||
var paths = pathname.split('/'); | ||
// 移除最后一个元素 | ||
paths.pop(); | ||
@@ -97,9 +88,11 @@ return "".concat(origin).concat(paths.join('/'), "/"); | ||
} | ||
} // Detect whether browser supports `<script type=module>` or not | ||
} | ||
// Detect whether browser supports `<script type=module>` or not | ||
export function isModuleScriptSupported() { | ||
var s = document.createElement('script'); | ||
return 'noModule' in s; | ||
} // RIC and shim for browsers setTimeout() without it | ||
} | ||
// RIC and shim for browsers setTimeout() without it | ||
export var requestIdleCallback = window.requestIdleCallback || function requestIdleCallback(cb) { | ||
@@ -120,49 +113,43 @@ var start = Date.now(); | ||
return response.text(); | ||
} // 如果没headers,发生在test环境下的mock数据,为兼容原有测试用例 | ||
} | ||
// 如果没headers,发生在test环境下的mock数据,为兼容原有测试用例 | ||
if (!response.headers) { | ||
return response.text(); | ||
} // 如果没返回content-type,走默认逻辑 | ||
} | ||
// 如果没返回content-type,走默认逻辑 | ||
var contentType = response.headers.get('Content-Type'); | ||
if (!contentType) { | ||
return response.text(); | ||
} // 解析content-type内的charset | ||
} | ||
// 解析content-type内的charset | ||
// Content-Type: text/html; charset=utf-8 | ||
// Content-Type: multipart/form-data; boundary=something | ||
// GET请求下不会出现第二种content-type | ||
var charset = 'utf-8'; | ||
var parts = contentType.split(';'); | ||
if (parts.length === 2) { | ||
var _parts$1$split = parts[1].split('='), | ||
_parts$1$split2 = _slicedToArray(_parts$1$split, 2), | ||
value = _parts$1$split2[1]; | ||
_parts$1$split2 = _slicedToArray(_parts$1$split, 2), | ||
value = _parts$1$split2[1]; | ||
var encoding = value && value.trim(); | ||
if (encoding) { | ||
charset = encoding; | ||
} | ||
} // 如果还是utf-8,那么走默认,兼容原有逻辑,这段代码删除也应该工作 | ||
} | ||
// 如果还是utf-8,那么走默认,兼容原有逻辑,这段代码删除也应该工作 | ||
if (charset.toUpperCase() === 'UTF-8') { | ||
return response.text(); | ||
} // 走流读取,编码可能是gbk,gb2312等,比如sofa 3默认是gbk编码 | ||
} | ||
// 走流读取,编码可能是gbk,gb2312等,比如sofa 3默认是gbk编码 | ||
return response.blob().then(function (file) { | ||
return new Promise(function (resolve, reject) { | ||
var reader = new window.FileReader(); | ||
reader.onload = function () { | ||
resolve(reader.result); | ||
}; | ||
reader.onerror = reject; | ||
@@ -176,3 +163,2 @@ reader.readAsText(file, charset); | ||
var key = scriptSrc; | ||
if (!evalCache[key]) { | ||
@@ -182,5 +168,12 @@ var functionWrappedCode = "(function(){".concat(code, "})"); | ||
} | ||
var evalFunc = evalCache[key]; | ||
evalFunc.call(window); | ||
} | ||
// 转换 url 中的转义字符,例如 & => & | ||
export function parseUrl(url) { | ||
var parser = new DOMParser(); | ||
var html = "<script src=\"".concat(url, "\"></script>"); | ||
var doc = parser.parseFromString(html, "text/html"); | ||
return doc.scripts[0].src; | ||
} |
144
lib/index.js
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
var _typeof = require("@babel/runtime/helpers/typeof"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -15,30 +13,20 @@ value: true | ||
exports.importEntry = importEntry; | ||
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); | ||
var _processTpl2 = _interopRequireWildcard(require("./process-tpl")); | ||
var _utils = require("./utils"); | ||
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } | ||
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } | ||
var styleCache = {}; | ||
var scriptCache = {}; | ||
var embedHTMLCache = {}; | ||
if (!window.fetch) { | ||
throw new Error('[import-html-entry] Here is no "fetch" on the window env, you need to polyfill it'); | ||
} | ||
var defaultFetch = window.fetch.bind(window); | ||
function defaultGetTemplate(tpl) { | ||
return tpl; | ||
} | ||
/** | ||
@@ -51,8 +39,6 @@ * convert external css link to inline style for performance optimization | ||
*/ | ||
function getEmbedHTML(template, styles) { | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var _opts$fetch = opts.fetch, | ||
fetch = _opts$fetch === void 0 ? defaultFetch : _opts$fetch; | ||
fetch = _opts$fetch === void 0 ? defaultFetch : _opts$fetch; | ||
var embedHTML = template; | ||
@@ -67,25 +53,25 @@ return _getExternalStyleSheets(styles, fetch).then(function (styleSheets) { | ||
} | ||
var isInlineCode = function isInlineCode(code) { | ||
return code.startsWith('<'); | ||
}; | ||
function getExecutableScript(scriptSrc, scriptText) { | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var proxy = opts.proxy, | ||
strictGlobal = opts.strictGlobal, | ||
_opts$scopedGlobalVar = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar === void 0 ? [] : _opts$scopedGlobalVar; | ||
var sourceUrl = isInlineCode(scriptSrc) ? '' : "//# sourceURL=".concat(scriptSrc, "\n"); // 将 scopedGlobalVariables 拼接成函数声明,用于缓存全局变量,避免每次使用时都走一遍代理 | ||
strictGlobal = opts.strictGlobal, | ||
_opts$scopedGlobalVar = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar === void 0 ? [] : _opts$scopedGlobalVar; | ||
var sourceUrl = isInlineCode(scriptSrc) ? '' : "//# sourceURL=".concat(scriptSrc, "\n"); | ||
var scopedGlobalVariableFnParameters = scopedGlobalVariables.length ? scopedGlobalVariables.join(',') : ''; // 通过这种方式获取全局 window,因为 script 也是在全局作用域下运行的,所以我们通过 window.proxy 绑定时也必须确保绑定到全局 window 上 | ||
// 将 scopedGlobalVariables 拼接成函数声明,用于缓存全局变量,避免每次使用时都走一遍代理 | ||
var scopedGlobalVariableFnParameters = scopedGlobalVariables.length ? scopedGlobalVariables.join(',') : ''; | ||
// 通过这种方式获取全局 window,因为 script 也是在全局作用域下运行的,所以我们通过 window.proxy 绑定时也必须确保绑定到全局 window 上 | ||
// 否则在嵌套场景下, window.proxy 设置的是内层应用的 window,而代码其实是在全局作用域运行的,会导致闭包里的 window.proxy 取的是最外层的微应用的 proxy | ||
var globalWindow = (0, eval)('window'); | ||
globalWindow.proxy = proxy; // TODO 通过 strictGlobal 方式切换 with 闭包,待 with 方式坑趟平后再合并 | ||
globalWindow.proxy = proxy; | ||
// TODO 通过 strictGlobal 方式切换 with 闭包,待 with 方式坑趟平后再合并 | ||
return strictGlobal ? scopedGlobalVariableFnParameters ? ";with(window.proxy){(function(".concat(scopedGlobalVariableFnParameters, "){;").concat(scriptText, "\n").concat(sourceUrl, "}).bind(window)(").concat(scopedGlobalVariableFnParameters, ")};") : ";(function(window, self, globalThis){with(window){;".concat(scriptText, "\n").concat(sourceUrl, "}}).bind(window.proxy)(window.proxy, window.proxy, window.proxy);") : ";(function(window, self, globalThis){;".concat(scriptText, "\n").concat(sourceUrl, "}).bind(window.proxy)(window.proxy, window.proxy, window.proxy);"); | ||
} // for prefetch | ||
} | ||
// for prefetch | ||
function _getExternalStyleSheets(styles) { | ||
@@ -104,9 +90,8 @@ var fetch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultFetch; | ||
})); | ||
} // for prefetch | ||
} | ||
// for prefetch | ||
function _getExternalScripts(scripts) { | ||
var fetch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultFetch; | ||
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; | ||
var fetchScript = function fetchScript(scriptUrl) { | ||
@@ -117,6 +102,4 @@ return scriptCache[scriptUrl] || (scriptCache[scriptUrl] = fetch(scriptUrl).then(function (response) { | ||
if (response.status >= 400) { | ||
errorCallback(); | ||
throw new Error("".concat(scriptUrl, " load failed with status ").concat(response.status)); | ||
} | ||
return response.text(); | ||
@@ -128,3 +111,2 @@ })["catch"](function (e) { | ||
}; | ||
return Promise.all(scripts.map(function (script) { | ||
@@ -142,4 +124,3 @@ if (typeof script === 'string') { | ||
var src = script.src, | ||
async = script.async; | ||
async = script.async; | ||
if (async) { | ||
@@ -156,3 +137,2 @@ return { | ||
} | ||
return fetchScript(src); | ||
@@ -162,3 +142,2 @@ } | ||
} | ||
function throwNonBlockingError(error, msg) { | ||
@@ -170,4 +149,4 @@ setTimeout(function () { | ||
} | ||
var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; | ||
var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; | ||
/** | ||
@@ -181,3 +160,2 @@ * FIXME to consistent with browser behavior, we should only provide callback way to invoke success and error event | ||
*/ | ||
function _execScripts(entry, scripts) { | ||
@@ -187,14 +165,14 @@ var proxy = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window; | ||
var _opts$fetch2 = opts.fetch, | ||
fetch = _opts$fetch2 === void 0 ? defaultFetch : _opts$fetch2, | ||
_opts$strictGlobal = opts.strictGlobal, | ||
strictGlobal = _opts$strictGlobal === void 0 ? false : _opts$strictGlobal, | ||
success = opts.success, | ||
_opts$error = opts.error, | ||
error = _opts$error === void 0 ? function () {} : _opts$error, | ||
_opts$beforeExec = opts.beforeExec, | ||
beforeExec = _opts$beforeExec === void 0 ? function () {} : _opts$beforeExec, | ||
_opts$afterExec = opts.afterExec, | ||
afterExec = _opts$afterExec === void 0 ? function () {} : _opts$afterExec, | ||
_opts$scopedGlobalVar2 = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar2 === void 0 ? [] : _opts$scopedGlobalVar2; | ||
fetch = _opts$fetch2 === void 0 ? defaultFetch : _opts$fetch2, | ||
_opts$strictGlobal = opts.strictGlobal, | ||
strictGlobal = _opts$strictGlobal === void 0 ? false : _opts$strictGlobal, | ||
success = opts.success, | ||
_opts$error = opts.error, | ||
error = _opts$error === void 0 ? function () {} : _opts$error, | ||
_opts$beforeExec = opts.beforeExec, | ||
beforeExec = _opts$beforeExec === void 0 ? function () {} : _opts$beforeExec, | ||
_opts$afterExec = opts.afterExec, | ||
afterExec = _opts$afterExec === void 0 ? function () {} : _opts$afterExec, | ||
_opts$scopedGlobalVar2 = opts.scopedGlobalVariables, | ||
scopedGlobalVariables = _opts$scopedGlobalVar2 === void 0 ? [] : _opts$scopedGlobalVar2; | ||
return _getExternalScripts(scripts, fetch, error).then(function (scriptsText) { | ||
@@ -211,14 +189,10 @@ var geval = function geval(scriptSrc, inlineScript) { | ||
}; | ||
function exec(scriptSrc, inlineScript, resolve) { | ||
var markName = "Evaluating script ".concat(scriptSrc); | ||
var measureName = "Evaluating Time Consuming: ".concat(scriptSrc); | ||
if (process.env.NODE_ENV === 'development' && supportsUserTiming) { | ||
performance.mark(markName); | ||
} | ||
if (scriptSrc === entry) { | ||
(0, _utils.noteGlobalProps)(strictGlobal ? proxy : window); | ||
try { | ||
@@ -252,3 +226,2 @@ // bind window.proxy to change `this` reference in script | ||
} | ||
if (process.env.NODE_ENV === 'development' && supportsUserTiming) { | ||
@@ -260,3 +233,2 @@ performance.measure(measureName, markName); | ||
} | ||
function schedule(i, resolvePromise) { | ||
@@ -266,4 +238,4 @@ if (i < scripts.length) { | ||
var inlineScript = scriptsText[i]; | ||
exec(scriptSrc, inlineScript, resolvePromise); // resolve the promise while the last script executed and entry not provided | ||
exec(scriptSrc, inlineScript, resolvePromise); | ||
// resolve the promise while the last script executed and entry not provided | ||
if (!entry && i === scripts.length - 1) { | ||
@@ -276,3 +248,2 @@ resolvePromise(); | ||
} | ||
return new Promise(function (resolve) { | ||
@@ -283,3 +254,2 @@ return schedule(0, success || resolve); | ||
} | ||
function importHTML(url) { | ||
@@ -291,4 +261,5 @@ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var getTemplate = defaultGetTemplate; | ||
var postProcessTemplate = opts.postProcessTemplate; // compatible with the legacy importHTML api | ||
var postProcessTemplate = opts.postProcessTemplate; | ||
// compatible with the legacy importHTML api | ||
if (typeof opts === 'function') { | ||
@@ -308,7 +279,5 @@ fetch = opts; | ||
} | ||
getPublicPath = opts.getPublicPath || opts.getDomain || _utils.defaultGetPublicPath; | ||
getTemplate = opts.getTemplate || defaultGetTemplate; | ||
} | ||
return embedHTMLCache[url] || (embedHTMLCache[url] = fetch(url).then(function (response) { | ||
@@ -318,9 +287,7 @@ return (0, _utils.readResAsString)(response, autoDecodeResponse); | ||
var assetPublicPath = getPublicPath(url); | ||
var _processTpl = (0, _processTpl2["default"])(getTemplate(html), assetPublicPath, postProcessTemplate), | ||
template = _processTpl.template, | ||
scripts = _processTpl.scripts, | ||
entry = _processTpl.entry, | ||
styles = _processTpl.styles; | ||
template = _processTpl.template, | ||
scripts = _processTpl.scripts, | ||
entry = _processTpl.entry, | ||
styles = _processTpl.styles; | ||
return getEmbedHTML(template, styles, { | ||
@@ -340,7 +307,5 @@ fetch: fetch | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
if (!scripts.length) { | ||
return Promise.resolve(); | ||
} | ||
return _execScripts(entry, scripts, proxy, _objectSpread({ | ||
@@ -355,17 +320,15 @@ fetch: fetch, | ||
} | ||
function importEntry(entry) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var _opts$fetch3 = opts.fetch, | ||
fetch = _opts$fetch3 === void 0 ? defaultFetch : _opts$fetch3, | ||
_opts$getTemplate = opts.getTemplate, | ||
getTemplate = _opts$getTemplate === void 0 ? defaultGetTemplate : _opts$getTemplate, | ||
postProcessTemplate = opts.postProcessTemplate; | ||
fetch = _opts$fetch3 === void 0 ? defaultFetch : _opts$fetch3, | ||
_opts$getTemplate = opts.getTemplate, | ||
getTemplate = _opts$getTemplate === void 0 ? defaultGetTemplate : _opts$getTemplate, | ||
postProcessTemplate = opts.postProcessTemplate; | ||
var getPublicPath = opts.getPublicPath || opts.getDomain || _utils.defaultGetPublicPath; | ||
if (!entry) { | ||
throw new SyntaxError('entry should not be empty!'); | ||
} // html entry | ||
} | ||
// html entry | ||
if (typeof entry === 'string') { | ||
@@ -378,13 +341,12 @@ return importHTML(entry, { | ||
}); | ||
} // config entry | ||
} | ||
// config entry | ||
if (Array.isArray(entry.scripts) || Array.isArray(entry.styles)) { | ||
var _entry$scripts = entry.scripts, | ||
scripts = _entry$scripts === void 0 ? [] : _entry$scripts, | ||
_entry$styles = entry.styles, | ||
styles = _entry$styles === void 0 ? [] : _entry$styles, | ||
_entry$html = entry.html, | ||
html = _entry$html === void 0 ? '' : _entry$html; | ||
scripts = _entry$scripts === void 0 ? [] : _entry$scripts, | ||
_entry$styles = entry.styles, | ||
styles = _entry$styles === void 0 ? [] : _entry$styles, | ||
_entry$html = entry.html, | ||
html = _entry$html === void 0 ? '' : _entry$html; | ||
var getHTMLWithStylePlaceholder = function getHTMLWithStylePlaceholder(tpl) { | ||
@@ -395,3 +357,2 @@ return styles.reduceRight(function (html, styleSrc) { | ||
}; | ||
var getHTMLWithScriptPlaceholder = function getHTMLWithScriptPlaceholder(tpl) { | ||
@@ -402,3 +363,2 @@ return scripts.reduce(function (html, scriptSrc) { | ||
}; | ||
return getEmbedHTML(getTemplate(getHTMLWithScriptPlaceholder(getHTMLWithStylePlaceholder(html))), styles, { | ||
@@ -418,7 +378,5 @@ fetch: fetch | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
if (!scripts.length) { | ||
return Promise.resolve(); | ||
} | ||
return _execScripts(scripts[scripts.length - 1], scripts, proxy, _objectSpread({ | ||
@@ -425,0 +383,0 @@ fetch: fetch, |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -10,7 +9,4 @@ value: true | ||
exports.inlineScriptReplaceSymbol = exports.genScriptReplaceSymbol = exports.genModuleScriptReplaceSymbol = exports.genLinkReplaceSymbol = exports.genIgnoreAssetReplaceSymbol = void 0; | ||
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); | ||
var _utils = require("./utils"); | ||
/** | ||
@@ -21,2 +17,3 @@ * @author Kuitos | ||
*/ | ||
var ALL_SCRIPT_REGEX = /(<script[\s\S]*?>)[\s\S]*?<\/script>/gi; | ||
@@ -41,11 +38,8 @@ var SCRIPT_TAG_REGEX = /<(script)\s+((?!type=('|")text\/ng\x2Dtemplate\3)[\s\S])*?>[\s\S]*?<\/\1>/i; | ||
var SCRIPT_IGNORE_REGEX = /<script(\s+|\s+[\s\S]+\s+)ignore(\s*|\s+[\s\S]*|=[\s\S]*)>/i; | ||
function hasProtocol(url) { | ||
return url.startsWith('//') || url.startsWith('http://') || url.startsWith('https://'); | ||
} | ||
function getEntirePath(path, baseURI) { | ||
return new URL(path, baseURI).toString(); | ||
} | ||
function isValidJavaScriptType(type) { | ||
@@ -55,3 +49,2 @@ var handleTypes = ['text/javascript', 'module', 'application/javascript', 'text/ecmascript', 'application/ecmascript']; | ||
} | ||
var genLinkReplaceSymbol = function genLinkReplaceSymbol(linkHref) { | ||
@@ -61,5 +54,3 @@ var preloadOrPrefetch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; | ||
}; | ||
exports.genLinkReplaceSymbol = genLinkReplaceSymbol; | ||
var genScriptReplaceSymbol = function genScriptReplaceSymbol(scriptSrc) { | ||
@@ -69,16 +60,13 @@ var async = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; | ||
}; | ||
exports.genScriptReplaceSymbol = genScriptReplaceSymbol; | ||
var inlineScriptReplaceSymbol = "<!-- inline scripts replaced by import-html-entry -->"; | ||
exports.inlineScriptReplaceSymbol = inlineScriptReplaceSymbol; | ||
var genIgnoreAssetReplaceSymbol = function genIgnoreAssetReplaceSymbol(url) { | ||
return "<!-- ignore asset ".concat(url || 'file', " replaced by import-html-entry -->"); | ||
}; | ||
exports.genIgnoreAssetReplaceSymbol = genIgnoreAssetReplaceSymbol; | ||
var genModuleScriptReplaceSymbol = function genModuleScriptReplaceSymbol(scriptSrc, moduleSupport) { | ||
return "<!-- ".concat(moduleSupport ? 'nomodule' : 'module', " script ").concat(scriptSrc, " ignored by import-html-entry -->"); | ||
}; | ||
/** | ||
@@ -96,6 +84,3 @@ * parse the script link from the template | ||
*/ | ||
exports.genModuleScriptReplaceSymbol = genModuleScriptReplaceSymbol; | ||
function processTpl(tpl, baseURI, postProcessTemplate) { | ||
@@ -107,6 +92,6 @@ var scripts = []; | ||
var template = tpl | ||
/* | ||
remove html comment first | ||
*/ | ||
.replace(HTML_COMMENT_REGEX, '').replace(LINK_TAG_REGEX, function (match) { | ||
*/.replace(HTML_COMMENT_REGEX, '').replace(LINK_TAG_REGEX, function (match) { | ||
/* | ||
@@ -116,19 +101,15 @@ change the css link | ||
var styleType = !!match.match(STYLE_TYPE_REGEX); | ||
if (styleType) { | ||
var styleHref = match.match(STYLE_HREF_REGEX); | ||
var styleIgnore = match.match(LINK_IGNORE_REGEX); | ||
if (styleHref) { | ||
var href = styleHref && styleHref[2]; | ||
var newHref = href; | ||
if (href && !hasProtocol(href)) { | ||
newHref = getEntirePath(href, baseURI); | ||
} | ||
if (styleIgnore) { | ||
return genIgnoreAssetReplaceSymbol(newHref); | ||
} | ||
newHref = (0, _utils.parseUrl)(newHref); | ||
styles.push(newHref); | ||
@@ -138,13 +119,9 @@ return genLinkReplaceSymbol(newHref); | ||
} | ||
var preloadOrPrefetchType = match.match(LINK_PRELOAD_OR_PREFETCH_REGEX) && match.match(LINK_HREF_REGEX) && !match.match(LINK_AS_FONT); | ||
if (preloadOrPrefetchType) { | ||
var _match$match = match.match(LINK_HREF_REGEX), | ||
_match$match2 = (0, _slicedToArray2["default"])(_match$match, 3), | ||
linkHref = _match$match2[2]; | ||
_match$match2 = (0, _slicedToArray2["default"])(_match$match, 3), | ||
linkHref = _match$match2[2]; | ||
return genLinkReplaceSymbol(linkHref, true); | ||
} | ||
return match; | ||
@@ -155,16 +132,15 @@ }).replace(STYLE_TAG_REGEX, function (match) { | ||
} | ||
return match; | ||
}).replace(ALL_SCRIPT_REGEX, function (match, scriptTag) { | ||
var scriptIgnore = scriptTag.match(SCRIPT_IGNORE_REGEX); | ||
var moduleScriptIgnore = moduleSupport && !!scriptTag.match(SCRIPT_NO_MODULE_REGEX) || !moduleSupport && !!scriptTag.match(SCRIPT_MODULE_REGEX); // in order to keep the exec order of all javascripts | ||
var moduleScriptIgnore = moduleSupport && !!scriptTag.match(SCRIPT_NO_MODULE_REGEX) || !moduleSupport && !!scriptTag.match(SCRIPT_MODULE_REGEX); | ||
// in order to keep the exec order of all javascripts | ||
var matchedScriptTypeMatch = scriptTag.match(SCRIPT_TYPE_REGEX); | ||
var matchedScriptType = matchedScriptTypeMatch && matchedScriptTypeMatch[2]; | ||
if (!isValidJavaScriptType(matchedScriptType)) { | ||
return match; | ||
} // if it is a external script | ||
} | ||
// if it is a external script | ||
if (SCRIPT_TAG_REGEX.test(match) && scriptTag.match(SCRIPT_SRC_REGEX)) { | ||
@@ -174,6 +150,6 @@ /* | ||
*/ | ||
var matchedScriptEntry = scriptTag.match(SCRIPT_ENTRY_REGEX); | ||
var matchedScriptSrcMatch = scriptTag.match(SCRIPT_SRC_REGEX); | ||
var matchedScriptSrc = matchedScriptSrcMatch && matchedScriptSrcMatch[2]; | ||
if (entry && matchedScriptEntry) { | ||
@@ -186,16 +162,13 @@ throw new SyntaxError('You should not set multiply entry script!'); | ||
} | ||
entry = entry || matchedScriptEntry && matchedScriptSrc; | ||
} | ||
if (scriptIgnore) { | ||
return genIgnoreAssetReplaceSymbol(matchedScriptSrc || 'js file'); | ||
} | ||
if (moduleScriptIgnore) { | ||
return genModuleScriptReplaceSymbol(matchedScriptSrc || 'js file', moduleSupport); | ||
} | ||
if (matchedScriptSrc) { | ||
var asyncScript = !!scriptTag.match(SCRIPT_ASYNC_REGEX); | ||
matchedScriptSrc = (0, _utils.parseUrl)(matchedScriptSrc); | ||
scripts.push(asyncScript ? { | ||
@@ -207,3 +180,2 @@ async: true, | ||
} | ||
return match; | ||
@@ -214,18 +186,16 @@ } else { | ||
} | ||
if (moduleScriptIgnore) { | ||
return genModuleScriptReplaceSymbol('js file', moduleSupport); | ||
} // if it is an inline script | ||
} | ||
// if it is an inline script | ||
var code = (0, _utils.getInlineCode)(match); | ||
var code = (0, _utils.getInlineCode)(match); // remove script blocks when all of these lines are comments. | ||
// remove script blocks when all of these lines are comments. | ||
var isPureCommentBlock = code.split(/[\r\n]+/).every(function (line) { | ||
return !line.trim() || line.trim().startsWith('//'); | ||
}); | ||
if (!isPureCommentBlock) { | ||
scripts.push(match); | ||
} | ||
return inlineScriptReplaceSymbol; | ||
@@ -245,8 +215,6 @@ } | ||
}; | ||
if (typeof postProcessTemplate === 'function') { | ||
tplResult = postProcessTemplate(tplResult); | ||
} | ||
return tplResult; | ||
} |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -14,9 +13,7 @@ value: true | ||
exports.noteGlobalProps = noteGlobalProps; | ||
exports.parseUrl = parseUrl; | ||
exports.readResAsString = readResAsString; | ||
exports.requestIdleCallback = void 0; | ||
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); | ||
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); | ||
/** | ||
@@ -28,7 +25,6 @@ * @author Kuitos | ||
*/ | ||
var isIE11 = typeof navigator !== 'undefined' && navigator.userAgent.indexOf('Trident') !== -1; | ||
function shouldSkipProperty(global, p) { | ||
if (!global.hasOwnProperty(p) || !isNaN(p) && p < global.length) return true; | ||
if (isIE11) { | ||
@@ -44,7 +40,6 @@ // https://github.com/kuitos/import-html-entry/pull/32,最小化 try 范围 | ||
} | ||
} // safari unpredictably lists some new globals first or second in object order | ||
} | ||
// safari unpredictably lists some new globals first or second in object order | ||
var firstGlobalProp, secondGlobalProp, lastGlobalProp; | ||
function getGlobalProp(global) { | ||
@@ -54,9 +49,8 @@ var cnt = 0; | ||
var hasIframe = false; | ||
for (var p in global) { | ||
if (shouldSkipProperty(global, p)) continue; // 遍历 iframe,检查 window 上的属性值是否是 iframe,是则跳过后面的 first 和 second 判断 | ||
if (shouldSkipProperty(global, p)) continue; | ||
// 遍历 iframe,检查 window 上的属性值是否是 iframe,是则跳过后面的 first 和 second 判断 | ||
for (var i = 0; i < window.frames.length && !hasIframe; i++) { | ||
var frame = window.frames[i]; | ||
if (frame === global[p]) { | ||
@@ -67,3 +61,2 @@ hasIframe = true; | ||
} | ||
if (!hasIframe && (cnt === 0 && p !== firstGlobalProp || cnt === 1 && p !== secondGlobalProp)) return p; | ||
@@ -73,6 +66,4 @@ cnt++; | ||
} | ||
if (lastProp !== lastGlobalProp) return lastProp; | ||
} | ||
function noteGlobalProps(global) { | ||
@@ -82,3 +73,2 @@ // alternatively Object.keys(global).pop() | ||
firstGlobalProp = secondGlobalProp = undefined; | ||
for (var p in global) { | ||
@@ -89,6 +79,4 @@ if (shouldSkipProperty(global, p)) continue; | ||
} | ||
return lastGlobalProp; | ||
} | ||
function getInlineCode(match) { | ||
@@ -99,3 +87,2 @@ var start = match.indexOf('>') + 1; | ||
} | ||
function defaultGetPublicPath(entry) { | ||
@@ -105,10 +92,8 @@ if ((0, _typeof2["default"])(entry) === 'object') { | ||
} | ||
try { | ||
var _URL = new URL(entry, location.href), | ||
origin = _URL.origin, | ||
pathname = _URL.pathname; | ||
var paths = pathname.split('/'); // 移除最后一个元素 | ||
origin = _URL.origin, | ||
pathname = _URL.pathname; | ||
var paths = pathname.split('/'); | ||
// 移除最后一个元素 | ||
paths.pop(); | ||
@@ -120,11 +105,11 @@ return "".concat(origin).concat(paths.join('/'), "/"); | ||
} | ||
} // Detect whether browser supports `<script type=module>` or not | ||
} | ||
// Detect whether browser supports `<script type=module>` or not | ||
function isModuleScriptSupported() { | ||
var s = document.createElement('script'); | ||
return 'noModule' in s; | ||
} // RIC and shim for browsers setTimeout() without it | ||
} | ||
// RIC and shim for browsers setTimeout() without it | ||
var requestIdleCallback = window.requestIdleCallback || function requestIdleCallback(cb) { | ||
@@ -141,5 +126,3 @@ var start = Date.now(); | ||
}; | ||
exports.requestIdleCallback = requestIdleCallback; | ||
function readResAsString(response, autoDetectCharset) { | ||
@@ -149,49 +132,43 @@ // 未启用自动检测 | ||
return response.text(); | ||
} // 如果没headers,发生在test环境下的mock数据,为兼容原有测试用例 | ||
} | ||
// 如果没headers,发生在test环境下的mock数据,为兼容原有测试用例 | ||
if (!response.headers) { | ||
return response.text(); | ||
} // 如果没返回content-type,走默认逻辑 | ||
} | ||
// 如果没返回content-type,走默认逻辑 | ||
var contentType = response.headers.get('Content-Type'); | ||
if (!contentType) { | ||
return response.text(); | ||
} // 解析content-type内的charset | ||
} | ||
// 解析content-type内的charset | ||
// Content-Type: text/html; charset=utf-8 | ||
// Content-Type: multipart/form-data; boundary=something | ||
// GET请求下不会出现第二种content-type | ||
var charset = 'utf-8'; | ||
var parts = contentType.split(';'); | ||
if (parts.length === 2) { | ||
var _parts$1$split = parts[1].split('='), | ||
_parts$1$split2 = (0, _slicedToArray2["default"])(_parts$1$split, 2), | ||
value = _parts$1$split2[1]; | ||
_parts$1$split2 = (0, _slicedToArray2["default"])(_parts$1$split, 2), | ||
value = _parts$1$split2[1]; | ||
var encoding = value && value.trim(); | ||
if (encoding) { | ||
charset = encoding; | ||
} | ||
} // 如果还是utf-8,那么走默认,兼容原有逻辑,这段代码删除也应该工作 | ||
} | ||
// 如果还是utf-8,那么走默认,兼容原有逻辑,这段代码删除也应该工作 | ||
if (charset.toUpperCase() === 'UTF-8') { | ||
return response.text(); | ||
} // 走流读取,编码可能是gbk,gb2312等,比如sofa 3默认是gbk编码 | ||
} | ||
// 走流读取,编码可能是gbk,gb2312等,比如sofa 3默认是gbk编码 | ||
return response.blob().then(function (file) { | ||
return new Promise(function (resolve, reject) { | ||
var reader = new window.FileReader(); | ||
reader.onload = function () { | ||
resolve(reader.result); | ||
}; | ||
reader.onerror = reject; | ||
@@ -202,8 +179,5 @@ reader.readAsText(file, charset); | ||
} | ||
var evalCache = {}; | ||
function evalCode(scriptSrc, code) { | ||
var key = scriptSrc; | ||
if (!evalCache[key]) { | ||
@@ -213,5 +187,12 @@ var functionWrappedCode = "(function(){".concat(code, "})"); | ||
} | ||
var evalFunc = evalCache[key]; | ||
evalFunc.call(window); | ||
} | ||
// 转换 url 中的转义字符,例如 & => & | ||
function parseUrl(url) { | ||
var parser = new DOMParser(); | ||
var html = "<script src=\"".concat(url, "\"></script>"); | ||
var doc = parser.parseFromString(html, "text/html"); | ||
return doc.scripts[0].src; | ||
} |
{ | ||
"name": "import-html-entry", | ||
"version": "1.14.3", | ||
"version": "1.14.4", | ||
"description": "import html and get the exports of entry", | ||
@@ -5,0 +5,0 @@ "main": "./lib/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 1 instance in 1 package
73821
1458
4
33