@module-federation/retry-plugin 0.0.0-docs-remove-invalid-lark-link-20251205062649
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/LICENSE +21 -0
- package/README.md +347 -0
- package/dist/CHANGELOG.md +451 -0
- package/dist/README.md +347 -0
- package/dist/esm/index.js +361 -0
- package/dist/index.d.mts +110 -0
- package/dist/index.d.ts +110 -0
- package/dist/index.js +390 -0
- package/dist/package.json +41 -0
- package/package.json +41 -0
package/dist/README.md
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
# @module-federation/retry-plugin
|
|
2
|
+
|
|
3
|
+
> A robust retry plugin for Module Federation that provides automatic retry mechanisms for failed module requests with domain rotation, cache-busting, and comprehensive error handling.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🔄 **Automatic Retry**: Automatically retries failed fetch and script requests
|
|
8
|
+
- 🌐 **Domain Rotation**: Rotate through multiple domains for better reliability
|
|
9
|
+
- ⚡ **Cache Busting**: Add query parameters to bypass cache issues
|
|
10
|
+
- 📊 **Lifecycle Callbacks**: Comprehensive callbacks for retry events
|
|
11
|
+
- 🎯 **Flexible Configuration**: Highly configurable retry strategies
|
|
12
|
+
- 🔧 **TypeScript Support**: Full TypeScript support with type definitions
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @module-federation/retry-plugin
|
|
18
|
+
# or
|
|
19
|
+
yarn add @module-federation/retry-plugin
|
|
20
|
+
# or
|
|
21
|
+
pnpm add @module-federation/retry-plugin
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Basic Usage
|
|
25
|
+
|
|
26
|
+
### Runtime Plugin Registration
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createInstance } from '@module-federation/enhanced/runtime';
|
|
30
|
+
import { RetryPlugin } from '@module-federation/retry-plugin';
|
|
31
|
+
|
|
32
|
+
const mf = createInstance({
|
|
33
|
+
name: 'host',
|
|
34
|
+
remotes: [
|
|
35
|
+
{
|
|
36
|
+
name: 'remote1',
|
|
37
|
+
entry: 'http://localhost:2001/mf-manifest.json',
|
|
38
|
+
}
|
|
39
|
+
],
|
|
40
|
+
plugins: [
|
|
41
|
+
RetryPlugin({
|
|
42
|
+
retryTimes: 3,
|
|
43
|
+
retryDelay: 1000,
|
|
44
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
|
|
45
|
+
manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'],
|
|
46
|
+
addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
|
|
47
|
+
onRetry: ({ times, url }) => console.log('Retrying...', times, url),
|
|
48
|
+
onSuccess: ({ url }) => console.log('Success!', url),
|
|
49
|
+
onError: ({ url }) => console.log('Failed!', url),
|
|
50
|
+
}),
|
|
51
|
+
]
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Build Plugin Registration
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
// webpack.config.js
|
|
59
|
+
import { ModuleFederationPlugin } from '@module-federation/webpack';
|
|
60
|
+
import { RetryPlugin } from '@module-federation/retry-plugin';
|
|
61
|
+
|
|
62
|
+
export default {
|
|
63
|
+
plugins: [
|
|
64
|
+
new ModuleFederationPlugin({
|
|
65
|
+
name: 'host',
|
|
66
|
+
remotes: {
|
|
67
|
+
remote1: 'remote1@http://localhost:2001/mf-manifest.json',
|
|
68
|
+
},
|
|
69
|
+
runtimePlugins: [
|
|
70
|
+
path.join(__dirname, './src/runtime-plugin/retry.ts'),
|
|
71
|
+
],
|
|
72
|
+
}),
|
|
73
|
+
],
|
|
74
|
+
};
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
// src/runtime-plugin/retry.ts
|
|
79
|
+
import { RetryPlugin } from '@module-federation/retry-plugin';
|
|
80
|
+
|
|
81
|
+
export default () => RetryPlugin({
|
|
82
|
+
retryTimes: 3,
|
|
83
|
+
retryDelay: 1000,
|
|
84
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
|
|
85
|
+
manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'],
|
|
86
|
+
addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
|
|
87
|
+
onRetry: ({ times, url }) => console.log('Retrying...', times, url),
|
|
88
|
+
onSuccess: ({ url }) => console.log('Success!', url),
|
|
89
|
+
onError: ({ url }) => console.log('Failed!', url),
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Configuration Options
|
|
94
|
+
|
|
95
|
+
### CommonRetryOptions
|
|
96
|
+
|
|
97
|
+
| Option | Type | Default | Description |
|
|
98
|
+
|--------|------|---------|-------------|
|
|
99
|
+
| `retryTimes` | `number` | `3` | Number of retry attempts |
|
|
100
|
+
| `retryDelay` | `number` | `1000` | Delay between retries in milliseconds |
|
|
101
|
+
| `successTimes` | `number` | `0` | Number of successful requests required |
|
|
102
|
+
| `domains` | `string[]` | `[]` | Alternative domains for script resources |
|
|
103
|
+
| `manifestDomains` | `string[]` | `[]` | Alternative domains for manifest files |
|
|
104
|
+
| `addQuery` | `boolean \| function` | `false` | Add query parameters for cache busting |
|
|
105
|
+
| `fetchOptions` | `RequestInit` | `{}` | Additional fetch options |
|
|
106
|
+
| `onRetry` | `function` | `undefined` | Callback when retry occurs |
|
|
107
|
+
| `onSuccess` | `function` | `undefined` | Callback when request succeeds |
|
|
108
|
+
| `onError` | `function` | `undefined` | Callback when all retries fail |
|
|
109
|
+
|
|
110
|
+
### addQuery Function
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
addQuery: ({ times, originalQuery }) => {
|
|
114
|
+
// Add retry count and timestamp for cache busting
|
|
115
|
+
const separator = originalQuery ? '&' : '?';
|
|
116
|
+
return `${originalQuery}${separator}retry=${times}&t=${Date.now()}`;
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Callback Functions
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
onRetry: ({ times, domains, url, tagName }) => {
|
|
124
|
+
console.log(`Retry attempt ${times} for ${url}`);
|
|
125
|
+
console.log(`Available domains: ${domains?.join(', ')}`);
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
onSuccess: ({ domains, url, tagName }) => {
|
|
129
|
+
console.log(`Successfully loaded ${url}`);
|
|
130
|
+
console.log(`Used domain: ${domains?.[0]}`);
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
onError: ({ domains, url, tagName }) => {
|
|
134
|
+
console.error(`Failed to load ${url} after all retries`);
|
|
135
|
+
console.error(`Tried domains: ${domains?.join(', ')}`);
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Advanced Examples
|
|
140
|
+
|
|
141
|
+
### Custom Retry Strategy
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
RetryPlugin({
|
|
145
|
+
retryTimes: 5,
|
|
146
|
+
retryDelay: (attempt) => Math.pow(2, attempt) * 1000, // Exponential backoff
|
|
147
|
+
domains: [
|
|
148
|
+
'https://cdn1.example.com',
|
|
149
|
+
'https://cdn2.example.com',
|
|
150
|
+
'https://cdn3.example.com',
|
|
151
|
+
],
|
|
152
|
+
manifestDomains: [
|
|
153
|
+
'https://api1.example.com',
|
|
154
|
+
'https://api2.example.com',
|
|
155
|
+
],
|
|
156
|
+
addQuery: ({ times, originalQuery }) => {
|
|
157
|
+
const params = new URLSearchParams(originalQuery);
|
|
158
|
+
params.set('retry', times.toString());
|
|
159
|
+
params.set('cache_bust', Date.now().toString());
|
|
160
|
+
return params.toString();
|
|
161
|
+
},
|
|
162
|
+
onRetry: ({ times, url, domains }) => {
|
|
163
|
+
console.log(`Retry ${times}/5 for ${url}`);
|
|
164
|
+
console.log(`Trying domain: ${domains?.[times % domains.length]}`);
|
|
165
|
+
},
|
|
166
|
+
onSuccess: ({ url, domains }) => {
|
|
167
|
+
console.log(`✅ Successfully loaded ${url}`);
|
|
168
|
+
console.log(`✅ Used domain: ${domains?.[0]}`);
|
|
169
|
+
},
|
|
170
|
+
onError: ({ url, domains }) => {
|
|
171
|
+
console.error(`❌ Failed to load ${url} after all retries`);
|
|
172
|
+
console.error(`❌ Tried all domains: ${domains?.join(', ')}`);
|
|
173
|
+
},
|
|
174
|
+
})
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Error Handling with Fallback
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
RetryPlugin({
|
|
181
|
+
retryTimes: 3,
|
|
182
|
+
retryDelay: 1000,
|
|
183
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
|
|
184
|
+
onError: ({ url, domains }) => {
|
|
185
|
+
// Log error for monitoring
|
|
186
|
+
console.error('Module loading failed:', { url, domains });
|
|
187
|
+
|
|
188
|
+
// Send error to monitoring service
|
|
189
|
+
if (window.gtag) {
|
|
190
|
+
window.gtag('event', 'module_load_error', {
|
|
191
|
+
event_category: 'module_federation',
|
|
192
|
+
event_label: url,
|
|
193
|
+
value: domains?.length || 0,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Show user-friendly error message
|
|
198
|
+
const errorElement = document.createElement('div');
|
|
199
|
+
errorElement.className = 'module-load-error';
|
|
200
|
+
errorElement.innerHTML = `
|
|
201
|
+
<div style="padding: 16px; border: 1px solid #ffa39e; border-radius: 4px; background: #fff1f0; color: #cf1322;">
|
|
202
|
+
<h4>Module Loading Failed</h4>
|
|
203
|
+
<p>Unable to load module: ${url}</p>
|
|
204
|
+
<p>Please refresh the page to try again.</p>
|
|
205
|
+
</div>
|
|
206
|
+
`;
|
|
207
|
+
document.body.appendChild(errorElement);
|
|
208
|
+
},
|
|
209
|
+
})
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### Production Configuration
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
RetryPlugin({
|
|
216
|
+
retryTimes: 3,
|
|
217
|
+
retryDelay: 1000,
|
|
218
|
+
domains: [
|
|
219
|
+
'https://cdn1.prod.example.com',
|
|
220
|
+
'https://cdn2.prod.example.com',
|
|
221
|
+
'https://cdn3.prod.example.com',
|
|
222
|
+
],
|
|
223
|
+
manifestDomains: [
|
|
224
|
+
'https://api1.prod.example.com',
|
|
225
|
+
'https://api2.prod.example.com',
|
|
226
|
+
],
|
|
227
|
+
addQuery: ({ times, originalQuery }) => {
|
|
228
|
+
const params = new URLSearchParams(originalQuery);
|
|
229
|
+
params.set('retry', times.toString());
|
|
230
|
+
params.set('v', process.env.BUILD_VERSION || '1.0.0');
|
|
231
|
+
return params.toString();
|
|
232
|
+
},
|
|
233
|
+
fetchOptions: {
|
|
234
|
+
cache: 'no-cache',
|
|
235
|
+
headers: {
|
|
236
|
+
'X-Requested-With': 'ModuleFederation',
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
onRetry: ({ times, url }) => {
|
|
240
|
+
// Only log in development
|
|
241
|
+
if (process.env.NODE_ENV === 'development') {
|
|
242
|
+
console.log(`Retry ${times} for ${url}`);
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
onSuccess: ({ url }) => {
|
|
246
|
+
// Track successful loads
|
|
247
|
+
if (window.analytics) {
|
|
248
|
+
window.analytics.track('module_loaded', { url });
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
onError: ({ url, domains }) => {
|
|
252
|
+
// Send error to monitoring service
|
|
253
|
+
if (window.errorReporting) {
|
|
254
|
+
window.errorReporting.captureException(
|
|
255
|
+
new Error(`Module loading failed: ${url}`),
|
|
256
|
+
{ extra: { domains, url } }
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
})
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## How It Works
|
|
264
|
+
|
|
265
|
+
1. **Fetch Retry**: Intercepts failed fetch requests for manifest files and retries with domain rotation
|
|
266
|
+
2. **Script Retry**: Intercepts failed script loading and retries with alternative domains
|
|
267
|
+
3. **Domain Rotation**: Cycles through provided domains to find working alternatives
|
|
268
|
+
4. **Cache Busting**: Adds query parameters to prevent cache-related issues
|
|
269
|
+
5. **Lifecycle Hooks**: Provides callbacks for monitoring and debugging
|
|
270
|
+
|
|
271
|
+
## Error Scenarios Handled
|
|
272
|
+
|
|
273
|
+
- Network timeouts and connection errors
|
|
274
|
+
- DNS resolution failures
|
|
275
|
+
- Server errors (5xx status codes)
|
|
276
|
+
- CDN failures and regional issues
|
|
277
|
+
- Cache-related loading problems
|
|
278
|
+
- CORS and security policy violations
|
|
279
|
+
|
|
280
|
+
## Browser Support
|
|
281
|
+
|
|
282
|
+
- Chrome 60+
|
|
283
|
+
- Firefox 55+
|
|
284
|
+
- Safari 12+
|
|
285
|
+
- Edge 79+
|
|
286
|
+
|
|
287
|
+
## TypeScript Support
|
|
288
|
+
|
|
289
|
+
The plugin includes full TypeScript definitions:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import { RetryPlugin, type CommonRetryOptions } from '@module-federation/retry-plugin';
|
|
293
|
+
|
|
294
|
+
const options: CommonRetryOptions = {
|
|
295
|
+
retryTimes: 3,
|
|
296
|
+
retryDelay: 1000,
|
|
297
|
+
domains: ['https://cdn1.example.com'],
|
|
298
|
+
onRetry: ({ times, url }) => {
|
|
299
|
+
console.log(`Retry ${times} for ${url}`);
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
const plugin = RetryPlugin(options);
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
## Migration Guide
|
|
307
|
+
|
|
308
|
+
### From v0.18.x to v0.19.x
|
|
309
|
+
|
|
310
|
+
The plugin configuration has been simplified. The old `fetch` and `script` configuration objects are deprecated:
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
// ❌ Old way (deprecated)
|
|
314
|
+
RetryPlugin({
|
|
315
|
+
fetch: {
|
|
316
|
+
url: 'http://localhost:2008/not-exist-mf-manifest.json',
|
|
317
|
+
fallback: () => 'http://localhost:2001/mf-manifest.json',
|
|
318
|
+
},
|
|
319
|
+
script: {
|
|
320
|
+
url: 'http://localhost:2001/static/js/async/src_App_tsx.js',
|
|
321
|
+
customCreateScript: (url, attrs) => { /* ... */ },
|
|
322
|
+
}
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
// ✅ New way
|
|
326
|
+
RetryPlugin({
|
|
327
|
+
retryTimes: 3,
|
|
328
|
+
retryDelay: 1000,
|
|
329
|
+
domains: ['http://localhost:2001'],
|
|
330
|
+
manifestDomains: ['http://localhost:2001'],
|
|
331
|
+
addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
|
|
332
|
+
})
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
## Contributing
|
|
336
|
+
|
|
337
|
+
Contributions are welcome! Please read our [contributing guidelines](https://github.com/module-federation/core/blob/main/CONTRIBUTING.md) and submit pull requests to our [GitHub repository](https://github.com/module-federation/core).
|
|
338
|
+
|
|
339
|
+
## License
|
|
340
|
+
|
|
341
|
+
`@module-federation/retry-plugin` is [MIT licensed](https://github.com/module-federation/core/blob/main/packages/retry-plugin/LICENSE).
|
|
342
|
+
|
|
343
|
+
## Related
|
|
344
|
+
|
|
345
|
+
- [Module Federation Documentation](https://module-federation.io/)
|
|
346
|
+
- [Module Federation Runtime](https://www.npmjs.com/package/@module-federation/runtime)
|
|
347
|
+
- [Module Federation Enhanced](https://www.npmjs.com/package/@module-federation/enhanced)
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
|
|
4
|
+
// packages/retry-plugin/src/constant.ts
|
|
5
|
+
var defaultRetries = 3;
|
|
6
|
+
var defaultRetryDelay = 1e3;
|
|
7
|
+
var PLUGIN_IDENTIFIER = "[ Module Federation RetryPlugin ]";
|
|
8
|
+
var ERROR_ABANDONED = "The request failed and has now been abandoned";
|
|
9
|
+
var RUNTIME_008 = "RUNTIME-008";
|
|
10
|
+
|
|
11
|
+
// packages/retry-plugin/src/logger.ts
|
|
12
|
+
import { createLogger } from "@module-federation/sdk";
|
|
13
|
+
var logger = createLogger(PLUGIN_IDENTIFIER);
|
|
14
|
+
var logger_default = logger;
|
|
15
|
+
|
|
16
|
+
// packages/retry-plugin/src/utils.ts
|
|
17
|
+
function rewriteWithNextDomain(currentUrl, domains) {
|
|
18
|
+
if (!domains || domains.length === 0)
|
|
19
|
+
return null;
|
|
20
|
+
try {
|
|
21
|
+
const u = new URL(currentUrl);
|
|
22
|
+
const currentHostname = u.hostname;
|
|
23
|
+
const currentPort = u.port;
|
|
24
|
+
const currentHost = `${currentHostname}${currentPort ? `:${currentPort}` : ""}`;
|
|
25
|
+
const normalized = domains.map((d) => {
|
|
26
|
+
try {
|
|
27
|
+
const du = new URL(d.startsWith("http") ? d : `https://${d}`);
|
|
28
|
+
return {
|
|
29
|
+
hostname: du.hostname,
|
|
30
|
+
port: du.port,
|
|
31
|
+
protocol: du.protocol
|
|
32
|
+
};
|
|
33
|
+
} catch {
|
|
34
|
+
return {
|
|
35
|
+
hostname: d,
|
|
36
|
+
port: "",
|
|
37
|
+
protocol: u.protocol
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}).filter((d) => !!d.hostname);
|
|
41
|
+
if (normalized.length === 0)
|
|
42
|
+
return null;
|
|
43
|
+
let idx = -1;
|
|
44
|
+
for (let i = normalized.length - 1; i >= 0; i--) {
|
|
45
|
+
const candHost = `${normalized[i].hostname}${normalized[i].port ? `:${normalized[i].port}` : ""}`;
|
|
46
|
+
if (candHost === currentHost) {
|
|
47
|
+
idx = i;
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const total = normalized.length;
|
|
52
|
+
for (let step = 1; step <= total; step++) {
|
|
53
|
+
const nextIdx = ((idx >= 0 ? idx : -1) + step) % total;
|
|
54
|
+
const candidate = normalized[nextIdx];
|
|
55
|
+
const candidateHost = `${candidate.hostname}${candidate.port ? `:${candidate.port}` : ""}`;
|
|
56
|
+
if (candidateHost !== currentHost) {
|
|
57
|
+
u.hostname = candidate.hostname;
|
|
58
|
+
if (candidate.port !== void 0 && candidate.port !== null && candidate.port !== "") {
|
|
59
|
+
u.port = candidate.port;
|
|
60
|
+
} else {
|
|
61
|
+
u.port = "";
|
|
62
|
+
}
|
|
63
|
+
u.protocol = candidate.protocol || u.protocol;
|
|
64
|
+
return u.toString();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
__name(rewriteWithNextDomain, "rewriteWithNextDomain");
|
|
73
|
+
function appendRetryCountQuery(url, retryIndex, key = "retryCount") {
|
|
74
|
+
try {
|
|
75
|
+
const u = new URL(url);
|
|
76
|
+
u.searchParams.delete(key);
|
|
77
|
+
u.searchParams.set(key, String(retryIndex));
|
|
78
|
+
return u.toString();
|
|
79
|
+
} catch {
|
|
80
|
+
return url;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
__name(appendRetryCountQuery, "appendRetryCountQuery");
|
|
84
|
+
function getRetryUrl(baseUrl, opts = {}) {
|
|
85
|
+
const { domains, addQuery, retryIndex = 0, queryKey = "retryCount" } = opts;
|
|
86
|
+
let cleanBaseUrl = baseUrl;
|
|
87
|
+
try {
|
|
88
|
+
const urlObj = new URL(baseUrl);
|
|
89
|
+
urlObj.searchParams.delete(queryKey);
|
|
90
|
+
cleanBaseUrl = urlObj.toString();
|
|
91
|
+
} catch {
|
|
92
|
+
}
|
|
93
|
+
let nextUrl = rewriteWithNextDomain(cleanBaseUrl, domains) ?? cleanBaseUrl;
|
|
94
|
+
if (retryIndex > 0 && addQuery) {
|
|
95
|
+
try {
|
|
96
|
+
const u = new URL(nextUrl);
|
|
97
|
+
const originalUrl = new URL(baseUrl);
|
|
98
|
+
originalUrl.searchParams.delete(queryKey);
|
|
99
|
+
const originalQuery = originalUrl.search.startsWith("?") ? originalUrl.search.slice(1) : originalUrl.search;
|
|
100
|
+
if (typeof addQuery === "function") {
|
|
101
|
+
const newQuery = addQuery({
|
|
102
|
+
times: retryIndex,
|
|
103
|
+
originalQuery
|
|
104
|
+
});
|
|
105
|
+
u.search = newQuery ? `?${newQuery.replace(/^\?/, "")}` : "";
|
|
106
|
+
nextUrl = u.toString();
|
|
107
|
+
} else if (addQuery === true) {
|
|
108
|
+
u.searchParams.delete(queryKey);
|
|
109
|
+
u.searchParams.set(queryKey, String(retryIndex));
|
|
110
|
+
nextUrl = u.toString();
|
|
111
|
+
}
|
|
112
|
+
} catch {
|
|
113
|
+
if (addQuery === true) {
|
|
114
|
+
nextUrl = appendRetryCountQuery(nextUrl, retryIndex, queryKey);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return nextUrl;
|
|
119
|
+
}
|
|
120
|
+
__name(getRetryUrl, "getRetryUrl");
|
|
121
|
+
function combineUrlDomainWithPathQuery(domainUrl, pathQueryUrl) {
|
|
122
|
+
try {
|
|
123
|
+
const domainUrlObj = new URL(domainUrl);
|
|
124
|
+
const pathQueryUrlObj = new URL(pathQueryUrl);
|
|
125
|
+
domainUrlObj.pathname = pathQueryUrlObj.pathname;
|
|
126
|
+
domainUrlObj.search = pathQueryUrlObj.search;
|
|
127
|
+
return domainUrlObj.toString();
|
|
128
|
+
} catch {
|
|
129
|
+
return pathQueryUrl;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
__name(combineUrlDomainWithPathQuery, "combineUrlDomainWithPathQuery");
|
|
133
|
+
|
|
134
|
+
// packages/retry-plugin/src/fetch-retry.ts
|
|
135
|
+
function autoParseResponse(url, response) {
|
|
136
|
+
try {
|
|
137
|
+
const parsed = new URL(url);
|
|
138
|
+
if (parsed.pathname.endsWith(".js") || parsed.pathname.endsWith(".cjs") || parsed.pathname.endsWith(".mjs")) {
|
|
139
|
+
return response.text();
|
|
140
|
+
}
|
|
141
|
+
return response.json();
|
|
142
|
+
} catch (error) {
|
|
143
|
+
return response.json();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
__name(autoParseResponse, "autoParseResponse");
|
|
147
|
+
async function fetchRetry(params, lastRequestUrl, originalTotal) {
|
|
148
|
+
const {
|
|
149
|
+
url,
|
|
150
|
+
fetchOptions = {},
|
|
151
|
+
retryTimes = defaultRetries,
|
|
152
|
+
retryDelay = defaultRetryDelay,
|
|
153
|
+
// List of retry domains when resource loading fails. In the domains array, the first item is the default domain for static resources, and the subsequent items are backup domains. When a request to a domain fails, the system will find that domain in the array and replace it with the next domain in the array.
|
|
154
|
+
domains,
|
|
155
|
+
// Whether to add query parameters during resource retry to avoid being affected by browser and CDN cache. When set to true, retry=${times} will be added to the query, requesting in the order of retry=1, retry=2, retry=3.
|
|
156
|
+
addQuery,
|
|
157
|
+
onRetry,
|
|
158
|
+
onSuccess,
|
|
159
|
+
onError
|
|
160
|
+
} = params;
|
|
161
|
+
if (!url) {
|
|
162
|
+
throw new Error(`${PLUGIN_IDENTIFIER}: url is required in fetchWithRetry`);
|
|
163
|
+
}
|
|
164
|
+
const total = originalTotal ?? params.retryTimes ?? defaultRetries;
|
|
165
|
+
const isFirstAttempt = !lastRequestUrl;
|
|
166
|
+
let baseUrl = url;
|
|
167
|
+
if (!isFirstAttempt && lastRequestUrl) {
|
|
168
|
+
baseUrl = combineUrlDomainWithPathQuery(lastRequestUrl, url);
|
|
169
|
+
}
|
|
170
|
+
let requestUrl = baseUrl;
|
|
171
|
+
if (!isFirstAttempt) {
|
|
172
|
+
requestUrl = getRetryUrl(baseUrl, {
|
|
173
|
+
domains,
|
|
174
|
+
addQuery,
|
|
175
|
+
retryIndex: total - retryTimes,
|
|
176
|
+
queryKey: "retryCount"
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
if (!isFirstAttempt && retryDelay > 0) {
|
|
181
|
+
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
182
|
+
}
|
|
183
|
+
const response = await fetch(requestUrl, fetchOptions);
|
|
184
|
+
const responseClone = response.clone();
|
|
185
|
+
if (!response.ok) {
|
|
186
|
+
throw new Error(`${PLUGIN_IDENTIFIER}: Request failed: ${response.status} ${response.statusText || ""} | url: ${requestUrl}`);
|
|
187
|
+
}
|
|
188
|
+
await autoParseResponse(requestUrl, responseClone).catch((error) => {
|
|
189
|
+
throw new Error(`${PLUGIN_IDENTIFIER}: JSON parse failed: ${error?.message || String(error)} | url: ${requestUrl}`);
|
|
190
|
+
});
|
|
191
|
+
if (!isFirstAttempt) {
|
|
192
|
+
onSuccess && requestUrl && onSuccess({
|
|
193
|
+
domains,
|
|
194
|
+
url: requestUrl,
|
|
195
|
+
tagName: "fetch"
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return response;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (retryTimes <= 0) {
|
|
201
|
+
const attemptedRetries = total - retryTimes;
|
|
202
|
+
if (!isFirstAttempt && attemptedRetries > 0) {
|
|
203
|
+
onError && onError({
|
|
204
|
+
domains,
|
|
205
|
+
url: requestUrl,
|
|
206
|
+
tagName: "fetch"
|
|
207
|
+
});
|
|
208
|
+
logger_default.log(`${PLUGIN_IDENTIFIER}: retry failed, no retries left for url: ${requestUrl}`);
|
|
209
|
+
}
|
|
210
|
+
throw new Error(`${RUNTIME_008}: ${PLUGIN_IDENTIFIER}: ${ERROR_ABANDONED} | url: ${requestUrl}`);
|
|
211
|
+
} else {
|
|
212
|
+
const nextIndex = total - retryTimes + 1;
|
|
213
|
+
const predictedBaseUrl = combineUrlDomainWithPathQuery(requestUrl, url);
|
|
214
|
+
const predictedNextUrl = getRetryUrl(predictedBaseUrl, {
|
|
215
|
+
domains,
|
|
216
|
+
addQuery,
|
|
217
|
+
retryIndex: nextIndex,
|
|
218
|
+
queryKey: "retryCount"
|
|
219
|
+
});
|
|
220
|
+
onRetry && onRetry({
|
|
221
|
+
times: nextIndex,
|
|
222
|
+
domains,
|
|
223
|
+
url: predictedNextUrl,
|
|
224
|
+
tagName: "fetch"
|
|
225
|
+
});
|
|
226
|
+
logger_default.log(`${PLUGIN_IDENTIFIER}: Trying again. Number of retries left: ${retryTimes - 1}`);
|
|
227
|
+
return await fetchRetry({
|
|
228
|
+
...params,
|
|
229
|
+
retryTimes: retryTimes - 1
|
|
230
|
+
}, requestUrl, total);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
__name(fetchRetry, "fetchRetry");
|
|
235
|
+
|
|
236
|
+
// packages/retry-plugin/src/script-retry.ts
|
|
237
|
+
function scriptRetry({ retryOptions, retryFn, beforeExecuteRetry = /* @__PURE__ */ __name(() => {
|
|
238
|
+
}, "beforeExecuteRetry") }) {
|
|
239
|
+
return async function(params) {
|
|
240
|
+
let retryWrapper;
|
|
241
|
+
let lastError;
|
|
242
|
+
let lastRequestUrl;
|
|
243
|
+
let originalUrl;
|
|
244
|
+
const { retryTimes = defaultRetries, retryDelay = defaultRetryDelay, domains, addQuery, onRetry, onSuccess, onError } = retryOptions || {};
|
|
245
|
+
let attempts = 0;
|
|
246
|
+
const maxAttempts = retryTimes;
|
|
247
|
+
while (attempts < maxAttempts) {
|
|
248
|
+
try {
|
|
249
|
+
beforeExecuteRetry();
|
|
250
|
+
if (retryDelay > 0 && attempts > 0) {
|
|
251
|
+
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
|
252
|
+
}
|
|
253
|
+
const retryIndex = attempts + 1;
|
|
254
|
+
retryWrapper = await retryFn({
|
|
255
|
+
...params,
|
|
256
|
+
getEntryUrl: (url) => {
|
|
257
|
+
if (!originalUrl) {
|
|
258
|
+
originalUrl = url;
|
|
259
|
+
}
|
|
260
|
+
let baseUrl = originalUrl;
|
|
261
|
+
if (lastRequestUrl) {
|
|
262
|
+
baseUrl = combineUrlDomainWithPathQuery(lastRequestUrl, originalUrl);
|
|
263
|
+
}
|
|
264
|
+
const next = getRetryUrl(baseUrl, {
|
|
265
|
+
domains,
|
|
266
|
+
addQuery,
|
|
267
|
+
retryIndex,
|
|
268
|
+
queryKey: "retryCount"
|
|
269
|
+
});
|
|
270
|
+
onRetry && onRetry({
|
|
271
|
+
times: retryIndex,
|
|
272
|
+
domains,
|
|
273
|
+
url: next,
|
|
274
|
+
tagName: "script"
|
|
275
|
+
});
|
|
276
|
+
lastRequestUrl = next;
|
|
277
|
+
return next;
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
onSuccess && lastRequestUrl && onSuccess({
|
|
281
|
+
domains,
|
|
282
|
+
url: lastRequestUrl,
|
|
283
|
+
tagName: "script"
|
|
284
|
+
});
|
|
285
|
+
break;
|
|
286
|
+
} catch (error) {
|
|
287
|
+
lastError = error;
|
|
288
|
+
attempts++;
|
|
289
|
+
if (attempts >= maxAttempts) {
|
|
290
|
+
onError && lastRequestUrl && onError({
|
|
291
|
+
domains,
|
|
292
|
+
url: lastRequestUrl,
|
|
293
|
+
tagName: "script"
|
|
294
|
+
});
|
|
295
|
+
throw new Error(`${PLUGIN_IDENTIFIER}: ${ERROR_ABANDONED} | url: ${lastRequestUrl || "unknown"}`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return retryWrapper;
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
__name(scriptRetry, "scriptRetry");
|
|
303
|
+
|
|
304
|
+
// packages/retry-plugin/src/index.ts
|
|
305
|
+
var RetryPlugin = /* @__PURE__ */ __name((params) => {
|
|
306
|
+
if (params?.fetch || params?.script) {
|
|
307
|
+
logger_default.warn(`${PLUGIN_IDENTIFIER}: params is ${params}, fetch or script config is deprecated, please use the new config style. See docs: https://module-federation.io/plugin/plugins/retry-plugin.html`);
|
|
308
|
+
}
|
|
309
|
+
const { fetchOptions = {}, retryTimes = defaultRetries, successTimes = 0, retryDelay = defaultRetryDelay, domains = [], manifestDomains = [], addQuery, onRetry, onSuccess, onError } = params || {};
|
|
310
|
+
return {
|
|
311
|
+
name: "retry-plugin",
|
|
312
|
+
async fetch(manifestUrl, options) {
|
|
313
|
+
return fetchRetry({
|
|
314
|
+
url: manifestUrl,
|
|
315
|
+
fetchOptions: {
|
|
316
|
+
...options,
|
|
317
|
+
...fetchOptions
|
|
318
|
+
},
|
|
319
|
+
domains: manifestDomains || domains,
|
|
320
|
+
addQuery,
|
|
321
|
+
onRetry,
|
|
322
|
+
onSuccess,
|
|
323
|
+
onError,
|
|
324
|
+
retryTimes,
|
|
325
|
+
successTimes,
|
|
326
|
+
retryDelay
|
|
327
|
+
});
|
|
328
|
+
},
|
|
329
|
+
async loadEntryError({ getRemoteEntry, origin, remoteInfo, remoteEntryExports, globalLoading, uniqueKey }) {
|
|
330
|
+
const beforeExecuteRetry = /* @__PURE__ */ __name(() => {
|
|
331
|
+
delete globalLoading[uniqueKey];
|
|
332
|
+
}, "beforeExecuteRetry");
|
|
333
|
+
const getRemoteEntryRetry = scriptRetry({
|
|
334
|
+
retryOptions: {
|
|
335
|
+
retryTimes,
|
|
336
|
+
retryDelay,
|
|
337
|
+
domains,
|
|
338
|
+
addQuery,
|
|
339
|
+
onRetry,
|
|
340
|
+
onSuccess,
|
|
341
|
+
onError
|
|
342
|
+
},
|
|
343
|
+
retryFn: getRemoteEntry,
|
|
344
|
+
beforeExecuteRetry
|
|
345
|
+
});
|
|
346
|
+
const result = await getRemoteEntryRetry({
|
|
347
|
+
origin,
|
|
348
|
+
remoteInfo,
|
|
349
|
+
remoteEntryExports
|
|
350
|
+
});
|
|
351
|
+
return result;
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}, "RetryPlugin");
|
|
355
|
+
export {
|
|
356
|
+
RetryPlugin,
|
|
357
|
+
appendRetryCountQuery,
|
|
358
|
+
combineUrlDomainWithPathQuery,
|
|
359
|
+
getRetryUrl,
|
|
360
|
+
rewriteWithNextDomain
|
|
361
|
+
};
|