@softarc/native-federation-runtime 3.5.1 → 4.0.0-RC1

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.
Files changed (35) hide show
  1. package/README.md +6 -2
  2. package/dist/index.d.ts +6 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +320 -0
  5. package/dist/lib/get-shared.d.ts +20 -0
  6. package/dist/lib/get-shared.d.ts.map +1 -0
  7. package/dist/lib/init-federation.d.ts +105 -0
  8. package/dist/lib/init-federation.d.ts.map +1 -0
  9. package/dist/lib/load-remote-module.d.ts +83 -0
  10. package/dist/lib/load-remote-module.d.ts.map +1 -0
  11. package/dist/lib/model/build-notifications-options.d.ts +2 -0
  12. package/dist/lib/model/build-notifications-options.d.ts.map +1 -0
  13. package/dist/lib/model/externals.d.ts +4 -0
  14. package/dist/lib/model/externals.d.ts.map +1 -0
  15. package/dist/lib/model/federation-info.d.ts +7 -0
  16. package/dist/lib/model/federation-info.d.ts.map +1 -0
  17. package/dist/lib/model/global-cache.d.ts +12 -0
  18. package/dist/lib/model/global-cache.d.ts.map +1 -0
  19. package/dist/lib/model/import-map.d.ts +8 -0
  20. package/dist/lib/model/import-map.d.ts.map +1 -0
  21. package/dist/lib/model/remotes.d.ts +10 -0
  22. package/dist/lib/model/remotes.d.ts.map +1 -0
  23. package/dist/lib/utils/add-import-map.d.ts +3 -0
  24. package/dist/lib/utils/add-import-map.d.ts.map +1 -0
  25. package/dist/lib/utils/path-utils.d.ts +14 -0
  26. package/dist/lib/utils/path-utils.d.ts.map +1 -0
  27. package/dist/lib/utils/trusted-types.d.ts +2 -0
  28. package/dist/lib/utils/trusted-types.d.ts.map +1 -0
  29. package/dist/lib/watch-federation-build.d.ts +10 -0
  30. package/dist/lib/watch-federation-build.d.ts.map +1 -0
  31. package/package.json +34 -16
  32. package/LICENSE +0 -8
  33. package/fesm2022/softarc-native-federation-runtime.mjs +0 -631
  34. package/fesm2022/softarc-native-federation-runtime.mjs.map +0 -1
  35. package/index.d.ts +0 -249
@@ -1,631 +0,0 @@
1
- const defaultShareOptions = {
2
- singleton: false,
3
- requiredVersionPrefix: '',
4
- };
5
- function getShared(options = defaultShareOptions) {
6
- const nfc = window;
7
- const externals = nfc.__NATIVE_FEDERATION__.externals;
8
- const shared = {};
9
- const allKeys = [...externals.keys()];
10
- const keys = allKeys
11
- .filter((k) => !k.startsWith('/@id/') &&
12
- !k.startsWith('@angular-architects/module-federation') &&
13
- !k.endsWith('@'))
14
- .sort();
15
- for (const key of keys) {
16
- const idx = key.lastIndexOf('@');
17
- const pkgName = key.substring(0, idx);
18
- const version = key.substring(idx + 1);
19
- const path = externals.get(key) ?? '';
20
- const shareObj = {
21
- version,
22
- get: async () => {
23
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
- const lib = await window.importShim(path);
25
- return () => lib;
26
- },
27
- shareConfig: {
28
- singleton: options.singleton,
29
- requiredVersion: options.requiredVersionPrefix + version,
30
- },
31
- };
32
- if (!shared[pkgName]) {
33
- shared[pkgName] = [];
34
- }
35
- shared[pkgName].push(shareObj);
36
- }
37
- return shared;
38
- }
39
-
40
- const nfNamespace = '__NATIVE_FEDERATION__';
41
- const global$1 = globalThis;
42
- global$1[nfNamespace] ??= {
43
- externals: new Map(),
44
- remoteNamesToRemote: new Map(),
45
- baseUrlToRemoteNames: new Map(),
46
- };
47
- const globalCache = global$1[nfNamespace];
48
-
49
- const externals = globalCache.externals;
50
- function getExternalKey(shared) {
51
- return `${shared.packageName}@${shared.version}`;
52
- }
53
- function getExternalUrl(shared) {
54
- const packageKey = getExternalKey(shared);
55
- return externals.get(packageKey);
56
- }
57
- function setExternalUrl(shared, url) {
58
- const packageKey = getExternalKey(shared);
59
- externals.set(packageKey, url);
60
- }
61
-
62
- function mergeImportMaps(map1, map2) {
63
- return {
64
- imports: { ...map1.imports, ...map2.imports },
65
- scopes: { ...map1.scopes, ...map2.scopes },
66
- };
67
- }
68
-
69
- const remoteNamesToRemote = globalCache.remoteNamesToRemote;
70
- const baseUrlToRemoteNames = globalCache.baseUrlToRemoteNames;
71
- function addRemote(remoteName, remote) {
72
- remoteNamesToRemote.set(remoteName, remote);
73
- baseUrlToRemoteNames.set(remote.baseUrl, remoteName);
74
- }
75
- function getRemoteNameByBaseUrl(baseUrl) {
76
- return baseUrlToRemoteNames.get(baseUrl);
77
- }
78
- function isRemoteInitialized(baseUrl) {
79
- return baseUrlToRemoteNames.has(baseUrl);
80
- }
81
- function getRemote(remoteName) {
82
- return remoteNamesToRemote.get(remoteName);
83
- }
84
- function hasRemote(remoteName) {
85
- return remoteNamesToRemote.has(remoteName);
86
- }
87
-
88
- const global = globalThis;
89
- let policy;
90
- function createPolicy() {
91
- if (policy === undefined) {
92
- policy = null;
93
- if (global.trustedTypes) {
94
- try {
95
- policy = global.trustedTypes.createPolicy('native-federation', {
96
- createHTML: (html) => html,
97
- createScript: (script) => script,
98
- createScriptURL: (url) => url,
99
- });
100
- }
101
- catch {
102
- // trustedTypes.createPolicy may throw an exception if called with a name that is already registered, even in report-only mode.
103
- }
104
- }
105
- }
106
- return policy;
107
- }
108
- function tryCreateTrustedScript(script) {
109
- return createPolicy()?.createScript(script) ?? script;
110
- }
111
-
112
- function appendImportMap(importMap) {
113
- document.head.appendChild(Object.assign(document.createElement('script'), {
114
- type: tryCreateTrustedScript('importmap-shim'),
115
- textContent: tryCreateTrustedScript(JSON.stringify(importMap)),
116
- }));
117
- }
118
-
119
- /**
120
- * Returns the full directory of a given path.
121
- * @param url - The path to get the directory of.
122
- * @returns The full directory of the path.
123
- */
124
- function getDirectory(url) {
125
- const parts = url.split('/');
126
- parts.pop();
127
- return parts.join('/');
128
- }
129
- /**
130
- * Joins two paths together taking into account trailing slashes and "./" prefixes.
131
- * @param path1 - The first path to join.
132
- * @param path2 - The second path to join.
133
- * @returns The joined path.
134
- */
135
- function joinPaths(path1, path2) {
136
- while (path1.endsWith('/')) {
137
- path1 = path1.substring(0, path1.length - 1);
138
- }
139
- if (path2.startsWith('./')) {
140
- path2 = path2.substring(2, path2.length);
141
- }
142
- return `${path1}/${path2}`;
143
- }
144
-
145
- const BUILD_NOTIFICATIONS_ENDPOINT = '/@angular-architects/native-federation:build-notifications';
146
- var BuildNotificationType;
147
- (function (BuildNotificationType) {
148
- BuildNotificationType["COMPLETED"] = "federation-rebuild-complete";
149
- BuildNotificationType["ERROR"] = "federation-rebuild-error";
150
- BuildNotificationType["CANCELLED"] = "federation-rebuild-cancelled";
151
- })(BuildNotificationType || (BuildNotificationType = {}));
152
-
153
- /**
154
- * Watches for federation build completion events and automatically reloads the page.
155
- *
156
- * This function establishes a Server-Sent Events (SSE) connection to listen for
157
- * 'federation-rebuild-complete' notifications. When a build completes successfully,
158
- * it triggers a page reload to reflect the latest changes.
159
- * @param endpoint - The SSE endpoint URL to watch for build notifications.
160
- */
161
- function watchFederationBuildCompletion(endpoint) {
162
- const eventSource = new EventSource(endpoint);
163
- eventSource.onmessage = function (event) {
164
- const data = JSON.parse(event.data);
165
- if (data.type === BuildNotificationType.COMPLETED) {
166
- console.log('[Federation] Rebuild completed, reloading...');
167
- window.location.reload();
168
- }
169
- };
170
- eventSource.onerror = function (event) {
171
- console.warn('[Federation] SSE connection error:', event);
172
- };
173
- }
174
-
175
- /**
176
- * Initializes the Native Federation runtime for the host application.
177
- *
178
- * This is the main entry point for setting up federation. It performs the following:
179
- * 1. Loads the host's remoteEntry.json to discover shared dependencies
180
- * 2. Loads each remote's remoteEntry.json to discover exposed modules
181
- * 3. Creates an ES Module import map with proper scoping
182
- * 4. Injects the import map into the DOM as a <script type="importmap-shim">
183
- *
184
- * The import map allows dynamic imports to resolve correctly:
185
- * - Host shared deps go in root imports (e.g., "angular": "./angular.js")
186
- * - Remote exposed modules go in root imports (e.g., "mfe1/Component": "http://...")
187
- * - Remote shared deps go in scoped imports for proper resolution
188
- *
189
- * @param remotesOrManifestUrl - Either:
190
- * - A record of remote names to their remoteEntry.json URLs
191
- * Example: { mfe1: 'http://localhost:3000/remoteEntry.json' }
192
- * - A URL to a manifest.json that contains the remotes record
193
- * Example: 'http://localhost:3000/federation-manifest.json'
194
- *
195
- * @param options - Configuration options:
196
- * - cacheTag: A version string to append as query param for cache busting
197
- * Example: { cacheTag: 'v1.0.0' } results in '?t=v1.0.0' on all requests
198
- *
199
- * @returns The final merged ImportMap that was injected into the DOM
200
- *
201
- */
202
- async function initFederation(remotesOrManifestUrl = {}, options) {
203
- const cacheTag = options?.cacheTag ? `?t=${options.cacheTag}` : '';
204
- const normalizedRemotes = typeof remotesOrManifestUrl === 'string'
205
- ? await loadManifest(remotesOrManifestUrl + cacheTag)
206
- : remotesOrManifestUrl;
207
- const hostInfo = await loadFederationInfo(`./remoteEntry.json${cacheTag}`);
208
- const hostImportMap = await processHostInfo(hostInfo);
209
- // Host application is fully loaded, now we can process the remotes
210
- // Each remote contributes:
211
- // - Exposed modules to root imports
212
- // - Shared dependencies to scoped imports
213
- const remotesImportMap = await processRemoteInfos(normalizedRemotes, {
214
- throwIfRemoteNotFound: false,
215
- ...options,
216
- });
217
- const mergedImportMap = mergeImportMaps(hostImportMap, remotesImportMap);
218
- // Inject the final import map into the DOM with importmap-shim
219
- appendImportMap(mergedImportMap);
220
- return mergedImportMap;
221
- }
222
- /**
223
- * Loads a federation manifest file (JSON) from the given URL.
224
- *
225
- * The manifest should map remote names to their remoteEntry.json URLs.
226
- *
227
- * @param manifestUrl - The URL to the manifest.json file.
228
- * @returns A promise resolving to an object mapping remote names to their remoteEntry.json URLs.
229
- */
230
- async function loadManifest(manifestUrl) {
231
- const manifest = (await fetch(manifestUrl).then((r) => r.json()));
232
- return manifest;
233
- }
234
- /**
235
- * Adds cache busting query parameter to a URL if cacheTag is provided.
236
- */
237
- function applyCacheTag(url, cacheTag) {
238
- if (!cacheTag)
239
- return url;
240
- const separator = url.includes('?') ? '&' : '?';
241
- return `${url}${separator}t=${cacheTag}`;
242
- }
243
- /**
244
- * Handles errors when loading a remote entry.
245
- * Either throws or logs based on options.
246
- */
247
- function handleRemoteLoadError(remoteName, remoteUrl, options, originalError) {
248
- const errorMessage = `Error loading remote entry for ${remoteName} from file ${remoteUrl}`;
249
- if (options.throwIfRemoteNotFound) {
250
- throw new Error(errorMessage);
251
- }
252
- console.error(errorMessage);
253
- console.error(originalError);
254
- return null;
255
- }
256
- /**
257
- * Fetches and registers multiple remote applications in parallel and merges their import maps.
258
- *
259
- * This function is the orchestrator for loading all remotes. It:
260
- * 1. Creates a promise for each remote to load its remoteEntry.json
261
- * 2. Applies cache busting to each remote URL
262
- * 3. Handles errors gracefully (logs or throws based on options)
263
- * 4. Merges all successful remote import maps into one
264
- *
265
- * Each remote contributes:
266
- * - Its exposed modules to the root imports
267
- * - Its shared dependencies to scoped imports
268
- *
269
- * @param remotes - Record of remote names to their remoteEntry.json URLs
270
- * @param options - Processing options including:
271
- * - throwIfRemoteNotFound: Whether to throw or log on remote load failure
272
- * - cacheTag: Cache busting tag to append to URLs
273
- *
274
- * @returns Merged import map containing all remotes' contributions
275
- *
276
- */
277
- async function processRemoteInfos(remotes, options = { throwIfRemoteNotFound: false }) {
278
- // Each promise will independently fetch and process its remoteEntry.json
279
- const fetchAndRegisterRemotePromises = Object.entries(remotes).map(async ([remoteName, remoteUrl]) => {
280
- try {
281
- const urlWithCache = applyCacheTag(remoteUrl, options.cacheTag);
282
- return await fetchAndRegisterRemote(urlWithCache, remoteName);
283
- }
284
- catch (e) {
285
- return handleRemoteLoadError(remoteName, remoteUrl, options, e);
286
- }
287
- });
288
- const remoteImportMaps = await Promise.all(fetchAndRegisterRemotePromises);
289
- // Filter out failed remotes (null values) and merge successful ones
290
- const importMap = remoteImportMaps.reduce((acc, remoteImportMap) => remoteImportMap ? mergeImportMaps(acc, remoteImportMap) : acc, { imports: {}, scopes: {} });
291
- return importMap;
292
- }
293
- /**
294
- * Fetches a single remote application's remoteEntry.json file and registers it in the system (global registry).
295
- *
296
- * This function handles everything needed to integrate one remote:
297
- * 1. Fetches the remote's remoteEntry.json file
298
- * 2. Extracts the base URL from the remoteEntry path
299
- * 3. Creates import map entries for exposed modules and shared deps
300
- * 4. Registers the remote in the global remotes registry
301
- * 5. Sets up hot reload watching if configured (development mode)
302
- *
303
- * @param federationInfoUrl - Full URL to the remote's remoteEntry.json
304
- * @param remoteName - Name to use for this remote (optional, uses info.name if not provided)
305
- *
306
- * @returns Import map containing this remote's exposed modules and shared dependencies
307
- *
308
- * @example
309
- * ```typescript
310
- * const importMap = await fetchAndRegisterRemote(
311
- * 'http://localhost:3000/mfe1/remoteEntry.json',
312
- * 'mfe1'
313
- * );
314
- * // Result: {
315
- * // imports: { 'mfe1/Component': 'http://localhost:3000/mfe1/Component.js' },
316
- * // scopes: { 'http://localhost:3000/mfe1/': { 'lodash': '...' } }
317
- * // }
318
- * ```
319
- */
320
- async function fetchAndRegisterRemote(federationInfoUrl, remoteName) {
321
- const baseUrl = getDirectory(federationInfoUrl);
322
- const remoteInfo = await loadFederationInfo(federationInfoUrl);
323
- // Uses the name from the remote's remoteEntry.json if not explicitly provided
324
- if (!remoteName) {
325
- remoteName = remoteInfo.name;
326
- }
327
- // Setup hot reload watching for development mode and in case it has a build notifications endpoint
328
- if (remoteInfo.buildNotificationsEndpoint) {
329
- watchFederationBuildCompletion(baseUrl + remoteInfo.buildNotificationsEndpoint);
330
- }
331
- const importMap = createRemoteImportMap(remoteInfo, remoteName, baseUrl);
332
- // Register this remote in the global registry
333
- addRemote(remoteName, { ...remoteInfo, baseUrl });
334
- return importMap;
335
- }
336
- /**
337
- * Creates an import map for a remote application.
338
- *
339
- * The import map has two parts:
340
- * 1. Imports (root level): Maps remote's exposed modules
341
- * Example: "mfe1/Component" -> "http://localhost:3000/mfe1/Component.js"
342
- *
343
- * 2. Scopes: Maps remote's shared dependencies within its scope
344
- * Example: "http://localhost:3000/mfe1/": { "lodash": "http://localhost:3000/mfe1/lodash.js" }
345
- *
346
- * Scoping ensures that when a module from this remote imports 'lodash',
347
- * it gets the version from this remote's bundle, not another version.
348
- *
349
- * @param remoteInfo - Federation info from the remote's remoteEntry.json
350
- * @param remoteName - Name used to prefix exposed module keys
351
- * @param baseUrl - Base URL where the remote is hosted
352
- *
353
- * @returns Import map with imports and scopes for this remote
354
- */
355
- function createRemoteImportMap(remoteInfo, remoteName, baseUrl) {
356
- const imports = processExposed(remoteInfo, remoteName, baseUrl);
357
- const scopes = processRemoteImports(remoteInfo, baseUrl);
358
- return { imports, scopes };
359
- }
360
- /**
361
- * Fetches and parses a remoteEntry.json file.
362
- *
363
- * The remoteEntry.json contains metadata about a federated module:
364
- * - name: The application name
365
- * - exposes: Array of modules this app exposes to others
366
- * - shared: Array of dependencies this app shares
367
- * - buildNotificationsEndpoint: Optional SSE endpoint for hot reload (development mode)
368
- *
369
- * @param remoteEntryUrl - URL to the remoteEntry.json file (can be relative or absolute)
370
- * @returns Parsed federation info object
371
- */
372
- async function loadFederationInfo(remoteEntryUrl) {
373
- const info = (await fetch(remoteEntryUrl).then((r) => r.json()));
374
- return info;
375
- }
376
- /**
377
- * Processes a remote's shared dependencies into scoped import map entries.
378
- *
379
- * Shared dependencies need to be scoped to avoid version conflicts.
380
- * When a module from "http://localhost:3000/mfe1/" imports "lodash",
381
- * the import map scope ensures it gets the correct version.
382
- *
383
- * Scope structure:
384
- * {
385
- * "http://localhost:3000/mfe1/": {
386
- * "lodash": "http://localhost:3000/mfe1/lodash.js",
387
- * "rxjs": "http://localhost:3000/mfe1/rxjs.js"
388
- * }
389
- * }
390
- *
391
- * This function also manages external URLs - if a shared dependency
392
- * has already been loaded from another location, it can reuse that URL.
393
- *
394
- * @param remoteInfo - Federation info containing shared dependencies
395
- * @param baseUrl - Base URL of the remote (used as the scope key)
396
- *
397
- * @returns Scopes object mapping baseUrl to its shared dependencies
398
- */
399
- function processRemoteImports(remoteInfo, baseUrl) {
400
- const scopes = {};
401
- const scopedImports = {};
402
- for (const shared of remoteInfo.shared) {
403
- // Check if this dependency already has an external URL registered
404
- // If not, construct the URL from the base path and output filename
405
- const outFileName = getExternalUrl(shared) ?? joinPaths(baseUrl, shared.outFileName);
406
- // Register this URL as the external location for this shared dependency
407
- // This allows other remotes to potentially reuse this version
408
- setExternalUrl(shared, outFileName);
409
- // Add to the scoped imports: package name -> full URL
410
- scopedImports[shared.packageName] = outFileName;
411
- }
412
- scopes[baseUrl + '/'] = scopedImports;
413
- return scopes;
414
- }
415
- /**
416
- * Processes a remote's exposed modules into root-level import map entries.
417
- *
418
- * Exposed modules are what the remote makes available to other applications.
419
- * They go in the root imports (not scoped) so any app can import them.
420
- *
421
- * Example exposed module:
422
- * - Remote 'mfe1' exposes './Component' from file 'Component.js'
423
- * - Results in: "mfe1/Component" -> "http://localhost:3000/mfe1/Component.js"
424
- *
425
- * This allows other apps to do:
426
- * ```typescript
427
- * import { Component } from 'mfe1/Component';
428
- * ```
429
- *
430
- * @param remoteInfo - Federation info containing exposed modules
431
- * @param remoteName - Name to prefix the exposed keys with
432
- * @param baseUrl - Base URL where the remote's files are hosted
433
- *
434
- * @returns Imports object mapping remote module keys to their URLs
435
- */
436
- function processExposed(remoteInfo, remoteName, baseUrl) {
437
- const imports = {};
438
- for (const exposed of remoteInfo.exposes) {
439
- // Create the import key by joining remote name with the exposed key
440
- // Example: 'mfe1' + './Component' -> 'mfe1/Component'
441
- const key = joinPaths(remoteName, exposed.key);
442
- // Create the full URL to the exposed module's output file
443
- // Example: 'http://localhost:3000/mfe1' + 'Component.js' -> 'http://localhost:3000/mfe1/Component.js'
444
- const value = joinPaths(baseUrl, exposed.outFileName);
445
- imports[key] = value;
446
- }
447
- return imports;
448
- }
449
- /**
450
- * Processes the host application's federation info into an import map.
451
- *
452
- * The host app typically doesn't expose modules (it's the consumer),
453
- * but it does share dependencies that should be available to remotes.
454
- *
455
- * Host shared dependencies go in root-level imports (not scoped) because:
456
- * 1. The host loads first and establishes the base environment
457
- * 2. Remotes should prefer host versions to avoid duplication
458
- *
459
- * @param hostInfo - Federation info from the host's remoteEntry.json
460
- * @param relBundlesPath - Relative path to the host's bundle directory (default: './')
461
- *
462
- * @returns Import map with host's shared dependencies in root imports
463
- */
464
- async function processHostInfo(hostInfo, relBundlesPath = './') {
465
- // Transform shared array into imports object
466
- const imports = hostInfo.shared.reduce((acc, cur) => ({
467
- ...acc,
468
- [cur.packageName]: relBundlesPath + cur.outFileName,
469
- }), {});
470
- // Register external URLs for host's shared dependencies
471
- // This allows remotes to discover and potentially reuse these versions
472
- for (const shared of hostInfo.shared) {
473
- setExternalUrl(shared, relBundlesPath + shared.outFileName);
474
- }
475
- // Host doesn't have scopes - its shared deps are at root level
476
- return { imports, scopes: {} };
477
- }
478
-
479
- /* eslint-disable @typescript-eslint/no-explicit-any */
480
- async function loadRemoteModule(optionsOrRemoteName, exposedModule) {
481
- const options = normalizeOptions(optionsOrRemoteName, exposedModule);
482
- await ensureRemoteInitialized(options);
483
- const remoteName = getRemoteNameByOptions(options);
484
- const remote = getRemote(remoteName);
485
- const fallback = options.fallback;
486
- // Handles errors when the remote is missing
487
- const remoteError = !remote ? 'unknown remote ' + remoteName : '';
488
- if (!remote && !fallback)
489
- throw new Error(remoteError);
490
- if (!remote) {
491
- logClientError(remoteError);
492
- return Promise.resolve(fallback);
493
- }
494
- const exposedModuleInfo = remote.exposes.find((e) => e.key === options.exposedModule);
495
- // Handles errors when the exposed module is missing
496
- const exposedError = !exposedModuleInfo
497
- ? `Unknown exposed module ${options.exposedModule} in remote ${remoteName}`
498
- : '';
499
- if (!exposedModuleInfo && !fallback)
500
- throw new Error(exposedError);
501
- if (!exposedModuleInfo) {
502
- logClientError(exposedError);
503
- return Promise.resolve(fallback);
504
- }
505
- const moduleUrl = joinPaths(remote.baseUrl, exposedModuleInfo.outFileName);
506
- try {
507
- const module = _import(moduleUrl);
508
- return module;
509
- }
510
- catch (e) {
511
- // Handles errors when the module import fails
512
- if (fallback) {
513
- console.error('error loading remote module', e);
514
- return fallback;
515
- }
516
- throw e;
517
- }
518
- }
519
- /**
520
- * Internal helper function to perform the dynamic import.
521
- *
522
- * @template T - The expected type of the module's exports
523
- * @param moduleUrl - Full URL to the module file to import
524
- * @returns Promise resolving to the imported module
525
- */
526
- function _import(moduleUrl) {
527
- return typeof importShim !== 'undefined'
528
- ? importShim(moduleUrl)
529
- : import(/* @vite-ignore */ moduleUrl);
530
- }
531
- /**
532
- * Resolves the remote name from the provided options.
533
- *
534
- * The remote name can be determined in two ways:
535
- * 1. If options.remoteName is provided, use it directly
536
- * 2. If only remoteEntry is provided, extract the baseUrl
537
- * and look up the remote name from the registry using that baseUrl
538
- *
539
- * @param options - Load options containing remoteName and/or remoteEntry
540
- * @returns The resolved remote name
541
- *
542
- * @throws Error if neither remoteName nor remoteEntry is provided
543
- * @throws Error if the remote name cannot be determined
544
- */
545
- function getRemoteNameByOptions(options) {
546
- let remoteName;
547
- if (options.remoteName) {
548
- remoteName = options.remoteName;
549
- }
550
- else if (options.remoteEntry) {
551
- const baseUrl = getDirectory(options.remoteEntry);
552
- remoteName = getRemoteNameByBaseUrl(baseUrl);
553
- }
554
- else {
555
- throw new Error('unexpected arguments: Please pass remoteName or remoteEntry');
556
- }
557
- if (!remoteName) {
558
- throw new Error('unknown remoteName ' + remoteName);
559
- }
560
- return remoteName;
561
- }
562
- /**
563
- * Ensures that the remote is initialized before attempting to load a module from it.
564
- *
565
- * This function enables lazy-loading of remotes that weren't registered during
566
- * the initial `initFederation()` call. It checks if:
567
- * 1. A remoteEntry URL is provided in the options
568
- * 2. The remote at that URL hasn't been initialized yet
569
- *
570
- * If both conditions are true, it:
571
- * 1. Fetches the remote's remoteEntry.json file
572
- * 2. Registers the remote in the global registry
573
- * 3. Creates and appends the remote's import map to the DOM
574
- *
575
- * @param options - Load options containing optional remoteEntry URL
576
- * @returns Promise that resolves when the remote is initialized (or immediately if already initialized)
577
- *
578
- */
579
- async function ensureRemoteInitialized(options) {
580
- if (options.remoteEntry &&
581
- !isRemoteInitialized(getDirectory(options.remoteEntry))) {
582
- const importMap = await fetchAndRegisterRemote(options.remoteEntry);
583
- appendImportMap(importMap);
584
- }
585
- }
586
- /**
587
- * Normalizes the function arguments into a standard LoadRemoteModuleOptions object.
588
- *
589
- * The function detects which pattern is being used and converts it to the
590
- * standard options object format for consistent internal processing.
591
- *
592
- * @param optionsOrRemoteName - Either an options object or the remote name string
593
- * @param exposedModule - The exposed module key
594
- * @returns Normalized options object
595
- *
596
- * @throws Error if arguments don't match either supported pattern
597
- */
598
- function normalizeOptions(optionsOrRemoteName, exposedModule) {
599
- let options;
600
- if (typeof optionsOrRemoteName === 'string' && exposedModule) {
601
- options = {
602
- remoteName: optionsOrRemoteName,
603
- exposedModule,
604
- };
605
- }
606
- else if (typeof optionsOrRemoteName === 'object' && !exposedModule) {
607
- options = optionsOrRemoteName;
608
- }
609
- else {
610
- throw new Error('unexpected arguments: please pass options or a remoteName/exposedModule-pair');
611
- }
612
- return options;
613
- }
614
- /**
615
- * Logs an error message to the console, but only in browser environments.
616
- *
617
- * @param error - The error message to log
618
- *
619
- */
620
- function logClientError(error) {
621
- if (typeof window !== 'undefined') {
622
- console.error(error);
623
- }
624
- }
625
-
626
- /**
627
- * Generated bundle index. Do not edit.
628
- */
629
-
630
- export { BUILD_NOTIFICATIONS_ENDPOINT, BuildNotificationType, fetchAndRegisterRemote, getShared, initFederation, loadRemoteModule, mergeImportMaps, processHostInfo, processRemoteInfos };
631
- //# sourceMappingURL=softarc-native-federation-runtime.mjs.map