@rsbuild/plugin-assets-retry 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,9 @@
1
+ let __rslib_import_meta_url__ = 'undefined' == typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
1
2
  var __webpack_modules__ = {
2
- "../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
3
- module1.exports = __webpack_require__("crypto").randomBytes;
3
+ "../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
4
+ module.exports = __webpack_require__("crypto").randomBytes;
4
5
  },
5
- "../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
6
+ "../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
6
7
  "use strict";
7
8
  var randomBytes = __webpack_require__("../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js"), UID = function() {
8
9
  for(var bytes = randomBytes(16), result = '', i = 0; i < 16; ++i)result += bytes[i].toString(16);
@@ -20,7 +21,7 @@ var __webpack_modules__ = {
20
21
  function escapeUnsafeChars(unsafeChar) {
21
22
  return ESCAPED_CHARS[unsafeChar];
22
23
  }
23
- module1.exports = function serialize(obj, options) {
24
+ module.exports = function serialize(obj, options) {
24
25
  options || (options = {}), ('number' == typeof options || 'string' == typeof options) && (options = {
25
26
  space: options
26
27
  });
@@ -60,24 +61,24 @@ var __webpack_modules__ = {
60
61
  });
61
62
  };
62
63
  },
63
- crypto: function(module1) {
64
+ crypto: function(module) {
64
65
  "use strict";
65
- module1.exports = require("crypto");
66
+ module.exports = require("crypto");
66
67
  }
67
68
  }, __webpack_module_cache__ = {};
68
69
  function __webpack_require__(moduleId) {
69
70
  var cachedModule = __webpack_module_cache__[moduleId];
70
71
  if (void 0 !== cachedModule) return cachedModule.exports;
71
- var module1 = __webpack_module_cache__[moduleId] = {
72
+ var module = __webpack_module_cache__[moduleId] = {
72
73
  exports: {}
73
74
  };
74
- return __webpack_modules__[moduleId](module1, module1.exports, __webpack_require__), module1.exports;
75
+ return __webpack_modules__[moduleId](module, module.exports, __webpack_require__), module.exports;
75
76
  }
76
- __webpack_require__.n = function(module1) {
77
- var getter = module1 && module1.__esModule ? function() {
78
- return module1.default;
77
+ __webpack_require__.n = function(module) {
78
+ var getter = module && module.__esModule ? function() {
79
+ return module.default;
79
80
  } : function() {
80
- return module1;
81
+ return module;
81
82
  };
82
83
  return __webpack_require__.d(getter, {
83
84
  a: getter
@@ -117,7 +118,7 @@ var __webpack_exports__ = {};
117
118
  writable: !0
118
119
  }) : obj[key] = value, obj;
119
120
  }
120
- let AsyncChunkRetryPlugin_dirname = external_node_path_default().dirname((0, external_node_url_namespaceObject.fileURLToPath)('undefined' == typeof document ? new (module.require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href));
121
+ let AsyncChunkRetryPlugin_dirname = external_node_path_default().dirname((0, external_node_url_namespaceObject.fileURLToPath)(__rslib_import_meta_url__));
121
122
  class AsyncChunkRetryPlugin {
122
123
  getRawRuntimeRetryCode() {
123
124
  let { RuntimeGlobals } = core_namespaceObject.rspack, filename = 'asyncChunkRetry', runtimeFilePath = external_node_path_default().join(AsyncChunkRetryPlugin_dirname, 'runtime', this.options.minify ? `${filename}.min.js` : `${filename}.js`);
@@ -125,26 +126,26 @@ var __webpack_exports__ = {};
125
126
  }
126
127
  apply(compiler) {
127
128
  compiler.hooks.thisCompilation.tap(this.name, (compilation)=>{
128
- compilation.hooks.runtimeModule.tap(this.name, (module1)=>{
129
+ compilation.hooks.runtimeModule.tap(this.name, (module)=>{
129
130
  var _module_constructor;
130
- let { isRspack } = this.options, constructorName = isRspack ? module1.constructorName : null === (_module_constructor = module1.constructor) || void 0 === _module_constructor ? void 0 : _module_constructor.name;
131
- if (!('publicPath' === module1.name || 'PublicPathRuntimeModule' === constructorName || 'AutoPublicPathRuntimeModule' === constructorName)) return;
131
+ let { isRspack } = this.options, constructorName = isRspack ? module.constructorName : null === (_module_constructor = module.constructor) || void 0 === _module_constructor ? void 0 : _module_constructor.name;
132
+ if (!('publicPath' === module.name || 'PublicPathRuntimeModule' === constructorName || 'AutoPublicPathRuntimeModule' === constructorName)) return;
132
133
  let runtimeCode = this.getRawRuntimeRetryCode();
133
- isRspack ? !function(module1, appendSource) {
134
+ isRspack ? !function(module, appendSource) {
134
135
  try {
135
- let source = module1.source.source.toString();
136
- module1.source.source = Buffer.from(`${source}\n${appendSource}`, 'utf-8');
136
+ let source = module.source.source.toString();
137
+ module.source.source = Buffer.from(`${source}\n${appendSource}`, 'utf-8');
137
138
  } catch (err) {
138
139
  throw console.error('Failed to modify Rspack RuntimeModule'), err;
139
140
  }
140
- }(module1, runtimeCode) : !function(module1, appendSource) {
141
+ }(module, runtimeCode) : !function(module, appendSource) {
141
142
  try {
142
- let originSource = module1.getGeneratedCode();
143
- module1.getGeneratedCode = ()=>`${originSource}\n${appendSource}`;
143
+ let originSource = module.getGeneratedCode();
144
+ module.getGeneratedCode = ()=>`${originSource}\n${appendSource}`;
144
145
  } catch (err) {
145
146
  throw console.error('Failed to modify Webpack RuntimeModule'), err;
146
147
  }
147
- }(module1, runtimeCode);
148
+ }(module, runtimeCode);
148
149
  });
149
150
  });
150
151
  }
@@ -162,7 +163,7 @@ var __webpack_exports__ = {};
162
163
  ]);
163
164
  }
164
165
  }
165
- let src_dirname = external_node_path_default().dirname((0, external_node_url_namespaceObject.fileURLToPath)('undefined' == typeof document ? new (module.require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href)), PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
166
+ let src_dirname = external_node_path_default().dirname((0, external_node_url_namespaceObject.fileURLToPath)(__rslib_import_meta_url__)), PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
166
167
  async function getRetryCode(options) {
167
168
  let filename = 'initialChunkRetry', { minify, inlineScript: _, ...restOptions } = options, runtimeFilePath = external_node_path_default().join(src_dirname, 'runtime', minify ? `${filename}.min.js` : `${filename}.js`), runtimeCode = await external_node_fs_default().promises.readFile(runtimeFilePath, 'utf-8');
168
169
  return `(function(){${runtimeCode};init(${serialize_javascript_default()(restOptions)});})()`;
@@ -172,7 +173,7 @@ var __webpack_exports__ = {};
172
173
  setup (api) {
173
174
  let { inlineScript = !0 } = userOptions, getScriptPath = (environment)=>{
174
175
  let distDir = environment.config.output.distPath.js;
175
- return external_node_path_default().posix.join(distDir, "assets-retry.1-0-5.js");
176
+ return external_node_path_default().posix.join(distDir, "assets-retry.1-0-7.js");
176
177
  }, formatOptions = (config)=>{
177
178
  let options = {
178
179
  ...userOptions
@@ -225,7 +226,7 @@ var __webpack_exports__ = {};
225
226
  });
226
227
  })();
227
228
  var __webpack_export_target__ = exports;
228
- for(var i in __webpack_exports__)__webpack_export_target__[i] = __webpack_exports__[i];
229
+ for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
229
230
  __webpack_exports__.__esModule && Object.defineProperty(__webpack_export_target__, '__esModule', {
230
231
  value: !0
231
232
  });
package/dist/index.js CHANGED
@@ -156,7 +156,7 @@ let pluginAssetsRetry = (userOptions = {})=>({
156
156
  setup (api) {
157
157
  let { inlineScript = !0 } = userOptions, getScriptPath = (environment)=>{
158
158
  let distDir = environment.config.output.distPath.js;
159
- return __WEBPACK_EXTERNAL_MODULE_node_path__.default.posix.join(distDir, "assets-retry.1-0-5.js");
159
+ return __WEBPACK_EXTERNAL_MODULE_node_path__.default.posix.join(distDir, "assets-retry.1-0-7.js");
160
160
  }, formatOptions = (config)=>{
161
161
  let options = {
162
162
  ...userOptions
@@ -50,28 +50,8 @@ function getUrlRetryQuery(existRetryTimes, originalQuery) {
50
50
  }
51
51
  return '';
52
52
  }
53
- function removeDomainFromUrl(url) {
54
- var protocolStartIndex = url.indexOf('//');
55
-
56
- // case /app/main/static/js/index.js
57
- if (protocolStartIndex === -1 && url.startsWith('/')) {
58
- return url;
59
- }
60
-
61
- // case "//cdn.com/app/main/static/js/index.js"
62
- // case "http://cdn.com/app/main/static/js/index.js"
63
- var protocolEndIndex = protocolStartIndex + 2;
64
- var pathStartIndex = url.indexOf('/', protocolEndIndex);
65
- return url.slice(pathStartIndex);
66
- }
67
-
68
- // "http://cdn.com/app/main/static/js/index.js?query=1#hash" -> "/app/main/static/js/index.js"
69
- function getAbsolutePathFromUrl(url) {
70
- return cleanUrl(removeDomainFromUrl(url));
71
- }
72
- function getNextRetryUrl(existRetryTimes, nextDomain, originalSrcUrl) {
73
- var absolutePath = getAbsolutePathFromUrl(originalSrcUrl);
74
- return nextDomain + absolutePath + getUrlRetryQuery(existRetryTimes, getQueryFromUrl(originalSrcUrl));
53
+ function getNextRetryUrl(currRetryUrl, domain, nextDomain, existRetryTimes, originalQuery) {
54
+ return cleanUrl(currRetryUrl.replace(domain, nextDomain)) + getUrlRetryQuery(existRetryTimes + 1, originalQuery);
75
55
  }
76
56
 
77
57
  // shared between ensureChunk and loadScript
@@ -83,14 +63,17 @@ function getCurrentRetry(chunkId, existRetryTimes) {
83
63
  function initRetry(chunkId) {
84
64
  var _config$domain$, _config$domain3;
85
65
  var originalScriptFilename = originalGetChunkScriptFilename(chunkId);
86
- var originalSrcUrl = __RUNTIME_GLOBALS_PUBLIC_PATH__ + originalScriptFilename;
87
- var existRetryTimes = 1;
66
+ var originalPublicPath = __RUNTIME_GLOBALS_PUBLIC_PATH__;
67
+ var originalSrcUrl = originalPublicPath.startsWith('/') ? window.origin + originalPublicPath + originalScriptFilename : originalPublicPath + originalScriptFilename;
68
+ var originalQuery = getQueryFromUrl(originalSrcUrl);
69
+ var existRetryTimes = 0;
88
70
  var nextDomain = (_config$domain$ = (_config$domain3 = config.domain) === null || _config$domain3 === void 0 ? void 0 : _config$domain3[0]) !== null && _config$domain$ !== void 0 ? _config$domain$ : window.origin;
89
71
  return {
90
72
  nextDomain: nextDomain,
91
- nextRetryUrl: getNextRetryUrl(existRetryTimes, nextDomain, originalSrcUrl),
73
+ nextRetryUrl: getNextRetryUrl(originalSrcUrl, nextDomain, nextDomain, existRetryTimes, originalQuery),
92
74
  originalScriptFilename: originalScriptFilename,
93
- originalSrcUrl: originalSrcUrl
75
+ originalSrcUrl: originalSrcUrl,
76
+ originalQuery: originalQuery
94
77
  };
95
78
  }
96
79
  function nextRetry(chunkId, existRetryTimes) {
@@ -102,13 +85,15 @@ function nextRetry(chunkId, existRetryTimes) {
102
85
  retryCollector[chunkId] = [];
103
86
  } else {
104
87
  var originalScriptFilename = currRetry.originalScriptFilename,
105
- originalSrcUrl = currRetry.originalSrcUrl;
88
+ originalSrcUrl = currRetry.originalSrcUrl,
89
+ originalQuery = currRetry.originalQuery;
106
90
  var nextDomain = findNextDomain(currRetry.nextDomain);
107
91
  nextRetry = {
108
92
  nextDomain: nextDomain,
109
- nextRetryUrl: getNextRetryUrl(nextExistRetryTimes, nextDomain, originalSrcUrl),
93
+ nextRetryUrl: getNextRetryUrl(currRetry.nextRetryUrl, currRetry.nextDomain, nextDomain, existRetryTimes, originalQuery),
110
94
  originalScriptFilename: originalScriptFilename,
111
- originalSrcUrl: originalSrcUrl
95
+ originalSrcUrl: originalSrcUrl,
96
+ originalQuery: originalQuery
112
97
  };
113
98
  }
114
99
  retryCollector[chunkId][nextExistRetryTimes] = nextRetry;
@@ -163,12 +148,12 @@ arg0, arg1, arg2, arg3, arg4, arg5, arg6) {
163
148
  // the first calling is not retry
164
149
  // if the failed request is 4 in network panel, callingCounter.count === 4, the first one is the normal request, and existRetryTimes is 3, retried 3 times
165
150
  var existRetryTimes = callingCounter.count - 1;
166
- var originalSrcUrl;
151
+ var originalScriptFilename;
167
152
  var nextRetryUrl;
168
153
  var nextDomain;
169
154
  try {
170
155
  var retryResult = nextRetry(chunkId, existRetryTimes);
171
- originalSrcUrl = retryResult.originalSrcUrl;
156
+ originalScriptFilename = retryResult.originalScriptFilename;
172
157
  nextRetryUrl = retryResult.nextRetryUrl;
173
158
  nextDomain = retryResult.nextDomain;
174
159
  } catch (e) {
@@ -192,7 +177,7 @@ arg0, arg1, arg2, arg3, arg4, arg5, arg6) {
192
177
  var context = createContext(existRetryTimes);
193
178
  if (existRetryTimes >= maxRetries) {
194
179
  var _error$message2;
195
- error.message = (_error$message2 = error.message) !== null && _error$message2 !== void 0 && _error$message2.includes('retries:') ? error.message : "Loading chunk ".concat(chunkId, " from ").concat(originalSrcUrl, " failed after ").concat(maxRetries, " retries: \"").concat(error.message, "\"");
180
+ error.message = (_error$message2 = error.message) !== null && _error$message2 !== void 0 && _error$message2.includes('retries:') ? error.message : "Loading chunk ".concat(chunkId, " from \"").concat(originalScriptFilename, "\" failed after ").concat(maxRetries, " retries: \"").concat(error.message, "\"");
196
181
  if (typeof config.onFail === 'function') {
197
182
  config.onFail(context);
198
183
  }
@@ -1 +1 @@
1
- "use strict";var _ref,_RUNTIME_GLOBALS_GET,config=__RETRY_OPTIONS__,maxRetries=config.max||3,retryCollector={};function findCurrentDomain(n){for(var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i="",t=0;t<e.length;t++)if(-1!==n.indexOf(e[t])){i=e[t];break}return i||window.origin}function findNextDomain(n){var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i=findCurrentDomain(n),t=e.indexOf(i);return e[(t+1)%e.length]||n}var postfixRE=/[?#].*$/;function cleanUrl(n){return n.replace(postfixRE,"")}function getQueryFromUrl(n){var r=n.split("?")[1];return r?"?".concat(r.split("#")[0]):""}function getUrlRetryQuery(n,r){return!0===config.addQuery?""!==r?"".concat(r,"&retry=").concat(n):"?retry=".concat(n):"function"==typeof config.addQuery?config.addQuery({times:n,originalQuery:r}):""}function removeDomainFromUrl(n){var r=n.indexOf("//");if(-1===r&&n.startsWith("/"))return n;var e=r+2,i=n.indexOf("/",e);return n.slice(i)}function getAbsolutePathFromUrl(n){return cleanUrl(removeDomainFromUrl(n))}function getNextRetryUrl(n,r,e){return r+getAbsolutePathFromUrl(e)+getUrlRetryQuery(n,getQueryFromUrl(e))}var globalCurrRetrying={};function getCurrentRetry(n,r){var e;return null===(e=retryCollector[n])||void 0===e?void 0:e[r]}function initRetry(n){var r,e,i=originalGetChunkScriptFilename(n),t=__RUNTIME_GLOBALS_PUBLIC_PATH__+i,o=null!==(r=null===(e=config.domain)||void 0===e?void 0:e[0])&&void 0!==r?r:window.origin;return{nextDomain:o,nextRetryUrl:getNextRetryUrl(1,o,t),originalScriptFilename:i,originalSrcUrl:t}}function nextRetry(n,r){var e,i=getCurrentRetry(n,r),t=r+1;if(0===r||void 0===i)e=initRetry(n),retryCollector[n]=[];else{var o=i.originalScriptFilename,a=i.originalSrcUrl,l=findNextDomain(i.nextDomain);e={nextDomain:l,nextRetryUrl:getNextRetryUrl(t,l,a),originalScriptFilename:o,originalSrcUrl:a}}return retryCollector[n][t]=e,globalCurrRetrying[n]=e,e}var originalEnsureChunk=__RUNTIME_GLOBALS_ENSURE_CHUNK__,originalGetChunkScriptFilename=__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__,originalGetCssFilename=null!==(_ref=null!==(_RUNTIME_GLOBALS_GET=__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__)&&void 0!==_RUNTIME_GLOBALS_GET?_RUNTIME_GLOBALS_GET:__RUNTIME_GLOBALS_GET_CSS_FILENAME__)&&void 0!==_ref?_ref:function(){return null},originalLoadScript=__RUNTIME_GLOBALS_LOAD_SCRIPT__,ERROR_PREFIX="[@rsbuild/plugin-assets-retry] ";function ensureChunk(n,r,e,i,t,o,a,l){for(var c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:{count:0},_=arguments.length,u=new Array(_>9?_-9:0),f=9;f<_;f++)u[f-9]=arguments[f];var g=originalEnsureChunk.apply(void 0,[n,r,e,i,t,o,a,l,c].concat(u));try{var R=originalGetChunkScriptFilename(n),d=originalGetCssFilename(n);"undefined"!=typeof window&&(R&&(window.__RB_ASYNC_CHUNKS__[R]=!0),d&&(window.__RB_ASYNC_CHUNKS__[d]=!0))}catch(n){console.error(ERROR_PREFIX,"get original script or css filename error",n)}return"number"!=typeof(null==c?void 0:c.count)?g:(c.count+=1,g.catch((function(_){var f,g,R,d,s=c.count-1;try{var y=nextRetry(n,s);g=y.originalSrcUrl,R=y.nextRetryUrl,d=y.nextDomain}catch(n){throw console.error(ERROR_PREFIX,"failed to get nextRetryUrl",n),_}var m,S=Boolean(null==_||null===(f=_.message)||void 0===f?void 0:f.includes("CSS chunk")),E=function(n){return{times:n,domain:d,url:R,tagName:S?"link":"script",isAsyncChunk:!0}},U=E(s);if(s>=maxRetries)throw _.message=null!==(m=_.message)&&void 0!==m&&m.includes("retries:")?_.message:"Loading chunk ".concat(n," from ").concat(g," failed after ").concat(maxRetries,' retries: "').concat(_.message,'"'),"function"==typeof config.onFail&&config.onFail(U),_;var v=config.test;if(v){if("string"==typeof v){var C=new RegExp(v);v=function(n){return C.test(n)}}if("function"!=typeof v||!v(R))throw _}if(config.domain&&config.domain.length>0&&-1===config.domain.indexOf(d))throw _;return"function"==typeof config.onRetry&&config.onRetry(U),ensureChunk.apply(void 0,[n,r,e,i,t,o,a,l,c].concat(u)).then((function(n){var r=(null==c?void 0:c.count)===s+2;if("function"==typeof config.onSuccess&&r){var e=E(s+1);config.onSuccess(e)}return n}))})))}function loadScript(n,r,e,i){for(var t=globalCurrRetrying[i],o=arguments.length,a=new Array(o>4?o-4:0),l=4;l<o;l++)a[l-4]=arguments[l];return originalLoadScript.apply(void 0,[t?t.nextRetryUrl:n,r,e,i].concat(a))}function registerAsyncChunkRetry(){if("undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={}),"undefined"!=typeof __RUNTIME_GLOBALS_REQUIRE__)try{__RUNTIME_GLOBALS_ENSURE_CHUNK__=ensureChunk,__RUNTIME_GLOBALS_LOAD_SCRIPT__=loadScript}catch(n){console.error(ERROR_PREFIX,"Register async chunk retry runtime failed",n)}}registerAsyncChunkRetry();
1
+ "use strict";var _ref,_RUNTIME_GLOBALS_GET,config=__RETRY_OPTIONS__,maxRetries=config.max||3,retryCollector={};function findCurrentDomain(n){for(var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i="",t=0;t<e.length;t++)if(-1!==n.indexOf(e[t])){i=e[t];break}return i||window.origin}function findNextDomain(n){var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i=findCurrentDomain(n),t=e.indexOf(i);return e[(t+1)%e.length]||n}var postfixRE=/[?#].*$/;function cleanUrl(n){return n.replace(postfixRE,"")}function getQueryFromUrl(n){var r=n.split("?")[1];return r?"?".concat(r.split("#")[0]):""}function getUrlRetryQuery(n,r){return!0===config.addQuery?""!==r?"".concat(r,"&retry=").concat(n):"?retry=".concat(n):"function"==typeof config.addQuery?config.addQuery({times:n,originalQuery:r}):""}function getNextRetryUrl(n,r,e,i,t){return cleanUrl(n.replace(r,e))+getUrlRetryQuery(i+1,t)}var globalCurrRetrying={};function getCurrentRetry(n,r){var e;return null===(e=retryCollector[n])||void 0===e?void 0:e[r]}function initRetry(n){var r,e,i=originalGetChunkScriptFilename(n),t=__RUNTIME_GLOBALS_PUBLIC_PATH__,o=t.startsWith("/")?window.origin+t+i:t+i,a=getQueryFromUrl(o),l=null!==(r=null===(e=config.domain)||void 0===e?void 0:e[0])&&void 0!==r?r:window.origin;return{nextDomain:l,nextRetryUrl:getNextRetryUrl(o,l,l,0,a),originalScriptFilename:i,originalSrcUrl:o,originalQuery:a}}function nextRetry(n,r){var e,i=getCurrentRetry(n,r),t=r+1;if(0===r||void 0===i)e=initRetry(n),retryCollector[n]=[];else{var o=i.originalScriptFilename,a=i.originalSrcUrl,l=i.originalQuery,c=findNextDomain(i.nextDomain);e={nextDomain:c,nextRetryUrl:getNextRetryUrl(i.nextRetryUrl,i.nextDomain,c,r,l),originalScriptFilename:o,originalSrcUrl:a,originalQuery:l}}return retryCollector[n][t]=e,globalCurrRetrying[n]=e,e}var originalEnsureChunk=__RUNTIME_GLOBALS_ENSURE_CHUNK__,originalGetChunkScriptFilename=__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__,originalGetCssFilename=null!==(_ref=null!==(_RUNTIME_GLOBALS_GET=__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__)&&void 0!==_RUNTIME_GLOBALS_GET?_RUNTIME_GLOBALS_GET:__RUNTIME_GLOBALS_GET_CSS_FILENAME__)&&void 0!==_ref?_ref:function(){return null},originalLoadScript=__RUNTIME_GLOBALS_LOAD_SCRIPT__,ERROR_PREFIX="[@rsbuild/plugin-assets-retry] ";function ensureChunk(n,r,e,i,t,o,a,l){for(var c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:{count:0},_=arguments.length,u=new Array(_>9?_-9:0),f=9;f<_;f++)u[f-9]=arguments[f];var g=originalEnsureChunk.apply(void 0,[n,r,e,i,t,o,a,l,c].concat(u));try{var R=originalGetChunkScriptFilename(n),d=originalGetCssFilename(n);"undefined"!=typeof window&&(R&&(window.__RB_ASYNC_CHUNKS__[R]=!0),d&&(window.__RB_ASYNC_CHUNKS__[d]=!0))}catch(n){console.error(ERROR_PREFIX,"get original script or css filename error",n)}return"number"!=typeof(null==c?void 0:c.count)?g:(c.count+=1,g.catch((function(_){var f,g,R,d,y=c.count-1;try{var s=nextRetry(n,y);g=s.originalScriptFilename,R=s.nextRetryUrl,d=s.nextDomain}catch(n){throw console.error(ERROR_PREFIX,"failed to get nextRetryUrl",n),_}var S,E=Boolean(null==_||null===(f=_.message)||void 0===f?void 0:f.includes("CSS chunk")),m=function(n){return{times:n,domain:d,url:R,tagName:E?"link":"script",isAsyncChunk:!0}},C=m(y);if(y>=maxRetries)throw _.message=null!==(S=_.message)&&void 0!==S&&S.includes("retries:")?_.message:"Loading chunk ".concat(n,' from "').concat(g,'" failed after ').concat(maxRetries,' retries: "').concat(_.message,'"'),"function"==typeof config.onFail&&config.onFail(C),_;var U=config.test;if(U){if("string"==typeof U){var v=new RegExp(U);U=function(n){return v.test(n)}}if("function"!=typeof U||!U(R))throw _}if(config.domain&&config.domain.length>0&&-1===config.domain.indexOf(d))throw _;return"function"==typeof config.onRetry&&config.onRetry(C),ensureChunk.apply(void 0,[n,r,e,i,t,o,a,l,c].concat(u)).then((function(n){var r=(null==c?void 0:c.count)===y+2;if("function"==typeof config.onSuccess&&r){var e=m(y+1);config.onSuccess(e)}return n}))})))}function loadScript(n,r,e,i){for(var t=globalCurrRetrying[i],o=arguments.length,a=new Array(o>4?o-4:0),l=4;l<o;l++)a[l-4]=arguments[l];return originalLoadScript.apply(void 0,[t?t.nextRetryUrl:n,r,e,i].concat(a))}function registerAsyncChunkRetry(){if("undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={}),"undefined"!=typeof __RUNTIME_GLOBALS_REQUIRE__)try{__RUNTIME_GLOBALS_ENSURE_CHUNK__=ensureChunk,__RUNTIME_GLOBALS_LOAD_SCRIPT__=loadScript}catch(n){console.error(ERROR_PREFIX,"Register async chunk retry runtime failed",n)}}registerAsyncChunkRetry();
@@ -8,6 +8,7 @@ var TAG_TYPE = {
8
8
  img: HTMLImageElement
9
9
  };
10
10
  var TYPES = Object.keys(TAG_TYPE);
11
+ // this function is the same as async chunk retry
11
12
  function findCurrentDomain(url, domainList) {
12
13
  var domain = '';
13
14
  for (var i = 0; i < domainList.length; i++) {
@@ -18,6 +19,8 @@ function findCurrentDomain(url, domainList) {
18
19
  }
19
20
  return domain || window.origin;
20
21
  }
22
+
23
+ // this function is the same as async chunk retry
21
24
  function findNextDomain(url, domainList) {
22
25
  var currentDomain = findCurrentDomain(url, domainList);
23
26
  var index = domainList.indexOf(currentDomain);
@@ -184,6 +187,8 @@ function retry(config, e) {
184
187
 
185
188
  // if the initial request is "/static/js/async/src_Hello_tsx.js?q=1", retry url would be "/static/js/async/src_Hello_tsx.js?q=1&retry=1"
186
189
  var originalQuery = (_target$dataset$rsbui = target.dataset.rsbuildOriginalQuery) !== null && _target$dataset$rsbui !== void 0 ? _target$dataset$rsbui : getQueryFromUrl(url);
190
+
191
+ // this function is the same as async chunk retry
187
192
  function getUrlRetryQuery(existRetryTimes) {
188
193
  if (config.addQuery === true) {
189
194
  return originalQuery !== '' ? "".concat(originalQuery, "&retry=").concat(existRetryTimes) : "?retry=".concat(existRetryTimes);
@@ -196,9 +201,14 @@ function retry(config, e) {
196
201
  }
197
202
  return '';
198
203
  }
204
+
205
+ // this function is the same as async chunk retry
206
+ function getNextRetryUrl(currRetryUrl, domain, nextDomain, existRetryTimes) {
207
+ return cleanUrl(currRetryUrl.replace(domain, nextDomain)) + getUrlRetryQuery(existRetryTimes + 1);
208
+ }
199
209
  var isAsync = Boolean(target.dataset.rsbuildAsync) || target.async || target.defer;
200
210
  var attributes = {
201
- url: cleanUrl(url.replace(domain, nextDomain)) + getUrlRetryQuery(existRetryTimes + 1),
211
+ url: getNextRetryUrl(url, domain, nextDomain, existRetryTimes),
202
212
  times: existRetryTimes + 1,
203
213
  crossOrigin: config.crossOrigin,
204
214
  isAsync: isAsync,
@@ -1 +1 @@
1
- "use strict";var TAG_TYPE={link:HTMLLinkElement,script:HTMLScriptElement,img:HTMLImageElement},TYPES=Object.keys(TAG_TYPE);function findCurrentDomain(e,n){for(var t="",r=0;r<n.length;r++)if(-1!==e.indexOf(n[r])){t=n[r];break}return t||window.origin}function findNextDomain(e,n){var t=findCurrentDomain(e,n),r=n.indexOf(t);return n[(r+1)%n.length]||e}function getRequestUrl(e){return e instanceof HTMLScriptElement||e instanceof HTMLImageElement?e.src:e instanceof HTMLLinkElement?e.href:null}var defaultConfig={max:3,type:TYPES,domain:[],crossOrigin:!1};function validateTargetInfo(e,n){var t,r=n.target,i=null===(t=r.tagName)||void 0===t?void 0:t.toLocaleLowerCase(),a=e.type,o=getRequestUrl(r);return!!(i&&-1!==a.indexOf(i)&&TAG_TYPE[i]&&r instanceof TAG_TYPE[i]&&o)&&{target:r,tagName:i,url:o}}var postfixRE=/[?#].*$/;function cleanUrl(e){return e.replace(postfixRE,"")}function getQueryFromUrl(e){var n=e.split("?")[1];return n?"?".concat(n.split("#")[0]):""}function createElement(e,n){var t=!0===n.crossOrigin?"anonymous":n.crossOrigin,r=t?'crossorigin="'.concat(t,'"'):"",i=n.times?'data-rsbuild-retry-times="'.concat(n.times,'"'):"",a=n.originalQuery?'data-rsbuild-original-query="'.concat(n.originalQuery,'"'):"",o=n.isAsync?"data-rsbuild-async":"";if(e instanceof HTMLScriptElement){var c=document.createElement("script");return c.src=n.url,t&&(c.crossOrigin=t),n.times&&(c.dataset.rsbuildRetryTimes=String(n.times)),n.isAsync&&(c.dataset.rsbuildAsync=""),void 0!==n.originalQuery&&(c.dataset.rsbuildOriginalQuery=n.originalQuery),{element:c,str:'<script src="'.concat(n.url,'" ').concat(r," ").concat(i," ").concat(o," ").concat(a,">")+"<\/script>"}}if(e instanceof HTMLLinkElement){var s=document.createElement("link");return s.rel=e.rel||"stylesheet",e.as&&(s.as=e.as),s.href=n.url,t&&(s.crossOrigin=t),n.times&&(s.dataset.rsbuildRetryTimes=String(n.times)),void 0!==n.originalQuery&&(s.dataset.rsbuildOriginalQuery=n.originalQuery),{element:s,str:'<link rel="'.concat(s.rel,'" href="').concat(n.url,'" ').concat(r," ").concat(i," ").concat(s.as?'as="'.concat(s.as,'"'):""," ").concat(a,"></link>")}}}function reloadElementResource(e,n,t){e instanceof HTMLScriptElement&&(t.isAsync?document.body.appendChild(n.element):document.write(n.str)),e instanceof HTMLLinkElement&&document.getElementsByTagName("head")[0].appendChild(n.element),e instanceof HTMLImageElement&&(e.src=t.url,e.dataset.rsbuildRetryTimes=String(t.times),e.dataset.rsbuildOriginalQuery=String(t.originalQuery))}function retry(e,n){var t,r=validateTargetInfo(e,n);if(!1!==r){var i=r.target,a=r.tagName,o=r.url;if("undefined"==typeof window||!Object.keys(window.__RB_ASYNC_CHUNKS__||{}).some((function(e){return-1!==o.indexOf(e)}))){var c=e.test;if(c){if("string"==typeof c){var s=new RegExp(c);c=function(e){return s.test(e)}}if("function"!=typeof c||!c(o))return}var l=findCurrentDomain(o,e.domain);if(!(e.domain&&e.domain.length>0&&-1===e.domain.indexOf(l))){var u=Number(i.dataset.rsbuildRetryTimes)||0;if(u!==e.max){var d=findNextDomain(l,e.domain),f=null!==(t=i.dataset.rsbuildOriginalQuery)&&void 0!==t?t:getQueryFromUrl(o),m=Boolean(i.dataset.rsbuildAsync)||i.async||i.defer,y={url:cleanUrl(o.replace(l,d))+function(n){return!0===e.addQuery?""!==f?"".concat(f,"&retry=").concat(n):"?retry=".concat(n):"function"==typeof e.addQuery?e.addQuery({times:n,originalQuery:f}):""}(u+1),times:u+1,crossOrigin:e.crossOrigin,isAsync:m,originalQuery:f},g=createElement(i,y);if(e.onRetry&&"function"==typeof e.onRetry){var p={times:u,domain:l,url:o,tagName:a,isAsyncChunk:!1};e.onRetry(p)}reloadElementResource(i,g,y)}else if("function"==typeof e.onFail){var v={times:u,domain:l,url:o,tagName:a,isAsyncChunk:!1};e.onFail(v)}}}}}function load(e,n){var t=validateTargetInfo(e,n);if(!1!==t){var r=t.target,i=t.tagName,a=t.url,o=findCurrentDomain(a,e.domain),c=Number(r.dataset.rsbuildRetryTimes)||0;if(0!==c&&"function"==typeof e.onSuccess){var s={times:c,domain:o,url:a,tagName:i,isAsyncChunk:!1};e.onSuccess(s)}}}function resourceMonitor(e,n){"undefined"!=typeof window&&void 0!==window.document&&(document.addEventListener("error",(function(n){n&&n.target instanceof Element&&e(n)}),!0),document.addEventListener("load",(function(e){e&&e.target instanceof Element&&n(e)}),!0))}function init(e){var n={};for(var t in defaultConfig)n[t]=defaultConfig[t];for(var r in e)n[r]=e[r];Array.isArray(n.type)&&0!==n.type.length||(n.type=defaultConfig.type),Array.isArray(n.domain)&&0!==n.domain.length||(n.domain=defaultConfig.domain),Array.isArray(n.domain)&&(n.domain=n.domain.filter(Boolean)),"undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={});try{resourceMonitor((function(e){try{retry(n,e)}catch(e){console.error("retry error captured",e)}}),(function(e){try{load(n,e)}catch(e){console.error("load error captured",e)}}))}catch(e){console.error("monitor error captured",e)}}
1
+ "use strict";var TAG_TYPE={link:HTMLLinkElement,script:HTMLScriptElement,img:HTMLImageElement},TYPES=Object.keys(TAG_TYPE);function findCurrentDomain(e,n){for(var t="",r=0;r<n.length;r++)if(-1!==e.indexOf(n[r])){t=n[r];break}return t||window.origin}function findNextDomain(e,n){var t=findCurrentDomain(e,n),r=n.indexOf(t);return n[(r+1)%n.length]||e}function getRequestUrl(e){return e instanceof HTMLScriptElement||e instanceof HTMLImageElement?e.src:e instanceof HTMLLinkElement?e.href:null}var defaultConfig={max:3,type:TYPES,domain:[],crossOrigin:!1};function validateTargetInfo(e,n){var t,r=n.target,i=null===(t=r.tagName)||void 0===t?void 0:t.toLocaleLowerCase(),a=e.type,o=getRequestUrl(r);return!!(i&&-1!==a.indexOf(i)&&TAG_TYPE[i]&&r instanceof TAG_TYPE[i]&&o)&&{target:r,tagName:i,url:o}}var postfixRE=/[?#].*$/;function cleanUrl(e){return e.replace(postfixRE,"")}function getQueryFromUrl(e){var n=e.split("?")[1];return n?"?".concat(n.split("#")[0]):""}function createElement(e,n){var t=!0===n.crossOrigin?"anonymous":n.crossOrigin,r=t?'crossorigin="'.concat(t,'"'):"",i=n.times?'data-rsbuild-retry-times="'.concat(n.times,'"'):"",a=n.originalQuery?'data-rsbuild-original-query="'.concat(n.originalQuery,'"'):"",o=n.isAsync?"data-rsbuild-async":"";if(e instanceof HTMLScriptElement){var c=document.createElement("script");return c.src=n.url,t&&(c.crossOrigin=t),n.times&&(c.dataset.rsbuildRetryTimes=String(n.times)),n.isAsync&&(c.dataset.rsbuildAsync=""),void 0!==n.originalQuery&&(c.dataset.rsbuildOriginalQuery=n.originalQuery),{element:c,str:'<script src="'.concat(n.url,'" ').concat(r," ").concat(i," ").concat(o," ").concat(a,">")+"<\/script>"}}if(e instanceof HTMLLinkElement){var s=document.createElement("link");return s.rel=e.rel||"stylesheet",e.as&&(s.as=e.as),s.href=n.url,t&&(s.crossOrigin=t),n.times&&(s.dataset.rsbuildRetryTimes=String(n.times)),void 0!==n.originalQuery&&(s.dataset.rsbuildOriginalQuery=n.originalQuery),{element:s,str:'<link rel="'.concat(s.rel,'" href="').concat(n.url,'" ').concat(r," ").concat(i," ").concat(s.as?'as="'.concat(s.as,'"'):""," ").concat(a,"></link>")}}}function reloadElementResource(e,n,t){e instanceof HTMLScriptElement&&(t.isAsync?document.body.appendChild(n.element):document.write(n.str)),e instanceof HTMLLinkElement&&document.getElementsByTagName("head")[0].appendChild(n.element),e instanceof HTMLImageElement&&(e.src=t.url,e.dataset.rsbuildRetryTimes=String(t.times),e.dataset.rsbuildOriginalQuery=String(t.originalQuery))}function retry(e,n){var t,r=validateTargetInfo(e,n);if(!1!==r){var i=r.target,a=r.tagName,o=r.url;if("undefined"==typeof window||!Object.keys(window.__RB_ASYNC_CHUNKS__||{}).some((function(e){return-1!==o.indexOf(e)}))){var c=e.test;if(c){if("string"==typeof c){var s=new RegExp(c);c=function(e){return s.test(e)}}if("function"!=typeof c||!c(o))return}var u=findCurrentDomain(o,e.domain);if(!(e.domain&&e.domain.length>0&&-1===e.domain.indexOf(u))){var l=Number(i.dataset.rsbuildRetryTimes)||0;if(l!==e.max){var d=findNextDomain(u,e.domain),f=null!==(t=i.dataset.rsbuildOriginalQuery)&&void 0!==t?t:getQueryFromUrl(o),m=Boolean(i.dataset.rsbuildAsync)||i.async||i.defer,y={url:function(n,t,r,i){return cleanUrl(n.replace(t,r))+function(n){return!0===e.addQuery?""!==f?"".concat(f,"&retry=").concat(n):"?retry=".concat(n):"function"==typeof e.addQuery?e.addQuery({times:n,originalQuery:f}):""}(i+1)}(o,u,d,l),times:l+1,crossOrigin:e.crossOrigin,isAsync:m,originalQuery:f},g=createElement(i,y);if(e.onRetry&&"function"==typeof e.onRetry){var p={times:l,domain:u,url:o,tagName:a,isAsyncChunk:!1};e.onRetry(p)}reloadElementResource(i,g,y)}else if("function"==typeof e.onFail){var v={times:l,domain:u,url:o,tagName:a,isAsyncChunk:!1};e.onFail(v)}}}}}function load(e,n){var t=validateTargetInfo(e,n);if(!1!==t){var r=t.target,i=t.tagName,a=t.url,o=findCurrentDomain(a,e.domain),c=Number(r.dataset.rsbuildRetryTimes)||0;if(0!==c&&"function"==typeof e.onSuccess){var s={times:c,domain:o,url:a,tagName:i,isAsyncChunk:!1};e.onSuccess(s)}}}function resourceMonitor(e,n){"undefined"!=typeof window&&void 0!==window.document&&(document.addEventListener("error",(function(n){n&&n.target instanceof Element&&e(n)}),!0),document.addEventListener("load",(function(e){e&&e.target instanceof Element&&n(e)}),!0))}function init(e){var n={};for(var t in defaultConfig)n[t]=defaultConfig[t];for(var r in e)n[r]=e[r];Array.isArray(n.type)&&0!==n.type.length||(n.type=defaultConfig.type),Array.isArray(n.domain)&&0!==n.domain.length||(n.domain=defaultConfig.domain),Array.isArray(n.domain)&&(n.domain=n.domain.filter(Boolean)),"undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={});try{resourceMonitor((function(e){try{retry(n,e)}catch(e){console.error("retry error captured",e)}}),(function(e){try{load(n,e)}catch(e){console.error("load error captured",e)}}))}catch(e){console.error("monitor error captured",e)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/plugin-assets-retry",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "Assets retry plugin for Rsbuild",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "repository": {
@@ -26,12 +26,12 @@
26
26
  "@babel/core": "^7.26.0",
27
27
  "@babel/preset-env": "^7.26.0",
28
28
  "@babel/preset-typescript": "^7.26.0",
29
- "@rslib/core": "0.0.18",
29
+ "@rslib/core": "0.1.3",
30
30
  "@types/serialize-javascript": "^5.0.4",
31
31
  "serialize-javascript": "^6.0.2",
32
- "terser": "5.36.0",
33
- "typescript": "^5.6.3",
34
- "@rsbuild/core": "1.1.4"
32
+ "terser": "5.37.0",
33
+ "typescript": "^5.7.2",
34
+ "@rsbuild/core": "1.1.9"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@rsbuild/core": "1.x"