@rsbuild/plugin-assets-retry 1.1.1 → 1.2.0

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.js CHANGED
@@ -4,17 +4,23 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
6
6
  var __webpack_modules__ = {
7
- "../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
7
+ "./node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
8
8
  module.exports = __webpack_require__("crypto").randomBytes;
9
9
  },
10
- "../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
11
- var randomBytes = __webpack_require__("../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js"), UID = function() {
12
- for(var bytes = randomBytes(16), result = '', i = 0; i < 16; ++i)result += bytes[i].toString(16);
13
- return result;
14
- }(), PLACE_HOLDER_REGEXP = RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g'), IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g, IS_PURE_FUNCTION = /function.*?\(/, IS_ARROW_FUNCTION = /.*?=>.*?/, UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g, RESERVED_SYMBOLS = [
10
+ "./node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
11
+ var randomBytes = __webpack_require__("./node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js");
12
+ var UID_LENGTH = 16;
13
+ var UID = generateUID();
14
+ var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g');
15
+ var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
16
+ var IS_PURE_FUNCTION = /function.*?\(/;
17
+ var IS_ARROW_FUNCTION = /.*?=>.*?/;
18
+ var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
19
+ var RESERVED_SYMBOLS = [
15
20
  '*',
16
21
  'async'
17
- ], ESCAPED_CHARS = {
22
+ ];
23
+ var ESCAPED_CHARS = {
18
24
  '<': '\\u003C',
19
25
  '>': '\\u003E',
20
26
  '/': '\\u002F',
@@ -24,202 +30,312 @@ var __webpack_modules__ = {
24
30
  function escapeUnsafeChars(unsafeChar) {
25
31
  return ESCAPED_CHARS[unsafeChar];
26
32
  }
33
+ function generateUID() {
34
+ var bytes = randomBytes(UID_LENGTH);
35
+ var result = '';
36
+ for(var i = 0; i < UID_LENGTH; ++i)result += bytes[i].toString(16);
37
+ return result;
38
+ }
39
+ function deleteFunctions(obj) {
40
+ var functionKeys = [];
41
+ for(var key in obj)if ("function" == typeof obj[key]) functionKeys.push(key);
42
+ for(var i = 0; i < functionKeys.length; i++)delete obj[functionKeys[i]];
43
+ }
27
44
  module.exports = function serialize(obj, options) {
28
- options || (options = {}), ('number' == typeof options || 'string' == typeof options) && (options = {
45
+ options || (options = {});
46
+ if ('number' == typeof options || 'string' == typeof options) options = {
29
47
  space: options
30
- });
31
- var str, functions = [], regexps = [], dates = [], maps = [], sets = [], arrays = [], undefs = [], infinities = [], bigInts = [], urls = [];
32
- return (options.ignoreFunction && "function" == typeof obj && (obj = void 0), void 0 === obj) ? String(obj) : 'string' != typeof (str = options.isJSON && !options.space ? JSON.stringify(obj) : JSON.stringify(obj, options.isJSON ? null : function(key, value) {
33
- if (options.ignoreFunction && function(obj) {
34
- var functionKeys = [];
35
- for(var key in obj)"function" == typeof obj[key] && functionKeys.push(key);
36
- for(var i = 0; i < functionKeys.length; i++)delete obj[functionKeys[i]];
37
- }(value), !value && void 0 !== value && value !== BigInt(0)) return value;
38
- var origValue = this[key], type = typeof origValue;
48
+ };
49
+ var functions = [];
50
+ var regexps = [];
51
+ var dates = [];
52
+ var maps = [];
53
+ var sets = [];
54
+ var arrays = [];
55
+ var undefs = [];
56
+ var infinities = [];
57
+ var bigInts = [];
58
+ var urls = [];
59
+ function replacer(key, value) {
60
+ if (options.ignoreFunction) deleteFunctions(value);
61
+ if (!value && void 0 !== value && value !== BigInt(0)) return value;
62
+ var origValue = this[key];
63
+ var type = typeof origValue;
39
64
  if ('object' === type) {
40
65
  if (origValue instanceof RegExp) return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
41
66
  if (origValue instanceof Date) return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
42
67
  if (origValue instanceof Map) return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
43
68
  if (origValue instanceof Set) return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
44
- if (origValue instanceof Array && origValue.filter(function() {
45
- return !0;
46
- }).length !== origValue.length) return '@__A-' + UID + '-' + (arrays.push(origValue) - 1) + '__@';
69
+ if (origValue instanceof Array) {
70
+ var isSparse = origValue.filter(function() {
71
+ return true;
72
+ }).length !== origValue.length;
73
+ if (isSparse) return '@__A-' + UID + '-' + (arrays.push(origValue) - 1) + '__@';
74
+ }
47
75
  if (origValue instanceof URL) return '@__L-' + UID + '-' + (urls.push(origValue) - 1) + '__@';
48
76
  }
49
- return 'function' === type ? '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@' : 'undefined' === type ? '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@' : 'number' !== type || isNaN(origValue) || isFinite(origValue) ? 'bigint' === type ? '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@' : value : '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@';
50
- }, options.space)) ? String(str) : (!0 !== options.unsafe && (str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars)), 0 === functions.length && 0 === regexps.length && 0 === dates.length && 0 === maps.length && 0 === sets.length && 0 === arrays.length && 0 === undefs.length && 0 === infinities.length && 0 === bigInts.length && 0 === urls.length) ? str : str.replace(PLACE_HOLDER_REGEXP, function(match, backSlash, type, valueIndex) {
51
- return backSlash ? match : 'D' === type ? "new Date(\"" + dates[valueIndex].toISOString() + "\")" : 'R' === type ? "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")" : 'M' === type ? "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")" : 'S' === type ? "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")" : 'A' === type ? "Array.prototype.slice.call(" + serialize(Object.assign({
77
+ if ('function' === type) return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
78
+ if ('undefined' === type) return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
79
+ if ('number' === type && !isNaN(origValue) && !isFinite(origValue)) return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@';
80
+ if ('bigint' === type) return '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@';
81
+ return value;
82
+ }
83
+ function serializeFunc(fn) {
84
+ var serializedFn = fn.toString();
85
+ if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) throw new TypeError('Serializing native function: ' + fn.name);
86
+ if (IS_PURE_FUNCTION.test(serializedFn)) return serializedFn;
87
+ if (IS_ARROW_FUNCTION.test(serializedFn)) return serializedFn;
88
+ var argsStartsAt = serializedFn.indexOf('(');
89
+ var def = serializedFn.substr(0, argsStartsAt).trim().split(' ').filter(function(val) {
90
+ return val.length > 0;
91
+ });
92
+ var nonReservedSymbols = def.filter(function(val) {
93
+ return -1 === RESERVED_SYMBOLS.indexOf(val);
94
+ });
95
+ if (nonReservedSymbols.length > 0) return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + (def.join('').indexOf('*') > -1 ? '*' : '') + serializedFn.substr(argsStartsAt);
96
+ return serializedFn;
97
+ }
98
+ if (options.ignoreFunction && "function" == typeof obj) obj = void 0;
99
+ if (void 0 === obj) return String(obj);
100
+ var str;
101
+ str = options.isJSON && !options.space ? JSON.stringify(obj) : JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
102
+ if ('string' != typeof str) return String(str);
103
+ if (true !== options.unsafe) str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
104
+ if (0 === functions.length && 0 === regexps.length && 0 === dates.length && 0 === maps.length && 0 === sets.length && 0 === arrays.length && 0 === undefs.length && 0 === infinities.length && 0 === bigInts.length && 0 === urls.length) return str;
105
+ return str.replace(PLACE_HOLDER_REGEXP, function(match, backSlash, type, valueIndex) {
106
+ if (backSlash) return match;
107
+ if ('D' === type) return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
108
+ if ('R' === type) return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
109
+ if ('M' === type) return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
110
+ if ('S' === type) return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
111
+ if ('A' === type) return "Array.prototype.slice.call(" + serialize(Object.assign({
52
112
  length: arrays[valueIndex].length
53
- }, arrays[valueIndex]), options) + ")" : 'U' === type ? 'undefined' : 'I' === type ? infinities[valueIndex] : 'B' === type ? "BigInt(\"" + bigInts[valueIndex] + "\")" : 'L' === type ? "new URL(" + serialize(urls[valueIndex].toString(), options) + ")" : function(fn) {
54
- var serializedFn = fn.toString();
55
- if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) throw TypeError('Serializing native function: ' + fn.name);
56
- if (IS_PURE_FUNCTION.test(serializedFn) || IS_ARROW_FUNCTION.test(serializedFn)) return serializedFn;
57
- var argsStartsAt = serializedFn.indexOf('('), def = serializedFn.substr(0, argsStartsAt).trim().split(' ').filter(function(val) {
58
- return val.length > 0;
59
- });
60
- return def.filter(function(val) {
61
- return -1 === RESERVED_SYMBOLS.indexOf(val);
62
- }).length > 0 ? (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + (def.join('').indexOf('*') > -1 ? '*' : '') + serializedFn.substr(argsStartsAt) : serializedFn;
63
- }(functions[valueIndex]);
113
+ }, arrays[valueIndex]), options) + ")";
114
+ if ('U' === type) return 'undefined';
115
+ if ('I' === type) return infinities[valueIndex];
116
+ if ('B' === type) return "BigInt(\"" + bigInts[valueIndex] + "\")";
117
+ if ('L' === type) return "new URL(" + serialize(urls[valueIndex].toString(), options) + ")";
118
+ var fn = functions[valueIndex];
119
+ return serializeFunc(fn);
64
120
  });
65
121
  };
66
122
  },
67
123
  crypto: function(module) {
68
124
  module.exports = __WEBPACK_EXTERNAL_MODULE_crypto__;
69
125
  }
70
- }, __webpack_module_cache__ = {};
126
+ };
127
+ var __webpack_module_cache__ = {};
71
128
  function __webpack_require__(moduleId) {
72
129
  var cachedModule = __webpack_module_cache__[moduleId];
73
130
  if (void 0 !== cachedModule) return cachedModule.exports;
74
131
  var module = __webpack_module_cache__[moduleId] = {
75
132
  exports: {}
76
133
  };
77
- return __webpack_modules__[moduleId](module, module.exports, __webpack_require__), module.exports;
134
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
135
+ return module.exports;
78
136
  }
79
- __webpack_require__.n = function(module) {
80
- var getter = module && module.__esModule ? function() {
81
- return module.default;
82
- } : function() {
83
- return module;
137
+ (()=>{
138
+ __webpack_require__.n = function(module) {
139
+ var getter = module && module.__esModule ? function() {
140
+ return module['default'];
141
+ } : function() {
142
+ return module;
143
+ };
144
+ __webpack_require__.d(getter, {
145
+ a: getter
146
+ });
147
+ return getter;
84
148
  };
85
- return __webpack_require__.d(getter, {
86
- a: getter
87
- }), getter;
88
- }, __webpack_require__.d = function(exports, definition) {
89
- for(var key in definition)__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key) && Object.defineProperty(exports, key, {
90
- enumerable: !0,
91
- get: definition[key]
92
- });
93
- }, __webpack_require__.o = function(obj, prop) {
94
- return Object.prototype.hasOwnProperty.call(obj, prop);
95
- };
96
- var serialize_javascript = __webpack_require__("../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js"), serialize_javascript_default = __webpack_require__.n(serialize_javascript);
149
+ })();
150
+ (()=>{
151
+ __webpack_require__.d = function(exports, definition) {
152
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
153
+ enumerable: true,
154
+ get: definition[key]
155
+ });
156
+ };
157
+ })();
158
+ (()=>{
159
+ __webpack_require__.o = function(obj, prop) {
160
+ return Object.prototype.hasOwnProperty.call(obj, prop);
161
+ };
162
+ })();
163
+ var serialize_javascript = __webpack_require__("./node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js");
164
+ var serialize_javascript_default = /*#__PURE__*/ __webpack_require__.n(serialize_javascript);
97
165
  function _define_property(obj, key, value) {
98
- return key in obj ? Object.defineProperty(obj, key, {
166
+ if (key in obj) Object.defineProperty(obj, key, {
99
167
  value: value,
100
- enumerable: !0,
101
- configurable: !0,
102
- writable: !0
103
- }) : obj[key] = value, obj;
168
+ enumerable: true,
169
+ configurable: true,
170
+ writable: true
171
+ });
172
+ else obj[key] = value;
173
+ return obj;
174
+ }
175
+ const AsyncChunkRetryPlugin_dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(import.meta.url));
176
+ function modifyWebpackRuntimeModule(module, modifier) {
177
+ try {
178
+ const originSource = module.getGeneratedCode();
179
+ module.getGeneratedCode = ()=>modifier(originSource);
180
+ } catch (err) {
181
+ console.error('Failed to modify webpack RuntimeModule');
182
+ throw err;
183
+ }
184
+ }
185
+ function modifyRspackRuntimeModule(module, modifier) {
186
+ try {
187
+ const originSource = module.source.source.toString();
188
+ module.source.source = Buffer.from(modifier(originSource), 'utf-8');
189
+ } catch (err) {
190
+ console.error('Failed to modify Rspack RuntimeModule');
191
+ throw err;
192
+ }
104
193
  }
105
- let AsyncChunkRetryPlugin_dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(import.meta.url));
106
194
  function modifyRuntimeModule(module, modifier, isRspack) {
107
- isRspack ? function(module, modifier) {
108
- try {
109
- let originSource = module.source.source.toString();
110
- module.source.source = Buffer.from(modifier(originSource), 'utf-8');
111
- } catch (err) {
112
- throw console.error('Failed to modify Rspack RuntimeModule'), err;
113
- }
114
- }(module, modifier) : function(module, modifier) {
115
- try {
116
- let originSource = module.getGeneratedCode();
117
- module.getGeneratedCode = ()=>modifier(originSource);
118
- } catch (err) {
119
- throw console.error('Failed to modify webpack RuntimeModule'), err;
120
- }
121
- }(module, modifier);
195
+ if (isRspack) modifyRspackRuntimeModule(module, modifier);
196
+ else modifyWebpackRuntimeModule(module, modifier);
197
+ }
198
+ function pick(obj, keys) {
199
+ return keys.reduce((ret, key)=>{
200
+ if (void 0 !== obj[key]) ret[key] = obj[key];
201
+ return ret;
202
+ }, {});
122
203
  }
123
204
  class AsyncChunkRetryPlugin {
124
205
  getRawRuntimeRetryCode() {
125
- let { RuntimeGlobals } = __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.rspack, filename = 'asyncChunkRetry', runtimeFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(AsyncChunkRetryPlugin_dirname, 'runtime', this.options.minify ? `${filename}.min.js` : `${filename}.js`);
126
- return __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.default.readFileSync(runtimeFilePath, 'utf-8').replaceAll('__RUNTIME_GLOBALS_REQUIRE__', RuntimeGlobals.require).replaceAll('__RUNTIME_GLOBALS_ENSURE_CHUNK__', RuntimeGlobals.ensureChunk).replaceAll('__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__', RuntimeGlobals.getChunkScriptFilename).replaceAll('__RUNTIME_GLOBALS_GET_CSS_FILENAME__', RuntimeGlobals.getChunkCssFilename).replaceAll('__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__', '__webpack_require__.miniCssF').replaceAll('__RUNTIME_GLOBALS_RSBUILD_LOAD_STYLESHEET__', '__webpack_require__.rbLoadStyleSheet').replaceAll('__RUNTIME_GLOBALS_PUBLIC_PATH__', RuntimeGlobals.publicPath).replaceAll('__RUNTIME_GLOBALS_LOAD_SCRIPT__', RuntimeGlobals.loadScript).replaceAll('__RETRY_OPTIONS__', serialize_javascript_default()(this.runtimeOptions));
206
+ const { RuntimeGlobals } = __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.rspack;
207
+ const filename = 'asyncChunkRetry';
208
+ const runtimeFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(AsyncChunkRetryPlugin_dirname, 'runtime', this.options.minify ? `${filename}.min.js` : `${filename}.js`);
209
+ const rawText = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(runtimeFilePath, 'utf-8');
210
+ return rawText.replaceAll('__RUNTIME_GLOBALS_REQUIRE__', RuntimeGlobals.require).replaceAll('__RUNTIME_GLOBALS_ENSURE_CHUNK__', RuntimeGlobals.ensureChunk).replaceAll('__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__', RuntimeGlobals.getChunkScriptFilename).replaceAll('__RUNTIME_GLOBALS_GET_CSS_FILENAME__', RuntimeGlobals.getChunkCssFilename).replaceAll('__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__', '__webpack_require__.miniCssF').replaceAll('__RUNTIME_GLOBALS_RSBUILD_LOAD_STYLESHEET__', '__webpack_require__.rbLoadStyleSheet').replaceAll('__RUNTIME_GLOBALS_PUBLIC_PATH__', RuntimeGlobals.publicPath).replaceAll('__RUNTIME_GLOBALS_LOAD_SCRIPT__', RuntimeGlobals.loadScript).replaceAll('__RETRY_OPTIONS__', serialize_javascript_default()(this.runtimeOptions));
127
211
  }
128
212
  apply(compiler) {
129
213
  compiler.hooks.thisCompilation.tap(this.name, (compilation)=>{
130
214
  compilation.hooks.runtimeModule.tap(this.name, (module)=>{
131
215
  var _module_constructor;
132
- let { isRspack } = this.options, constructorName = isRspack ? module.constructorName : null === (_module_constructor = module.constructor) || void 0 === _module_constructor ? void 0 : _module_constructor.name;
133
- if ('CssLoadingRuntimeModule' === constructorName) {
216
+ const { isRspack } = this.options;
217
+ const constructorName = isRspack ? module.constructorName : null === (_module_constructor = module.constructor) || void 0 === _module_constructor ? void 0 : _module_constructor.name;
218
+ const isCssLoadingRuntimeModule = 'CssLoadingRuntimeModule' === constructorName;
219
+ if (isCssLoadingRuntimeModule) {
134
220
  modifyRuntimeModule(module, (originSource)=>originSource.replace('var fullhref = __webpack_require__.p + href;', 'var fullhref = __webpack_require__.rbLoadStyleSheet ? __webpack_require__.rbLoadStyleSheet(href, chunkId) : (__webpack_require__.p + href);'), isRspack);
135
221
  return;
136
222
  }
137
- if ('publicPath' === module.name || 'PublicPathRuntimeModule' === constructorName || 'AutoPublicPathRuntimeModule' === constructorName) {
138
- let runtimeCode = this.getRawRuntimeRetryCode();
223
+ const isPublicPathModule = 'publicPath' === module.name || 'PublicPathRuntimeModule' === constructorName || 'AutoPublicPathRuntimeModule' === constructorName;
224
+ if (isPublicPathModule) {
225
+ const runtimeCode = this.getRawRuntimeRetryCode();
139
226
  modifyRuntimeModule(module, (originSource)=>`${originSource}\n${runtimeCode}`, isRspack);
140
227
  }
141
228
  });
142
229
  });
143
230
  }
144
231
  constructor(options){
145
- _define_property(this, "name", 'ASYNC_CHUNK_RETRY_PLUGIN'), _define_property(this, "options", void 0), _define_property(this, "runtimeOptions", void 0), this.options = options, this.runtimeOptions = [
232
+ _define_property(this, "name", 'ASYNC_CHUNK_RETRY_PLUGIN');
233
+ _define_property(this, "options", void 0);
234
+ _define_property(this, "runtimeOptions", void 0);
235
+ this.options = options;
236
+ this.runtimeOptions = pick(options, [
146
237
  'domain',
147
238
  'max',
148
239
  'onRetry',
149
240
  'onSuccess',
150
241
  'onFail',
151
242
  'addQuery',
152
- 'test'
153
- ].reduce((ret, key)=>(void 0 !== options[key] && (ret[key] = options[key]), ret), {});
243
+ 'test',
244
+ 'delay'
245
+ ]);
154
246
  }
155
247
  }
156
- let src_dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(import.meta.url)), PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
248
+ const src_dirname = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(import.meta.url));
249
+ const PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
250
+ function getRuntimeOptions(userOptions) {
251
+ const defaultOptions = {
252
+ max: 3,
253
+ type: [
254
+ 'link',
255
+ "script",
256
+ 'img'
257
+ ],
258
+ domain: [],
259
+ crossOrigin: false,
260
+ delay: 0
261
+ };
262
+ const result = {
263
+ ...defaultOptions,
264
+ ...userOptions
265
+ };
266
+ if (!Array.isArray(result.type) || 0 === result.type.length) result.type = defaultOptions.type;
267
+ if (!Array.isArray(result.domain) || 0 === result.domain.length) result.domain = defaultOptions.domain;
268
+ if (Array.isArray(result.domain)) result.domain = result.domain.filter(Boolean);
269
+ return result;
270
+ }
157
271
  async function getRetryCode(options) {
158
- let filename = 'initialChunkRetry', { minify, inlineScript: _, ...restOptions } = options, runtimeFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(src_dirname, 'runtime', minify ? `${filename}.min.js` : `${filename}.js`), runtimeCode = await __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.default.promises.readFile(runtimeFilePath, 'utf-8'), runtimeOptions = function(userOptions) {
159
- let defaultOptions = {
160
- max: 3,
161
- type: [
162
- 'link',
163
- "script",
164
- 'img'
165
- ],
166
- domain: [],
167
- crossOrigin: !1
168
- }, result = {
169
- ...defaultOptions,
170
- ...userOptions
171
- };
172
- return Array.isArray(result.type) && 0 !== result.type.length || (result.type = defaultOptions.type), Array.isArray(result.domain) && 0 !== result.domain.length || (result.domain = defaultOptions.domain), Array.isArray(result.domain) && (result.domain = result.domain.filter(Boolean)), result;
173
- }(restOptions);
272
+ const filename = 'initialChunkRetry';
273
+ const { minify, inlineScript: _, ...restOptions } = options;
274
+ const runtimeFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(src_dirname, 'runtime', minify ? `${filename}.min.js` : `${filename}.js`);
275
+ const runtimeCode = await __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].promises.readFile(runtimeFilePath, 'utf-8');
276
+ const runtimeOptions = getRuntimeOptions(restOptions);
174
277
  return `(function(){${runtimeCode}})()`.replace('__RUNTIME_GLOBALS_OPTIONS__', serialize_javascript_default()(runtimeOptions));
175
278
  }
176
- let pluginAssetsRetry = (userOptions = {})=>({
279
+ const pluginAssetsRetry = (userOptions = {})=>({
177
280
  name: PLUGIN_ASSETS_RETRY_NAME,
178
281
  setup (api) {
179
- let { inlineScript = !0 } = userOptions, getScriptPath = (environment)=>{
180
- let distDir = environment.config.output.distPath.js;
181
- return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.posix.join(distDir, "assets-retry.1-1-1.js");
182
- }, formatOptions = (config)=>{
183
- let options = {
282
+ const { inlineScript = true } = userOptions;
283
+ const getScriptPath = (environment)=>{
284
+ const distDir = environment.config.output.distPath.js;
285
+ return __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].posix.join(distDir, "assets-retry.1-2-0.js");
286
+ };
287
+ const formatOptions = (config)=>{
288
+ const options = {
184
289
  ...userOptions
185
290
  };
186
- if (void 0 === options.crossOrigin && (options.crossOrigin = config.html.crossorigin), void 0 === options.minify) {
291
+ if (void 0 === options.crossOrigin) options.crossOrigin = config.html.crossorigin;
292
+ if (void 0 === options.minify) {
187
293
  var _config_output_minify;
188
- let minify = 'boolean' == typeof config.output.minify ? config.output.minify : null === (_config_output_minify = config.output.minify) || void 0 === _config_output_minify ? void 0 : _config_output_minify.js;
294
+ const minify = 'boolean' == typeof config.output.minify ? config.output.minify : null === (_config_output_minify = config.output.minify) || void 0 === _config_output_minify ? void 0 : _config_output_minify.js;
189
295
  options.minify = minify && 'production' === config.mode;
190
296
  }
191
297
  return options;
192
298
  };
193
- inlineScript ? api.modifyHTMLTags(async ({ headTags, bodyTags }, { environment })=>{
194
- let code = await getRetryCode(formatOptions(environment.config));
195
- return headTags.unshift({
299
+ if (inlineScript) api.modifyHTMLTags(async ({ headTags, bodyTags }, { environment })=>{
300
+ const code = await getRetryCode(formatOptions(environment.config));
301
+ headTags.unshift({
196
302
  tag: "script",
197
303
  attrs: {},
198
304
  children: code
199
- }), {
305
+ });
306
+ return {
200
307
  headTags,
201
308
  bodyTags
202
309
  };
203
- }) : (api.modifyHTMLTags(async ({ headTags, bodyTags }, { assetPrefix, environment })=>{
204
- let scriptPath = getScriptPath(environment), url = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.ensureAssetPrefix)(scriptPath, assetPrefix);
205
- return headTags.unshift({
206
- tag: "script",
207
- attrs: {
208
- src: url
209
- }
210
- }), {
211
- headTags,
212
- bodyTags
213
- };
214
- }), api.processAssets({
215
- stage: 'additional'
216
- }, async ({ sources, compilation, environment })=>{
217
- let scriptPath = getScriptPath(environment), code = await getRetryCode(formatOptions(environment.config));
218
- compilation.emitAsset(scriptPath, new sources.RawSource(code));
219
- })), api.modifyBundlerChain(async (chain, { environment })=>{
220
- let { config, htmlPaths } = environment;
310
+ });
311
+ else {
312
+ api.modifyHTMLTags(async ({ headTags, bodyTags }, { assetPrefix, environment })=>{
313
+ const scriptPath = getScriptPath(environment);
314
+ const url = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.ensureAssetPrefix)(scriptPath, assetPrefix);
315
+ headTags.unshift({
316
+ tag: "script",
317
+ attrs: {
318
+ src: url
319
+ }
320
+ });
321
+ return {
322
+ headTags,
323
+ bodyTags
324
+ };
325
+ });
326
+ api.processAssets({
327
+ stage: 'additional'
328
+ }, async ({ sources, compilation, environment })=>{
329
+ const scriptPath = getScriptPath(environment);
330
+ const code = await getRetryCode(formatOptions(environment.config));
331
+ compilation.emitAsset(scriptPath, new sources.RawSource(code));
332
+ });
333
+ }
334
+ api.modifyBundlerChain(async (chain, { environment })=>{
335
+ const { config, htmlPaths } = environment;
221
336
  if (!userOptions || 0 === Object.keys(htmlPaths).length) return;
222
- let options = formatOptions(config), isRspack = 'rspack' === api.context.bundlerType;
337
+ const options = formatOptions(config);
338
+ const isRspack = 'rspack' === api.context.bundlerType;
223
339
  chain.plugin('async-chunk-retry').use(AsyncChunkRetryPlugin, [
224
340
  {
225
341
  ...options,
@@ -206,8 +206,14 @@ function ensureChunk(chunkId) {
206
206
  if (typeof config.onRetry === 'function') {
207
207
  config.onRetry(context);
208
208
  }
209
- var nextPromise = ensureChunk.apply(ensureChunk, args);
210
- return nextPromise.then(function(result) {
209
+ var _config_delay;
210
+ var delayTime = typeof config.delay === 'function' ? config.delay(context) : (_config_delay = config.delay) !== null && _config_delay !== void 0 ? _config_delay : 0;
211
+ var delayPromise = delayTime > 0 ? new Promise(function(resolve) {
212
+ return setTimeout(resolve, delayTime);
213
+ }) : Promise.resolve();
214
+ return delayPromise.then(function() {
215
+ return ensureChunk.apply(ensureChunk, args);
216
+ }).then(function(result) {
211
217
  // when after retrying the third time
212
218
  // ensureChunk(chunkId, { count: 3 }), at that time, existRetryTimes === 2
213
219
  // at the end, callingCounter.count is 4
@@ -1 +1 @@
1
- var n=__RETRY_OPTIONS__,r=n.max||3,e={},i={},t=/[?#].*$/;function o(r,e,i,o,_){var a;return r.replace(e,i).replace(t,"")+(a=o+1,!0===n.addQuery?""!==_?"".concat(_,"&retry=").concat(a):"?retry=".concat(a):"function"==typeof n.addQuery?n.addQuery({times:a,originalQuery:_}):"")}var _={},a={},c=__RUNTIME_GLOBALS_ENSURE_CHUNK__,l=__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__,u=__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__||__RUNTIME_GLOBALS_GET_CSS_FILENAME__||function(){return null},d=__RUNTIME_GLOBALS_LOAD_SCRIPT__,s="[@rsbuild/plugin-assets-retry] ";function f(t){var d=Array.prototype.slice.call(arguments);d[10]||(d[10]={count:0,cssFailedCount:0});var S=d[10],y=c.apply(null,d);try{var R=l(t),p=u(t);"undefined"!=typeof window&&(R&&(window.__RB_ASYNC_CHUNKS__[R]=!0),p&&(window.__RB_ASYNC_CHUNKS__[p]=!0))}catch(n){console.error(s,"get original script or CSS filename error",n)}return S&&"number"==typeof S.count&&"number"==typeof S.cssFailedCount?(S.count+=1,y.catch(function(c){var y,R,p,v,E,U=S.count-1,L=S.cssFailedCount,g=!!(null==c?void 0:null===(y=c.message)||void 0===y?void 0:y.includes("CSS chunk"));g&&(S.cssFailedCount+=1);var N=g?L:U-L;try{var m=function(r,t,c){var d,s,f,S=c?null===(d=i[r])||void 0===d?void 0:d[t]:null===(s=e[r])||void 0===s?void 0:s[t],y=t+1;if(0===t||void 0===S)f=function(r,e){var i,t,_=e?u(r):l(r);if(!_)throw Error("only support cssExtract");var a=__RUNTIME_GLOBALS_PUBLIC_PATH__,c=a.startsWith("/")?window.origin+a+_:a+_,d=(i=c.split("?")[1])?"?".concat(i.split("#")[0]):"",s=(null===(t=n.domain)||void 0===t?void 0:t[0])||window.origin;return{nextDomain:s,nextRetryUrl:o(c,s,s,0,d),originalScriptFilename:_,originalSrcUrl:c,originalQuery:d}}(r,c),c?i[r]=[]:e[r]=[];else{var R,p,v,E,U=S.originalScriptFilename,L=S.originalSrcUrl,g=S.originalQuery,N=(R=S.nextDomain,p=n.domain||[],v=function(r){for(var e=n.domain||[],i="",t=0;t<e.length;t++)if(-1!==r.indexOf(e[t])){i=e[t];break}return i||window.origin}(R),E=p.indexOf(v),p[(E+1)%p.length]||R);f={nextDomain:N,nextRetryUrl:o(S.nextRetryUrl,S.nextDomain,N,t,g),originalScriptFilename:U,originalSrcUrl:L,originalQuery:g}}return c?(i[r][y]=f,a[r]=f):(e[r][y]=f,_[r]=f),f}(t,N,g);R=m.originalScriptFilename,p=m.nextRetryUrl,v=m.nextDomain}catch(n){throw console.error(s,"failed to get nextRetryUrl",n),c}var A=function(n){return{times:n,domain:v,url:p,tagName:g?"link":"script",isAsyncChunk:!0}},C=A(N);if(N>=r)throw c.message=(null===(E=c.message)||void 0===E?void 0:E.includes("retries:"))?c.message:"Loading chunk ".concat(t,' from "').concat(R,'" failed after ').concat(r,' retries: "').concat(c.message,'"'),"function"==typeof n.onFail&&n.onFail(C),c;var T=n.test;if(T){if("string"==typeof T){var w=new RegExp(T);T=function(n){return w.test(n)}}if("function"!=typeof T||!T(p))throw c}if(n.domain&&-1===n.domain.indexOf(v))throw c;return"function"==typeof n.onRetry&&n.onRetry(C),f.apply(f,d).then(function(r){var e=(null==S?void 0:S.count)===U+2;if("function"==typeof n.onSuccess&&e){var i=A(N+1);n.onSuccess(i)}return r})})):y}function S(){var n=Array.prototype.slice.call(arguments),r=_[n[3]];return r&&(n[0]=r.nextRetryUrl),d.apply(null,n)}function y(n,r){var e=a[r];return e&&e.nextRetryUrl||__RUNTIME_GLOBALS_PUBLIC_PATH__+n}!function(){if("undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={}),"undefined"!=typeof __RUNTIME_GLOBALS_REQUIRE__)try{__RUNTIME_GLOBALS_ENSURE_CHUNK__=f,__RUNTIME_GLOBALS_LOAD_SCRIPT__=S,__RUNTIME_GLOBALS_RSBUILD_LOAD_STYLESHEET__=y}catch(n){console.error(s,"Register async chunk retry runtime failed",n)}}();
1
+ var n=__RETRY_OPTIONS__,r=n.max||3,e={},i={},t=/[?#].*$/;function o(r,e,i,o,_){var a;return r.replace(e,i).replace(t,"")+(a=o+1,!0===n.addQuery?""!==_?"".concat(_,"&retry=").concat(a):"?retry=".concat(a):"function"==typeof n.addQuery?n.addQuery({times:a,originalQuery:_}):"")}var _={},a={},l=__RUNTIME_GLOBALS_ENSURE_CHUNK__,c=__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__,u=__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__||__RUNTIME_GLOBALS_GET_CSS_FILENAME__||function(){return null},d=__RUNTIME_GLOBALS_LOAD_SCRIPT__,s="[@rsbuild/plugin-assets-retry] ";function f(t){var d=Array.prototype.slice.call(arguments);d[10]||(d[10]={count:0,cssFailedCount:0});var y=d[10],S=l.apply(null,d);try{var v=c(t),R=u(t);"undefined"!=typeof window&&(v&&(window.__RB_ASYNC_CHUNKS__[v]=!0),R&&(window.__RB_ASYNC_CHUNKS__[R]=!0))}catch(n){console.error(s,"get original script or CSS filename error",n)}return y&&"number"==typeof y.count&&"number"==typeof y.cssFailedCount?(y.count+=1,S.catch(function(l){var S,v,R,p,E,U,L=y.count-1,m=y.cssFailedCount,g=!!(null==l?void 0:null===(S=l.message)||void 0===S?void 0:S.includes("CSS chunk"));g&&(y.cssFailedCount+=1);var N=g?m:L-m;try{var A=function(r,t,l){var d,s,f,y=l?null===(d=i[r])||void 0===d?void 0:d[t]:null===(s=e[r])||void 0===s?void 0:s[t],S=t+1;if(0===t||void 0===y)f=function(r,e){var i,t,_=e?u(r):c(r);if(!_)throw Error("only support cssExtract");var a=__RUNTIME_GLOBALS_PUBLIC_PATH__,l=a.startsWith("/")?window.origin+a+_:a+_,d=(i=l.split("?")[1])?"?".concat(i.split("#")[0]):"",s=(null===(t=n.domain)||void 0===t?void 0:t[0])||window.origin;return{nextDomain:s,nextRetryUrl:o(l,s,s,0,d),originalScriptFilename:_,originalSrcUrl:l,originalQuery:d}}(r,l),l?i[r]=[]:e[r]=[];else{var v,R,p,E,U=y.originalScriptFilename,L=y.originalSrcUrl,m=y.originalQuery,g=(v=y.nextDomain,R=n.domain||[],p=function(r){for(var e=n.domain||[],i="",t=0;t<e.length;t++)if(-1!==r.indexOf(e[t])){i=e[t];break}return i||window.origin}(v),E=R.indexOf(p),R[(E+1)%R.length]||v);f={nextDomain:g,nextRetryUrl:o(y.nextRetryUrl,y.nextDomain,g,t,m),originalScriptFilename:U,originalSrcUrl:L,originalQuery:m}}return l?(i[r][S]=f,a[r]=f):(e[r][S]=f,_[r]=f),f}(t,N,g);v=A.originalScriptFilename,R=A.nextRetryUrl,p=A.nextDomain}catch(n){throw console.error(s,"failed to get nextRetryUrl",n),l}var C=function(n){return{times:n,domain:p,url:R,tagName:g?"link":"script",isAsyncChunk:!0}},T=C(N);if(N>=r)throw l.message=(null===(E=l.message)||void 0===E?void 0:E.includes("retries:"))?l.message:"Loading chunk ".concat(t,' from "').concat(v,'" failed after ').concat(r,' retries: "').concat(l.message,'"'),"function"==typeof n.onFail&&n.onFail(T),l;var w=n.test;if(w){if("string"==typeof w){var I=new RegExp(w);w=function(n){return I.test(n)}}if("function"!=typeof w||!w(R))throw l}if(n.domain&&-1===n.domain.indexOf(p))throw l;"function"==typeof n.onRetry&&n.onRetry(T);var O="function"==typeof n.delay?n.delay(T):null!==(U=n.delay)&&void 0!==U?U:0;return(O>0?new Promise(function(n){return setTimeout(n,O)}):Promise.resolve()).then(function(){return f.apply(f,d)}).then(function(r){var e=(null==y?void 0:y.count)===L+2;if("function"==typeof n.onSuccess&&e){var i=C(N+1);n.onSuccess(i)}return r})})):S}function y(){var n=Array.prototype.slice.call(arguments),r=_[n[3]];return r&&(n[0]=r.nextRetryUrl),d.apply(null,n)}function S(n,r){var e=a[r];return e&&e.nextRetryUrl||__RUNTIME_GLOBALS_PUBLIC_PATH__+n}!function(){if("undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={}),"undefined"!=typeof __RUNTIME_GLOBALS_REQUIRE__)try{__RUNTIME_GLOBALS_ENSURE_CHUNK__=f,__RUNTIME_GLOBALS_LOAD_SCRIPT__=y,__RUNTIME_GLOBALS_RSBUILD_LOAD_STYLESHEET__=S}catch(n){console.error(s,"Register async chunk retry runtime failed",n)}}();
@@ -200,17 +200,26 @@ function retry(config, e) {
200
200
  originalQuery: originalQuery
201
201
  };
202
202
  var element = createElement(target, attributes);
203
+ var context1 = {
204
+ times: existRetryTimes,
205
+ domain: domain,
206
+ url: url,
207
+ tagName: tagName,
208
+ isAsyncChunk: false
209
+ };
203
210
  if (typeof config.onRetry === 'function') {
204
- var context1 = {
205
- times: existRetryTimes,
206
- domain: domain,
207
- url: url,
208
- tagName: tagName,
209
- isAsyncChunk: false
210
- };
211
211
  config.onRetry(context1);
212
212
  }
213
- reloadElementResource(target, element, attributes);
213
+ var _config_delay;
214
+ // Delay retry
215
+ var delayValue = typeof config.delay === 'function' ? config.delay(context1) : (_config_delay = config.delay) !== null && _config_delay !== void 0 ? _config_delay : 0;
216
+ if (delayValue > 0) {
217
+ setTimeout(function() {
218
+ reloadElementResource(target, element, attributes);
219
+ }, delayValue);
220
+ } else {
221
+ reloadElementResource(target, element, attributes);
222
+ }
214
223
  }
215
224
  function load(config, e) {
216
225
  var targetInfo = validateTargetInfo(config, e);
@@ -1 +1 @@
1
- function e(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t}var t={link:HTMLLinkElement,script:HTMLScriptElement,img:HTMLImageElement};function n(e,t){for(var n="",r=0;r<t.length;r++)if(-1!==e.indexOf(t[r])){n=t[r];break}return n||window.origin}function r(n,r){var i=r.target,a=i.tagName.toLocaleLowerCase(),o=n.type,c=e(i,HTMLScriptElement)||e(i,HTMLImageElement)?i.src:e(i,HTMLLinkElement)?i.href:null;return!!(a&&-1!==o.indexOf(a)&&t[a]&&e(i,t[a]))&&!!c&&{target:i,tagName:a,url:c}}var i=/[?#].*$/;"undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={});try{var a,o,c=__RUNTIME_GLOBALS_OPTIONS__;a=function(t){try{!function(t,a){var o,c,s,l,u,d,m=r(t,a);if(!1!==m){var y=m.target,f=m.tagName,g=m.url;if(!("undefined"!=typeof window&&Object.keys(window.__RB_ASYNC_CHUNKS__||{}).some(function(e){return -1!==g.indexOf(e)}))){var p=t.test;if(p){if("string"==typeof p){var _=new RegExp(p);p=function(e){return _.test(e)}}if("function"!=typeof p||!p(g))return}var v=n(g,t.domain);if(!t.domain||!(t.domain.length>0)||-1!==t.domain.indexOf(v)){var b=Number(y.dataset.rbRetryTimes)||0;if(b===t.max){"function"==typeof t.onFail&&t.onFail({times:b,domain:v,url:g,tagName:f,isAsyncChunk:!1});return}var L=(c=n(v,o=t.domain),s=o.indexOf(c),o[(s+1)%o.length]||v),S=null!==(d=y.dataset.rbOriginalQuery)&&void 0!==d?d:(l=g.split("?")[1])?"?".concat(l.split("#")[0]):"",E=!!y.dataset.rbAsync||y.async||y.defer,w={url:g.replace(v,L).replace(i,"")+(u=b+1,!0===t.addQuery?""!==S?"".concat(S,"&retry=").concat(u):"?retry=".concat(u):"function"==typeof t.addQuery?t.addQuery({times:u,originalQuery:S}):""),times:b+1,crossOrigin:t.crossOrigin,isAsync:E,originalQuery:S},O=function(t,n){var r=!0===n.crossOrigin?"anonymous":n.crossOrigin,i=r?'crossorigin="'.concat(r,'"'):"",a=n.times?'data-rb-retry-times="'.concat(n.times,'"'):"",o=n.originalQuery?'data-rb-original-query="'.concat(n.originalQuery,'"'):"",c=n.isAsync?"data-rb-async":"";if(e(t,HTMLScriptElement)){var s=document.createElement("script");return s.src=n.url,r&&(s.crossOrigin=r),n.times&&(s.dataset.rbRetryTimes=String(n.times)),n.isAsync&&(s.dataset.rbAsync=""),void 0!==n.originalQuery&&(s.dataset.rbOriginalQuery=n.originalQuery),{element:s,str:'<script src="'.concat(n.url,'" ').concat(i," ").concat(a," ").concat(c," ").concat(o,">")+"<\/script>"}}if(e(t,HTMLLinkElement)){var l=document.createElement("link");return l.rel=t.rel||"stylesheet",t.as&&(l.as=t.as),l.href=n.url,r&&(l.crossOrigin=r),n.times&&(l.dataset.rbRetryTimes=String(n.times)),void 0!==n.originalQuery&&(l.dataset.rbOriginalQuery=n.originalQuery),{element:l,str:'<link rel="'.concat(l.rel,'" href="').concat(n.url,'" ').concat(i," ").concat(a," ").concat(l.as?'as="'.concat(l.as,'"'):""," ").concat(o,"></link>")}}}(y,w);"function"==typeof t.onRetry&&t.onRetry({times:b,domain:v,url:g,tagName:f,isAsyncChunk:!1}),e(y,HTMLScriptElement)&&(w.isAsync?document.body.appendChild(O.element):document.write(O.str)),e(y,HTMLLinkElement)&&document.getElementsByTagName("head")[0].appendChild(O.element),e(y,HTMLImageElement)&&(y.src=w.url,y.dataset.rbRetryTimes=String(w.times),y.dataset.rbOriginalQuery=String(w.originalQuery))}}}}(c,t)}catch(e){console.error("retry error captured",e)}},o=function(e){try{!function(e,t){var i=r(e,t);if(!1!==i){var a=i.target,o=i.tagName,c=i.url,s=n(c,e.domain),l=Number(a.dataset.rbRetryTimes)||0;0!==l&&"function"==typeof e.onSuccess&&e.onSuccess({times:l,domain:s,url:c,tagName:o,isAsyncChunk:!1})}}(c,e)}catch(e){console.error("load error captured",e)}},"undefined"!=typeof window&&void 0!==window.document&&(document.addEventListener("error",function(t){t&&e(t.target,Element)&&a(t)},!0),document.addEventListener("load",function(t){t&&e(t.target,Element)&&o(t)},!0))}catch(e){console.error("monitor error captured",e)}
1
+ function e(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t}var t={link:HTMLLinkElement,script:HTMLScriptElement,img:HTMLImageElement};function n(e,t){for(var n="",r=0;r<t.length;r++)if(-1!==e.indexOf(t[r])){n=t[r];break}return n||window.origin}function r(n,r){var i=r.target,a=i.tagName.toLocaleLowerCase(),o=n.type,c=e(i,HTMLScriptElement)||e(i,HTMLImageElement)?i.src:e(i,HTMLLinkElement)?i.href:null;return!!(a&&-1!==o.indexOf(a)&&t[a]&&e(i,t[a]))&&!!c&&{target:i,tagName:a,url:c}}var i=/[?#].*$/;function a(t,n,r){e(t,HTMLScriptElement)&&(r.isAsync?document.body.appendChild(n.element):document.write(n.str)),e(t,HTMLLinkElement)&&document.getElementsByTagName("head")[0].appendChild(n.element),e(t,HTMLImageElement)&&(t.src=r.url,t.dataset.rbRetryTimes=String(r.times),t.dataset.rbOriginalQuery=String(r.originalQuery))}"undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={});try{var o,c,s=__RUNTIME_GLOBALS_OPTIONS__;o=function(t){try{!function(t,o){var c,s,l,u,d,m,y,f=r(t,o);if(!1!==f){var g=f.target,p=f.tagName,v=f.url;if(!("undefined"!=typeof window&&Object.keys(window.__RB_ASYNC_CHUNKS__||{}).some(function(e){return -1!==v.indexOf(e)}))){var _=t.test;if(_){if("string"==typeof _){var b=new RegExp(_);_=function(e){return b.test(e)}}if("function"!=typeof _||!_(v))return}var L=n(v,t.domain);if(!t.domain||!(t.domain.length>0)||-1!==t.domain.indexOf(L)){var S=Number(g.dataset.rbRetryTimes)||0;if(S===t.max){"function"==typeof t.onFail&&t.onFail({times:S,domain:L,url:v,tagName:p,isAsyncChunk:!1});return}var E=(s=n(L,c=t.domain),l=c.indexOf(s),c[(l+1)%c.length]||L),T=null!==(m=g.dataset.rbOriginalQuery)&&void 0!==m?m:(u=v.split("?")[1])?"?".concat(u.split("#")[0]):"",w=!!g.dataset.rbAsync||g.async||g.defer,O={url:v.replace(L,E).replace(i,"")+(d=S+1,!0===t.addQuery?""!==T?"".concat(T,"&retry=").concat(d):"?retry=".concat(d):"function"==typeof t.addQuery?t.addQuery({times:d,originalQuery:T}):""),times:S+1,crossOrigin:t.crossOrigin,isAsync:w,originalQuery:T},h=function(t,n){var r=!0===n.crossOrigin?"anonymous":n.crossOrigin,i=r?'crossorigin="'.concat(r,'"'):"",a=n.times?'data-rb-retry-times="'.concat(n.times,'"'):"",o=n.originalQuery?'data-rb-original-query="'.concat(n.originalQuery,'"'):"",c=n.isAsync?"data-rb-async":"";if(e(t,HTMLScriptElement)){var s=document.createElement("script");return s.src=n.url,r&&(s.crossOrigin=r),n.times&&(s.dataset.rbRetryTimes=String(n.times)),n.isAsync&&(s.dataset.rbAsync=""),void 0!==n.originalQuery&&(s.dataset.rbOriginalQuery=n.originalQuery),{element:s,str:'<script src="'.concat(n.url,'" ').concat(i," ").concat(a," ").concat(c," ").concat(o,">")+"<\/script>"}}if(e(t,HTMLLinkElement)){var l=document.createElement("link");return l.rel=t.rel||"stylesheet",t.as&&(l.as=t.as),l.href=n.url,r&&(l.crossOrigin=r),n.times&&(l.dataset.rbRetryTimes=String(n.times)),void 0!==n.originalQuery&&(l.dataset.rbOriginalQuery=n.originalQuery),{element:l,str:'<link rel="'.concat(l.rel,'" href="').concat(n.url,'" ').concat(i," ").concat(a," ").concat(l.as?'as="'.concat(l.as,'"'):""," ").concat(o,"></link>")}}}(g,O),N={times:S,domain:L,url:v,tagName:p,isAsyncChunk:!1};"function"==typeof t.onRetry&&t.onRetry(N);var Q="function"==typeof t.delay?t.delay(N):null!==(y=t.delay)&&void 0!==y?y:0;Q>0?setTimeout(function(){a(g,h,O)},Q):a(g,h,O)}}}}(s,t)}catch(e){console.error("retry error captured",e)}},c=function(e){try{!function(e,t){var i=r(e,t);if(!1!==i){var a=i.target,o=i.tagName,c=i.url,s=n(c,e.domain),l=Number(a.dataset.rbRetryTimes)||0;0!==l&&"function"==typeof e.onSuccess&&e.onSuccess({times:l,domain:s,url:c,tagName:o,isAsyncChunk:!1})}}(s,e)}catch(e){console.error("load error captured",e)}},"undefined"!=typeof window&&void 0!==window.document&&(document.addEventListener("error",function(t){t&&e(t.target,Element)&&o(t)},!0),document.addEventListener("load",function(t){t&&e(t.target,Element)&&c(t)},!0))}catch(e){console.error("monitor error captured",e)}
package/dist/types.d.ts CHANGED
@@ -56,6 +56,11 @@ export type PluginAssetsRetryOptions = {
56
56
  * @default rsbuildConfig.mode === 'production'
57
57
  */
58
58
  minify?: boolean;
59
+ /**
60
+ * The delay time between retries. Unit: ms
61
+ * @default 0
62
+ */
63
+ delay?: number | ((context: AssetsRetryHookContext) => number);
59
64
  };
60
65
  export type RuntimeRetryOptions = Omit<PluginAssetsRetryOptions, 'inlineScript' | 'minify'>;
61
66
  export type AssetsRetryHookContext = {