@softarc/native-federation-orchestrator 4.2.0 → 4.2.1

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.
@@ -43,7 +43,7 @@ var cloneEntry = (name, raw) => {
43
43
  return JSON.parse(JSON.stringify(raw));
44
44
  } catch {
45
45
  }
46
- throw new NFError(`Could not parse storage entry '${String(name)}'`);
46
+ throw new NFError(`Could not clone entry '${String(name)}'`);
47
47
  };
48
48
 
49
49
  // src/lib/4.config/storage/global-this.storage.ts
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/2.app/config/log.contract.ts", "../../src/lib/4.config/logging/console.logger.ts", "../../src/lib/4.config/logging/noop.logger.ts", "../../src/lib/native-federation.error.ts", "../../src/lib/utils/clone-entry.ts", "../../src/lib/4.config/storage/global-this.storage.ts", "../../src/lib/4.config/storage/local.storage.ts", "../../src/lib/4.config/storage/session.storage.ts", "../../src/lib/4.config/import-map/trusted-types.ts", "../../src/lib/4.config/import-map/replace-in-dom.ts", "../../src/lib/4.config/import-map/use-import-shim.ts", "../../src/lib/4.config/import-map/use-default.ts", "../../src/lib/4.config/mode/default.profile.ts", "../../src/lib/4.config/mode/caching.profile.ts"],
4
- "sourcesContent": ["export const LogLevel = {\n debug: 0,\n warn: 1,\n error: 2,\n};\n\nexport type LogType = keyof typeof LogLevel;\n\nexport type Logger = {\n error: (step: number, msg: string, details?: unknown) => void;\n warn: (step: number, msg: string, details?: unknown) => void;\n debug: (step: number, msg: string, details?: unknown) => void;\n};\n\nexport type LogHandler = Logger & {\n level: LogType;\n};\n\nexport type LoggingConfig = {\n log: LogHandler;\n sse: boolean;\n};\n\nexport type LoggingOptions = {\n logger?: Logger;\n logLevel?: LogType;\n sse?: boolean;\n};\n", "import type { Logger } from 'lib/2.app/config/log.contract';\n\nconst consoleLogger: Logger = {\n /* eslint no-console: \"off\", curly: \"error\" */\n debug: (step: number, msg: string, err) =>\n !!err ? console.log(`[DEBUG][${step}]: ${msg}`, err) : console.log(`[DEBUG][${step}]: ${msg}`),\n error: (step: number, msg: string, err) =>\n !!err ? console.error(`[NF][${step}]: ${msg}`, err) : console.error(`[NF][${step}]: ${msg}`),\n warn: (step: number, msg: string, err) =>\n !!err ? console.warn(`[NF][${step}]: ${msg}`, err) : console.warn(`[NF][${step}]: ${msg}`),\n};\n\nexport { consoleLogger };\n", "import type { Logger } from 'lib/2.app/config/log.contract';\n\nconst noopLogger: Logger = {\n debug: () => {},\n error: () => {},\n warn: () => {},\n};\n\nexport { noopLogger };\n", "class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "import type { StorageEntryKey } from 'lib/2.app/config/storage.contract';\nimport { NFError } from 'lib/native-federation.error';\n\ntype CloneEntry = <T>(name: StorageEntryKey, raw: T) => T;\n\nconst cloneEntry: CloneEntry = <T>(name: StorageEntryKey, raw: T) => {\n try {\n if (typeof structuredClone === 'function') {\n return structuredClone(raw);\n }\n } catch {\n /* structured clone is unavailable */\n }\n try {\n return JSON.parse(JSON.stringify(raw));\n } catch {\n /* object is not stringifyable */\n }\n throw new NFError(`Could not parse storage entry '${String(name)}'`);\n};\n\nexport { CloneEntry, cloneEntry };\n", "import { cloneEntry } from '../../utils/clone-entry';\nimport { type StorageEntryCreator, type StorageEntry } from 'lib/2.app/config/storage.contract';\n\nconst globalThisStorageEntry: StorageEntryCreator =\n (namespace: string) =>\n <TValue>(key: string, initialValue: TValue) => {\n if (!(globalThis as unknown as { [namespace]: unknown })[namespace]) {\n (globalThis as unknown as { [namespace]: unknown })[namespace] = {};\n }\n\n const storage = (globalThis as unknown as { [namespace]: { [P in typeof key]: TValue } })[\n namespace\n ]!;\n if (!storage[key]) storage[key] = initialValue;\n\n const entry: StorageEntry<TValue> = {\n get(): TValue {\n return cloneEntry(key, storage[key])!;\n },\n set(value: TValue): StorageEntry<TValue> {\n storage[key] = cloneEntry(key, value);\n return entry;\n },\n clear(): StorageEntry<TValue> {\n storage[key] = cloneEntry(key, initialValue);\n return this;\n },\n };\n\n return entry;\n };\n\nexport { globalThisStorageEntry };\n", "import type { StorageEntryCreator, StorageEntry } from 'lib/2.app/config/storage.contract';\n\nconst localStorageEntry: StorageEntryCreator =\n (namespace: string) =>\n <TValue>(key: string, initialValue: TValue) => {\n if (!localStorage.getItem(`${namespace}.${String(key)}`)) {\n localStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n }\n const entry: StorageEntry<TValue> = {\n get() {\n const fromCache = localStorage.getItem(`${namespace}.${String(key)}`);\n if (!fromCache) return undefined;\n return JSON.parse(fromCache);\n },\n set(value: TValue): StorageEntry<TValue> {\n localStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(value));\n return entry;\n },\n clear(): StorageEntry<TValue> {\n localStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n return this;\n },\n };\n return entry;\n };\n\nexport { localStorageEntry };\n", "import type { StorageEntryCreator, StorageEntry } from 'lib/2.app/config/storage.contract';\n\nconst sessionStorageEntry: StorageEntryCreator =\n (namespace: string) =>\n <TValue>(key: string, initialValue: TValue) => {\n if (!sessionStorage.getItem(`${namespace}.${String(key)}`)) {\n sessionStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n }\n const entry: StorageEntry<TValue> = {\n get() {\n const fromCache = sessionStorage.getItem(`${namespace}.${String(key)}`);\n if (!fromCache) return undefined;\n return JSON.parse(fromCache);\n },\n set(value: TValue): StorageEntry<TValue> {\n sessionStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(value));\n return entry;\n },\n clear(): StorageEntry<TValue> {\n sessionStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n return this;\n },\n };\n return entry;\n };\n\nexport { sessionStorageEntry };\n", "type TTCreateScript = (input: string) => string;\ntype TTCreateScriptURL = (input: string) => string;\n\ntype TTPolicyRules = {\n createScript?: TTCreateScript;\n createScriptURL?: TTCreateScriptURL;\n};\n\ntype TTPolicy = {\n createScript: TTCreateScript;\n createScriptURL: TTCreateScriptURL;\n};\n\ntype TTFactory = {\n createPolicy: (name: string, rules: TTPolicyRules) => TTPolicy;\n};\n\nexport type NFTrustedTypesPolicy = {\n createScript: (input: string) => string;\n createScriptURL: (input: string) => string;\n};\n\nconst IMPORT_MAP_KEYS = new Set(['imports', 'scopes', 'integrity']);\n\nconst validateImportMapJSON = (input: string): string => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n throw new TypeError('[nf-orchestrator] trusted-types: import map is not valid JSON');\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new TypeError('[nf-orchestrator] trusted-types: import map must be a plain object');\n }\n for (const key of Object.keys(parsed as Record<string, unknown>)) {\n if (!IMPORT_MAP_KEYS.has(key)) {\n throw new TypeError(`[nf-orchestrator] trusted-types: unexpected key \"${key}\" in import map`);\n }\n }\n return input;\n};\n\nconst validateScriptURL = (input: string): string => {\n const base = typeof location !== 'undefined' ? location.href : 'http://localhost/';\n let url: URL;\n try {\n url = new URL(input, base);\n } catch {\n throw new TypeError(`[nf-orchestrator] trusted-types: invalid script URL \"${input}\"`);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new TypeError(\n `[nf-orchestrator] trusted-types: disallowed protocol \"${url.protocol}\" for script URL`\n );\n }\n return input;\n};\n\nconst passThroughPolicy: NFTrustedTypesPolicy = {\n createScript: input => input,\n createScriptURL: input => input,\n};\n\nlet cachedPolicy: NFTrustedTypesPolicy | null = null;\n\nexport const getTrustedTypesPolicy = (\n name: string | false = 'nfo'\n): NFTrustedTypesPolicy => {\n if (name === false) return passThroughPolicy;\n if (cachedPolicy) return cachedPolicy;\n\n const factory = (globalThis as { trustedTypes?: TTFactory }).trustedTypes;\n if (!factory) {\n cachedPolicy = passThroughPolicy;\n return cachedPolicy;\n }\n\n const native = factory.createPolicy(name, {\n createScript: validateImportMapJSON,\n createScriptURL: validateScriptURL,\n });\n\n cachedPolicy = {\n createScript: input => native.createScript(input) as unknown as string,\n createScriptURL: input => native.createScriptURL(input) as unknown as string,\n };\n return cachedPolicy;\n};\n\nexport const __resetTrustedTypesPolicyForTests = (): void => {\n cachedPolicy = null;\n};\n", "import type { ImportMap } from 'lib/1.domain';\nimport type { SetImportMap } from 'lib/2.app/config/import-map.contract';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\nexport const replaceInDOM =\n (mapType: string, trustedTypesPolicyName: string | false = 'nfo'): SetImportMap =>\n (importMap: ImportMap, opts = {}) => {\n if (opts?.override) {\n document.head\n .querySelectorAll(`script[type=\"${mapType}\"]`)\n .forEach(importMap => importMap.remove());\n }\n\n const policy = getTrustedTypesPolicy(trustedTypesPolicyName);\n document.head.appendChild(\n Object.assign(document.createElement('script'), {\n type: mapType,\n text: policy.createScript(JSON.stringify(importMap)),\n })\n );\n return Promise.resolve(importMap);\n };\n", "import type { ImportMapConfig } from 'lib/2.app/config/import-map.contract';\nimport { replaceInDOM } from './replace-in-dom';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\ndeclare function importShim<T>(url: string): T;\n\nconst useShimImportMap = (\n cfg: { shimMode: boolean } = { shimMode: false },\n trustedTypesPolicyName: string | false = 'nfo'\n): ImportMapConfig => ({\n loadModuleFn: url => {\n const trusted = getTrustedTypesPolicy(trustedTypesPolicyName).createScriptURL(url);\n return importShim(String(trusted));\n },\n setImportMapFn: replaceInDOM(\n cfg.shimMode ? 'importmap-shim' : 'importmap',\n trustedTypesPolicyName\n ),\n reloadBrowserFn: () => {\n window.location.reload();\n },\n});\n\nexport { useShimImportMap };\n", "import type { ImportMapConfig } from 'lib/2.app/config/import-map.contract';\nimport { replaceInDOM } from './replace-in-dom';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\nconst useDefaultImportMap = (\n trustedTypesPolicyName: string | false = 'nfo'\n): ImportMapConfig => ({\n loadModuleFn: url => {\n const trusted = getTrustedTypesPolicy(trustedTypesPolicyName).createScriptURL(url);\n return import(/* @vite-ignore */ trusted);\n },\n setImportMapFn: replaceInDOM('importmap', trustedTypesPolicyName),\n reloadBrowserFn: () => {\n window.location.reload();\n },\n});\n\nexport { useDefaultImportMap };\n", "import type { ModeProfileConfig } from 'lib/2.app/config/mode.contract';\n\nexport const defaultProfile: ModeProfileConfig = {\n latestSharedExternal: false,\n overrideCachedRemotes: 'init-only',\n overrideCachedRemotesIfURLMatches: false,\n};\n", "import type { ModeProfileConfig } from 'lib/2.app/config/mode.contract';\n\nexport const cachingProfile: ModeProfileConfig = {\n latestSharedExternal: false,\n overrideCachedRemotes: 'never',\n overrideCachedRemotesIfURLMatches: false,\n};\n"],
5
- "mappings": ";AAAO,IAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AACT;;;ACFA,IAAM,gBAAwB;AAAA;AAAA,EAE5B,OAAO,CAAC,MAAc,KAAa,QACjC,CAAC,CAAC,MAAM,QAAQ,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,GAAG,IAAI,QAAQ,IAAI,WAAW,IAAI,MAAM,GAAG,EAAE;AAAA,EAC/F,OAAO,CAAC,MAAc,KAAa,QACjC,CAAC,CAAC,MAAM,QAAQ,MAAM,QAAQ,IAAI,MAAM,GAAG,IAAI,GAAG,IAAI,QAAQ,MAAM,QAAQ,IAAI,MAAM,GAAG,EAAE;AAAA,EAC7F,MAAM,CAAC,MAAc,KAAa,QAChC,CAAC,CAAC,MAAM,QAAQ,KAAK,QAAQ,IAAI,MAAM,GAAG,IAAI,GAAG,IAAI,QAAQ,KAAK,QAAQ,IAAI,MAAM,GAAG,EAAE;AAC7F;;;ACRA,IAAM,aAAqB;AAAA,EACzB,OAAO,MAAM;AAAA,EAAC;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAAA,EACd,MAAM,MAAM;AAAA,EAAC;AACf;;;ACNA,IAAM,UAAN,cAAsB,MAAM;AAAA,EAC1B,YAAY,SAAiB,O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cesContent": ["export const LogLevel = {\n debug: 0,\n warn: 1,\n error: 2,\n};\n\nexport type LogType = keyof typeof LogLevel;\n\nexport type Logger = {\n error: (step: number, msg: string, details?: unknown) => void;\n warn: (step: number, msg: string, details?: unknown) => void;\n debug: (step: number, msg: string, details?: unknown) => void;\n};\n\nexport type LogHandler = Logger & {\n level: LogType;\n};\n\nexport type LoggingConfig = {\n log: LogHandler;\n sse: boolean;\n};\n\nexport type LoggingOptions = {\n logger?: Logger;\n logLevel?: LogType;\n sse?: boolean;\n};\n", "import type { Logger } from 'lib/2.app/config/log.contract';\n\nconst consoleLogger: Logger = {\n /* eslint no-console: \"off\", curly: \"error\" */\n debug: (step: number, msg: string, err) =>\n !!err ? console.log(`[DEBUG][${step}]: ${msg}`, err) : console.log(`[DEBUG][${step}]: ${msg}`),\n error: (step: number, msg: string, err) =>\n !!err ? console.error(`[NF][${step}]: ${msg}`, err) : console.error(`[NF][${step}]: ${msg}`),\n warn: (step: number, msg: string, err) =>\n !!err ? console.warn(`[NF][${step}]: ${msg}`, err) : console.warn(`[NF][${step}]: ${msg}`),\n};\n\nexport { consoleLogger };\n", "import type { Logger } from 'lib/2.app/config/log.contract';\n\nconst noopLogger: Logger = {\n debug: () => {},\n error: () => {},\n warn: () => {},\n};\n\nexport { noopLogger };\n", "class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "import type { StorageEntryKey } from 'lib/2.app/config/storage.contract';\nimport { NFError } from 'lib/native-federation.error';\n\ntype CloneEntry = <T>(name: StorageEntryKey, raw: T) => T;\n\nconst cloneEntry: CloneEntry = <T>(name: StorageEntryKey, raw: T) => {\n try {\n if (typeof structuredClone === 'function') {\n return structuredClone(raw);\n }\n } catch {\n /* structured clone is unavailable */\n }\n try {\n return JSON.parse(JSON.stringify(raw));\n } catch {\n /* object is not stringifyable */\n }\n throw new NFError(`Could not clone entry '${String(name)}'`);\n};\n\nexport { CloneEntry, cloneEntry };\n", "import { cloneEntry } from '../../utils/clone-entry';\nimport { type StorageEntryCreator, type StorageEntry } from 'lib/2.app/config/storage.contract';\n\nconst globalThisStorageEntry: StorageEntryCreator =\n (namespace: string) =>\n <TValue>(key: string, initialValue: TValue) => {\n if (!(globalThis as unknown as { [namespace]: unknown })[namespace]) {\n (globalThis as unknown as { [namespace]: unknown })[namespace] = {};\n }\n\n const storage = (globalThis as unknown as { [namespace]: { [P in typeof key]: TValue } })[\n namespace\n ]!;\n if (!storage[key]) storage[key] = initialValue;\n\n const entry: StorageEntry<TValue> = {\n get(): TValue {\n return cloneEntry(key, storage[key])!;\n },\n set(value: TValue): StorageEntry<TValue> {\n storage[key] = cloneEntry(key, value);\n return entry;\n },\n clear(): StorageEntry<TValue> {\n storage[key] = cloneEntry(key, initialValue);\n return this;\n },\n };\n\n return entry;\n };\n\nexport { globalThisStorageEntry };\n", "import type { StorageEntryCreator, StorageEntry } from 'lib/2.app/config/storage.contract';\n\nconst localStorageEntry: StorageEntryCreator =\n (namespace: string) =>\n <TValue>(key: string, initialValue: TValue) => {\n if (!localStorage.getItem(`${namespace}.${String(key)}`)) {\n localStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n }\n const entry: StorageEntry<TValue> = {\n get() {\n const fromCache = localStorage.getItem(`${namespace}.${String(key)}`);\n if (!fromCache) return undefined;\n return JSON.parse(fromCache);\n },\n set(value: TValue): StorageEntry<TValue> {\n localStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(value));\n return entry;\n },\n clear(): StorageEntry<TValue> {\n localStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n return this;\n },\n };\n return entry;\n };\n\nexport { localStorageEntry };\n", "import type { StorageEntryCreator, StorageEntry } from 'lib/2.app/config/storage.contract';\n\nconst sessionStorageEntry: StorageEntryCreator =\n (namespace: string) =>\n <TValue>(key: string, initialValue: TValue) => {\n if (!sessionStorage.getItem(`${namespace}.${String(key)}`)) {\n sessionStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n }\n const entry: StorageEntry<TValue> = {\n get() {\n const fromCache = sessionStorage.getItem(`${namespace}.${String(key)}`);\n if (!fromCache) return undefined;\n return JSON.parse(fromCache);\n },\n set(value: TValue): StorageEntry<TValue> {\n sessionStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(value));\n return entry;\n },\n clear(): StorageEntry<TValue> {\n sessionStorage.setItem(`${namespace}.${String(key)}`, JSON.stringify(initialValue));\n return this;\n },\n };\n return entry;\n };\n\nexport { sessionStorageEntry };\n", "type TTCreateScript = (input: string) => string;\ntype TTCreateScriptURL = (input: string) => string;\n\ntype TTPolicyRules = {\n createScript?: TTCreateScript;\n createScriptURL?: TTCreateScriptURL;\n};\n\ntype TTPolicy = {\n createScript: TTCreateScript;\n createScriptURL: TTCreateScriptURL;\n};\n\ntype TTFactory = {\n createPolicy: (name: string, rules: TTPolicyRules) => TTPolicy;\n};\n\nexport type NFTrustedTypesPolicy = {\n createScript: (input: string) => string;\n createScriptURL: (input: string) => string;\n};\n\nconst IMPORT_MAP_KEYS = new Set(['imports', 'scopes', 'integrity']);\n\nconst validateImportMapJSON = (input: string): string => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n throw new TypeError('[nf-orchestrator] trusted-types: import map is not valid JSON');\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new TypeError('[nf-orchestrator] trusted-types: import map must be a plain object');\n }\n for (const key of Object.keys(parsed as Record<string, unknown>)) {\n if (!IMPORT_MAP_KEYS.has(key)) {\n throw new TypeError(`[nf-orchestrator] trusted-types: unexpected key \"${key}\" in import map`);\n }\n }\n return input;\n};\n\nconst validateScriptURL = (input: string): string => {\n const base = typeof location !== 'undefined' ? location.href : 'http://localhost/';\n let url: URL;\n try {\n url = new URL(input, base);\n } catch {\n throw new TypeError(`[nf-orchestrator] trusted-types: invalid script URL \"${input}\"`);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new TypeError(\n `[nf-orchestrator] trusted-types: disallowed protocol \"${url.protocol}\" for script URL`\n );\n }\n return input;\n};\n\nconst passThroughPolicy: NFTrustedTypesPolicy = {\n createScript: input => input,\n createScriptURL: input => input,\n};\n\nlet cachedPolicy: NFTrustedTypesPolicy | null = null;\n\nexport const getTrustedTypesPolicy = (\n name: string | false = 'nfo'\n): NFTrustedTypesPolicy => {\n if (name === false) return passThroughPolicy;\n if (cachedPolicy) return cachedPolicy;\n\n const factory = (globalThis as { trustedTypes?: TTFactory }).trustedTypes;\n if (!factory) {\n cachedPolicy = passThroughPolicy;\n return cachedPolicy;\n }\n\n const native = factory.createPolicy(name, {\n createScript: validateImportMapJSON,\n createScriptURL: validateScriptURL,\n });\n\n cachedPolicy = {\n createScript: input => native.createScript(input) as unknown as string,\n createScriptURL: input => native.createScriptURL(input) as unknown as string,\n };\n return cachedPolicy;\n};\n\nexport const __resetTrustedTypesPolicyForTests = (): void => {\n cachedPolicy = null;\n};\n", "import type { ImportMap } from 'lib/1.domain';\nimport type { SetImportMap } from 'lib/2.app/config/import-map.contract';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\nexport const replaceInDOM =\n (mapType: string, trustedTypesPolicyName: string | false = 'nfo'): SetImportMap =>\n (importMap: ImportMap, opts = {}) => {\n if (opts?.override) {\n document.head\n .querySelectorAll(`script[type=\"${mapType}\"]`)\n .forEach(importMap => importMap.remove());\n }\n\n const policy = getTrustedTypesPolicy(trustedTypesPolicyName);\n document.head.appendChild(\n Object.assign(document.createElement('script'), {\n type: mapType,\n text: policy.createScript(JSON.stringify(importMap)),\n })\n );\n return Promise.resolve(importMap);\n };\n", "import type { ImportMapConfig } from 'lib/2.app/config/import-map.contract';\nimport { replaceInDOM } from './replace-in-dom';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\ndeclare function importShim<T>(url: string): T;\n\nconst useShimImportMap = (\n cfg: { shimMode: boolean } = { shimMode: false },\n trustedTypesPolicyName: string | false = 'nfo'\n): ImportMapConfig => ({\n loadModuleFn: url => {\n const trusted = getTrustedTypesPolicy(trustedTypesPolicyName).createScriptURL(url);\n return importShim(String(trusted));\n },\n setImportMapFn: replaceInDOM(\n cfg.shimMode ? 'importmap-shim' : 'importmap',\n trustedTypesPolicyName\n ),\n reloadBrowserFn: () => {\n window.location.reload();\n },\n});\n\nexport { useShimImportMap };\n", "import type { ImportMapConfig } from 'lib/2.app/config/import-map.contract';\nimport { replaceInDOM } from './replace-in-dom';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\nconst useDefaultImportMap = (\n trustedTypesPolicyName: string | false = 'nfo'\n): ImportMapConfig => ({\n loadModuleFn: url => {\n const trusted = getTrustedTypesPolicy(trustedTypesPolicyName).createScriptURL(url);\n return import(/* @vite-ignore */ trusted);\n },\n setImportMapFn: replaceInDOM('importmap', trustedTypesPolicyName),\n reloadBrowserFn: () => {\n window.location.reload();\n },\n});\n\nexport { useDefaultImportMap };\n", "import type { ModeProfileConfig } from 'lib/2.app/config/mode.contract';\n\nexport const defaultProfile: ModeProfileConfig = {\n latestSharedExternal: false,\n overrideCachedRemotes: 'init-only',\n overrideCachedRemotesIfURLMatches: false,\n};\n", "import type { ModeProfileConfig } from 'lib/2.app/config/mode.contract';\n\nexport const cachingProfile: ModeProfileConfig = {\n latestSharedExternal: false,\n overrideCachedRemotes: 'never',\n overrideCachedRemotesIfURLMatches: false,\n};\n"],
5
+ "mappings": ";AAAO,IAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AACT;;;ACFA,IAAM,gBAAwB;AAAA;AAAA,EAE5B,OAAO,CAAC,MAAc,KAAa,QACjC,CAAC,CAAC,MAAM,QAAQ,IAAI,WAAW,IAAI,MAAM,GAAG,IAAI,GAAG,IAAI,QAAQ,IAAI,WAAW,IAAI,MAAM,GAAG,EAAE;AAAA,EAC/F,OAAO,CAAC,MAAc,KAAa,QACjC,CAAC,CAAC,MAAM,QAAQ,MAAM,QAAQ,I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yBAAyC,WACpB;AAAA,EACrB,cAAc,SAAO;AACnB,UAAM,UAAU,sBAAsB,sBAAsB,EAAE,gBAAgB,GAAG;AACjF,WAAO;AAAA;AAAA,MAA0B;AAAA;AAAA,EACnC;AAAA,EACA,gBAAgB,aAAa,aAAa,sBAAsB;AAAA,EAChE,iBAAiB,MAAM;AACrB,WAAO,SAAS,OAAO;AAAA,EACzB;AACF;;;ACbO,IAAM,iBAAoC;AAAA,EAC/C,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,mCAAmC;AACrC;;;ACJO,IAAM,iBAAoC;AAAA,EAC/C,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,mCAAmC;AACrC;",
6
6
  "names": ["importMap"]
7
7
  }
@@ -1,11 +1,66 @@
1
+ // src/lib/native-federation.error.ts
2
+ var NFError = class extends Error {
3
+ constructor(message, cause) {
4
+ super(message, cause);
5
+ this.name = "NFError";
6
+ }
7
+ };
8
+
9
+ // src/lib/utils/clone-entry.ts
10
+ var cloneEntry = (name, raw) => {
11
+ try {
12
+ if (typeof structuredClone === "function") {
13
+ return structuredClone(raw);
14
+ }
15
+ } catch {
16
+ }
17
+ try {
18
+ return JSON.parse(JSON.stringify(raw));
19
+ } catch {
20
+ }
21
+ throw new NFError(`Could not clone entry '${String(name)}'`);
22
+ };
23
+
1
24
  // src/lib/2.app/flows/registry/setup-registry.ts
2
25
  function createRegistry(opts) {
26
+ const cfg = {
27
+ maxStreams: opts.maxStreams,
28
+ maxEvents: opts.maxEvents ?? 1,
29
+ removePercentage: opts.removePercentage
30
+ };
3
31
  const resources = /* @__PURE__ */ new Map();
4
32
  const pending = /* @__PURE__ */ new Map();
5
33
  const events = /* @__PURE__ */ new Map();
6
34
  const listeners = /* @__PURE__ */ new Map();
7
- const recentlyUsedEvents = /* @__PURE__ */ new Set();
8
- const REMOVE_EVENTS = Math.ceil(opts.maxEvents * opts.removePercentage);
35
+ const recentlyUsedStreams = /* @__PURE__ */ new Set();
36
+ const REMOVE_EVENTS = Math.min(
37
+ cfg.maxEvents - 1,
38
+ cfg.removePercentage ? Math.ceil(cfg.maxEvents * cfg.removePercentage) : 1
39
+ );
40
+ const touchStream = (type) => {
41
+ if (!cfg.maxStreams) return;
42
+ recentlyUsedStreams.delete(type);
43
+ recentlyUsedStreams.add(type);
44
+ if (recentlyUsedStreams.size > cfg.maxStreams) {
45
+ const oldest = recentlyUsedStreams.values().next().value;
46
+ if (oldest) {
47
+ recentlyUsedStreams.delete(oldest);
48
+ events.delete(oldest);
49
+ }
50
+ }
51
+ };
52
+ const appendAndNotify = (type, event) => {
53
+ let history = events.get(type) ?? [];
54
+ history.push(event);
55
+ if (history.length > cfg.maxEvents) {
56
+ history = history.slice(-(cfg.maxEvents - REMOVE_EVENTS));
57
+ }
58
+ events.set(type, history);
59
+ const typeListeners = listeners.get(type);
60
+ if (typeListeners && typeListeners.size > 0) {
61
+ typeListeners.forEach((listener) => listener(event));
62
+ }
63
+ };
9
64
  const register = async (type, resource) => {
10
65
  const value = typeof resource === "function" ? await resource() : resource;
11
66
  resources.set(type, value);
@@ -35,18 +90,21 @@ function createRegistry(opts) {
35
90
  }
36
91
  };
37
92
  };
38
- const on = (type, callback) => {
93
+ const on = (type, callback, opts2 = {}) => {
94
+ const replay = opts2.replay ?? 1;
39
95
  const history = events.get(type);
40
- const historyCopy = history ? [...history] : null;
41
96
  let typeListeners = listeners.get(type);
42
97
  if (!typeListeners) {
43
98
  typeListeners = /* @__PURE__ */ new Set();
44
99
  listeners.set(type, typeListeners);
45
100
  }
46
101
  typeListeners.add(callback);
47
- if (historyCopy && historyCopy.length > 0) {
102
+ if (history && history.length > 0 && replay > 0) {
48
103
  queueMicrotask(() => {
49
- historyCopy.forEach((event) => callback(event));
104
+ const start = Math.max(0, history.length - replay);
105
+ for (let i = start; i < history.length; i++) {
106
+ callback(cloneEntry("event channel " + type, history[i]));
107
+ }
50
108
  });
51
109
  }
52
110
  return () => {
@@ -57,29 +115,18 @@ function createRegistry(opts) {
57
115
  };
58
116
  };
59
117
  const emit = (type, data) => {
60
- const event = {
61
- data,
118
+ touchStream(type);
119
+ appendAndNotify(type, { data, timestamp: Date.now() });
120
+ };
121
+ const update = (type, updateFn) => {
122
+ touchStream(type);
123
+ const history = events.get(type) ?? [];
124
+ const lastEvent = history[history.length - 1];
125
+ const current = lastEvent === void 0 ? void 0 : cloneEntry("event channel " + type, lastEvent.data);
126
+ appendAndNotify(type, {
127
+ data: updateFn(current),
62
128
  timestamp: Date.now()
63
- };
64
- recentlyUsedEvents.delete(type);
65
- recentlyUsedEvents.add(type);
66
- if (recentlyUsedEvents.size > opts.maxStreams) {
67
- const oldest = recentlyUsedEvents.values().next().value;
68
- if (oldest) {
69
- recentlyUsedEvents.delete(oldest);
70
- events.delete(oldest);
71
- }
72
- }
73
- let history = events.get(type) || [];
74
- history.push(event);
75
- if (history.length > opts.maxEvents) {
76
- history = history.slice(-(opts.maxEvents - REMOVE_EVENTS));
77
- }
78
- events.set(type, history);
79
- const typeListeners = listeners.get(type);
80
- if (typeListeners && typeListeners.size > 0) {
81
- typeListeners.forEach((listener) => listener(event));
82
- }
129
+ });
83
130
  };
84
131
  const clear = (type) => {
85
132
  if (type) {
@@ -87,19 +134,20 @@ function createRegistry(opts) {
87
134
  listeners.delete(type);
88
135
  resources.delete(type);
89
136
  pending.delete(type);
90
- recentlyUsedEvents.delete(type);
137
+ recentlyUsedStreams.delete(type);
91
138
  } else {
92
139
  events.clear();
93
140
  listeners.clear();
94
141
  pending.clear();
95
142
  resources.clear();
96
- recentlyUsedEvents.clear();
143
+ recentlyUsedStreams.clear();
97
144
  }
98
145
  };
99
146
  return () => ({
100
147
  register,
101
148
  onReady,
102
149
  emit,
150
+ update,
103
151
  on,
104
152
  clear
105
153
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/lib/2.app/flows/registry/setup-registry.ts"],
4
- "sourcesContent": ["import type {\n NFEventConsumer,\n NFEventData,\n NFEventProvider,\n NFEventUnsubscribe,\n} from '../../../1.domain/registry/event.contract';\nimport type { ForManagingEvents } from 'lib/2.app/driver-ports/registry/for-managing-events.port';\nimport type { NFEventRegistryConfig } from 'lib/2.app/config/registry.contract';\n\nexport function createRegistry(opts: NFEventRegistryConfig): ForManagingEvents {\n // resources\n const resources = new Map<string, unknown>();\n const pending = new Map<string, Set<NFEventConsumer<any>>>();\n\n // events\n const events = new Map<string, NFEventData[]>();\n const listeners = new Map<string, Set<NFEventConsumer<NFEventData<any>>>>();\n const recentlyUsedEvents = new Set<string>();\n\n const REMOVE_EVENTS = Math.ceil(opts.maxEvents * opts.removePercentage);\n\n /**\n * RESOURCE: Register a resource by name. If the resource is a provider function, it is\n * invoked to obtain the actual resource. All callbacks waiting for this\n * resource via `onReady` are invoked once the resource is registered.\n */\n const register = async <T>(type: string, resource: T | NFEventProvider<T>): Promise<void> => {\n const value =\n typeof resource === 'function' ? await (resource as NFEventProvider<T>)() : resource;\n\n resources.set(type, value);\n\n const callbacks = pending.get(type);\n if (callbacks) {\n pending.delete(type);\n callbacks.forEach(cb => cb(value));\n }\n };\n\n /**\n * RESOURCE: Subscribe to the readiness of a resource. If the resource is already\n * registered, the callback is invoked immediately. Otherwise, the callback\n * is invoked once the resource is registered.\n */\n const onReady = <T>(type: string, callback: NFEventConsumer<T>): NFEventUnsubscribe => {\n const existing = resources.get(type);\n if (existing !== undefined) {\n callback(existing as T);\n return () => {};\n }\n\n let callbacks = pending.get(type);\n if (!callbacks) {\n callbacks = new Set();\n pending.set(type, callbacks);\n }\n callbacks.add(callback);\n\n return () => {\n callbacks!.delete(callback);\n if (callbacks!.size === 0) {\n pending.delete(type);\n }\n };\n };\n\n /**\n * EVENT: Subscribe to events of a specific type. The callback is invoked for all\n * past events of that type, and for all future events.\n */\n const on = <T>(type: string, callback: NFEventConsumer<NFEventData<T>>): NFEventUnsubscribe => {\n const history = events.get(type);\n const historyCopy = history ? [...history] : null;\n\n let typeListeners = listeners.get(type);\n if (!typeListeners) {\n typeListeners = new Set();\n listeners.set(type, typeListeners);\n }\n typeListeners.add(callback);\n\n if (historyCopy && historyCopy.length > 0) {\n queueMicrotask(() => {\n historyCopy.forEach(event => callback(event));\n });\n }\n\n return () => {\n typeListeners!.delete(callback);\n if (typeListeners!.size === 0) {\n listeners.delete(type);\n }\n };\n };\n\n /**\n * Emit an event of a specific type with associated data. The event is stored\n * in the history for that type, and all listeners subscribed to that type are\n * invoked with the new event. If the number of stored events exceeds\n * the maximum, the oldest events are removed based on the configured\n * removal percentage. If the number of event types exceeds the maximum,\n * the oldest event type and its history are removed.\n */\n const emit = <T>(type: string, data: T): void => {\n const event: NFEventData<T> = {\n data,\n timestamp: Date.now(),\n };\n\n recentlyUsedEvents.delete(type);\n recentlyUsedEvents.add(type);\n\n if (recentlyUsedEvents.size > opts.maxStreams) {\n const oldest = recentlyUsedEvents.values().next().value;\n if (oldest) {\n recentlyUsedEvents.delete(oldest);\n events.delete(oldest);\n }\n }\n\n let history = events.get(type) || [];\n history.push(event);\n\n if (history.length > opts.maxEvents) {\n history = history.slice(-(opts.maxEvents - REMOVE_EVENTS));\n }\n\n events.set(type, history);\n\n const typeListeners = listeners.get(type);\n if (typeListeners && typeListeners.size > 0) {\n typeListeners.forEach(listener => listener(event));\n }\n };\n\n const clear = (type?: string): void => {\n if (type) {\n // Clear event-related data\n events.delete(type);\n listeners.delete(type);\n\n // Clear resource-related data\n resources.delete(type);\n pending.delete(type);\n\n recentlyUsedEvents.delete(type);\n } else {\n // Clear all data\n events.clear();\n listeners.clear();\n pending.clear();\n resources.clear();\n recentlyUsedEvents.clear();\n }\n };\n\n return () => ({\n register,\n onReady,\n emit,\n on,\n clear,\n });\n}\n"],
5
- "mappings": ";AASO,SAAS,eAAe,MAAgD;AAE7E,QAAM,YAAY,oBAAI,IAAqB;AAC3C,QAAM,UAAU,oBAAI,IAAuC;AAG3D,QAAM,SAAS,oBAAI,IAA2B;AAC9C,QAAM,YAAY,oBAAI,IAAoD;AAC1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F;",
6
- "names": []
3
+ "sources": ["../../src/lib/native-federation.error.ts", "../../src/lib/utils/clone-entry.ts", "../../src/lib/2.app/flows/registry/setup-registry.ts"],
4
+ "sourcesContent": ["class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "import type { StorageEntryKey } from 'lib/2.app/config/storage.contract';\nimport { NFError } from 'lib/native-federation.error';\n\ntype CloneEntry = <T>(name: StorageEntryKey, raw: T) => T;\n\nconst cloneEntry: CloneEntry = <T>(name: StorageEntryKey, raw: T) => {\n try {\n if (typeof structuredClone === 'function') {\n return structuredClone(raw);\n }\n } catch {\n /* structured clone is unavailable */\n }\n try {\n return JSON.parse(JSON.stringify(raw));\n } catch {\n /* object is not stringifyable */\n }\n throw new NFError(`Could not clone entry '${String(name)}'`);\n};\n\nexport { CloneEntry, cloneEntry };\n", "import type {\n NFEventConsumer,\n NFEventData,\n NFEventProvider,\n NFEventUnsubscribe,\n} from '../../../1.domain/registry/event.contract';\nimport type { ForManagingEvents } from 'lib/2.app/driver-ports/registry/for-managing-events.port';\nimport type {\n NFEventRegistryConfig,\n NFEventRegistryOptions,\n} from 'lib/2.app/config/registry.contract';\nimport { cloneEntry } from 'lib/sdk.index';\n\nexport function createRegistry(opts: NFEventRegistryOptions): ForManagingEvents {\n const cfg: NFEventRegistryConfig = {\n maxStreams: opts.maxStreams,\n maxEvents: opts.maxEvents ?? 1,\n removePercentage: opts.removePercentage,\n };\n\n // resources\n const resources = new Map<string, unknown>();\n const pending = new Map<string, Set<NFEventConsumer<any>>>();\n\n // events\n const events = new Map<string, NFEventData[]>();\n const listeners = new Map<string, Set<NFEventConsumer<NFEventData<any>>>>();\n const recentlyUsedStreams = new Set<string>();\n\n // Clamp to (maxEvents - 1) so at least one event always survives the trim.\n // Without this, maxEvents=1 (or any config where REMOVE_EVENTS == maxEvents)\n // would compute slice(-0), which returns the whole array and never trims.\n const REMOVE_EVENTS = Math.min(\n cfg.maxEvents - 1,\n cfg.removePercentage ? Math.ceil(cfg.maxEvents * cfg.removePercentage) : 1\n );\n\n /**\n * Mark `type` as the most-recently-used stream. When `maxStreams` is set and\n * the LRU set grows past that bound, the oldest stream (and its history) is\n * dropped. No-op when `maxStreams` is undefined \u2014 streams are then unbounded.\n */\n const touchStream = (type: string): void => {\n if (!cfg.maxStreams) return;\n recentlyUsedStreams.delete(type);\n recentlyUsedStreams.add(type);\n\n if (recentlyUsedStreams.size > cfg.maxStreams) {\n const oldest = recentlyUsedStreams.values().next().value;\n if (oldest) {\n recentlyUsedStreams.delete(oldest);\n events.delete(oldest);\n }\n }\n };\n\n /**\n * Append an event to `type`'s history, trim the history if it exceeds\n * `maxEvents`, and synchronously notify all current listeners. Trimming is\n * batched: when the history overflows, it is sliced down to\n * `(maxEvents - REMOVE_EVENTS)` items so subsequent emits don't slice on\n * every call.\n */\n const appendAndNotify = <T>(type: string, event: NFEventData<T>): void => {\n let history = events.get(type) ?? [];\n history.push(event);\n\n if (history.length > cfg.maxEvents) {\n history = history.slice(-(cfg.maxEvents - REMOVE_EVENTS));\n }\n\n events.set(type, history);\n\n const typeListeners = listeners.get(type);\n if (typeListeners && typeListeners.size > 0) {\n typeListeners.forEach(listener => listener(event));\n }\n };\n\n /**\n * RESOURCE: Register a resource by name. If the resource is a provider function, it is\n * invoked to obtain the actual resource. All callbacks waiting for this\n * resource via `onReady` are invoked once the resource is registered.\n */\n const register = async <T>(type: string, resource: T | NFEventProvider<T>): Promise<void> => {\n const value =\n typeof resource === 'function' ? await (resource as NFEventProvider<T>)() : resource;\n\n resources.set(type, value);\n\n const callbacks = pending.get(type);\n if (callbacks) {\n pending.delete(type);\n callbacks.forEach(cb => cb(value));\n }\n };\n\n /**\n * RESOURCE: Subscribe to the readiness of a resource. If the resource is already\n * registered, the callback is invoked immediately. Otherwise, the callback\n * is invoked once the resource is registered.\n */\n const onReady = <T>(type: string, callback: NFEventConsumer<T>): NFEventUnsubscribe => {\n const existing = resources.get(type);\n if (existing !== undefined) {\n callback(existing as T);\n return () => {};\n }\n\n let callbacks = pending.get(type);\n if (!callbacks) {\n callbacks = new Set();\n pending.set(type, callbacks);\n }\n callbacks.add(callback);\n\n return () => {\n callbacks!.delete(callback);\n if (callbacks!.size === 0) {\n pending.delete(type);\n }\n };\n };\n\n /**\n * EVENT: Subscribe to events of a specific type. The callback is invoked for\n * all future events of that type, and \u2014 when `opts.replay > 0` \u2014 for the\n * most recent `opts.replay` events already in history. Replay deliveries are\n * scheduled via `queueMicrotask`, so the unsubscribe handle is returned\n * synchronously and the callback fires after the current task completes.\n *\n * @param type Stream identifier.\n * @param callback Listener invoked with each event (replay + future).\n * @param opts.replay Number of buffered events to replay on subscribe, taken\n * from the tail of history (most recent first, delivered\n * in chronological order). Defaults to `1`, matching the\n * BehaviorSubject pattern: a fresh subscriber receives\n * the latest state. Pass `0` to suppress replay; pass a\n * larger value (capped by `maxEvents`) to receive more\n * history.\n * @returns Function that unsubscribes the listener.\n */\n const on = <T>(\n type: string,\n callback: NFEventConsumer<NFEventData<T>>,\n opts: { replay?: number } = {}\n ): NFEventUnsubscribe => {\n const replay = opts.replay ?? 1;\n const history = events.get(type);\n\n let typeListeners = listeners.get(type);\n if (!typeListeners) {\n typeListeners = new Set();\n listeners.set(type, typeListeners);\n }\n typeListeners.add(callback);\n\n if (history && history.length > 0 && replay > 0) {\n queueMicrotask(() => {\n const start = Math.max(0, history.length - replay);\n for (let i = start; i < history.length; i++) {\n callback(cloneEntry('event channel ' + type, history[i]!));\n }\n });\n }\n\n return () => {\n typeListeners!.delete(callback);\n if (typeListeners!.size === 0) {\n listeners.delete(type);\n }\n };\n };\n\n /**\n * EVENT: Publish a new event on `type`. The event is appended to the stream's\n * history and delivered synchronously to every current listener. When\n * `maxEvents` is exceeded the history is batch-trimmed; when `maxStreams` is\n * set, emitting to a new type may evict the least-recently-used stream.\n */\n const emit = <T>(type: string, data: T): void => {\n touchStream(type);\n appendAndNotify(type, { data, timestamp: Date.now() });\n };\n\n /**\n * EVENT: Publish a new event on `type` derived from the previous value, in\n * the style of a state reducer. `updateFn` receives a structured clone of\n * the last event's data (or `undefined` if the stream is empty), and its\n * return value becomes the next event. The clone protects historical events\n * from accidental mutation inside `updateFn`.\n *\n * Use this instead of `emit` when the new state depends on the old one \u2014 it\n * collapses the read-modify-write into a single, race-free call. Requires\n * `data` to be structured-clone-able when the stream is non-empty.\n *\n * @param type Stream identifier.\n * @param updateFn Reducer: `(current | undefined) => next`. Called with a\n * cloned snapshot of the last value (or `undefined` on\n * first emit).\n */\n const update = <T>(type: string, updateFn: (current: T | undefined) => T): void => {\n touchStream(type);\n\n const history = events.get(type) ?? [];\n const lastEvent = history[history.length - 1];\n const current =\n lastEvent === undefined ? undefined : cloneEntry('event channel ' + type, lastEvent.data);\n\n appendAndNotify(type, {\n data: updateFn(current),\n timestamp: Date.now(),\n });\n };\n\n const clear = (type?: string): void => {\n if (type) {\n // Clear event-related data\n events.delete(type);\n listeners.delete(type);\n\n // Clear resource-related data\n resources.delete(type);\n pending.delete(type);\n\n recentlyUsedStreams.delete(type);\n } else {\n // Clear all data\n events.clear();\n listeners.clear();\n pending.clear();\n resources.clear();\n recentlyUsedStreams.clear();\n }\n };\n\n return () => ({\n register,\n onReady,\n emit,\n update,\n on,\n clear,\n });\n}\n"],
5
+ "mappings": ";AAAA,IAAM,UAAN,cAAsB,MAAM;AAAA,EAC1B,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,KAAK;AACpB,SAAK,OAAO;AAAA,EACd;AACF;;;ACAA,IAAM,aAAyB,CAAI,MAAuB,QAAW;AACnE,MAAI;AACF,QAAI,OAAO,oBAAoB,YAAY;AACzC,aAAO,gBAAgB,GAAG;AAAA,IAC5B;AAAA,EACF,QAAQ;AAAA,EAER;AACA,MAAI;AACF,WAAO,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC;AAAA,EACvC,QAAQ;AAAA,EAER;AACA,QAAM,IAAI,QAAQ,0BAA0B,OAAO,I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,MAAM;AACX,oBAAe,OAAO,QAAQ;AAC9B,UAAI,cAAe,SAAS,GAAG;AAC7B,kBAAU,OAAO,IAAI;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAQA,QAAM,OAAO,CAAI,MAAc,SAAkB;AAC/C,gBAAY,IAAI;AAChB,oBAAgB,MAAM,EAAE,MAAM,WAAW,KAAK,IAAI,EAAE,CAAC;AAAA,EACvD;AAkBA,QAAM,SAAS,CAAI,MAAc,aAAkD;AACjF,gBAAY,IAAI;AAEhB,UAAM,UAAU,OAAO,IAAI,IAAI,KAAK,CAAC;AACrC,UAAM,YAAY,QAAQ,QAAQ,SAAS,CAAC;AAC5C,UAAM,UACJ,cAAc,SAAY,SAAY,WAAW,mBAAmB,MAAM,UAAU,IAAI;AAE1F,oBAAgB,MAAM;AAAA,MACpB,MAAM,SAAS,OAAO;AAAA,MACtB,WAAW,KAAK,IAAI;AAAA,IACtB,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,CAAC,SAAwB;AACrC,QAAI,MAAM;AAER,aAAO,OAAO,IAAI;AAClB,gBAAU,OAAO,IAAI;AAGrB,gBAAU,OAAO,IAAI;AACrB,cAAQ,OAAO,IAAI;AAEnB,0BAAoB,OAAO,IAAI;AAAA,IACjC,OAAO;AAEL,aAAO,MAAM;AACb,gBAAU,MAAM;AAChB,cAAQ,MAAM;AACd,gBAAU,MAAM;AAChB,0BAAoB,MAAM;AAAA,IAC5B;AAAA,EACF;AAEA,SAAO,OAAO;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
+ "names": ["opts"]
7
7
  }
package/fesm2022/sdk.mjs CHANGED
@@ -88,7 +88,7 @@ var cloneEntry = (name, raw) => {
88
88
  return JSON.parse(JSON.stringify(raw));
89
89
  } catch {
90
90
  }
91
- throw new NFError(`Could not parse storage entry '${String(name)}'`);
91
+ throw new NFError(`Could not clone entry '${String(name)}'`);
92
92
  };
93
93
  export {
94
94
  GLOBAL_SCOPE,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/1.domain/externals/external.contract.ts", "../../src/lib/utils/optional.ts", "../../src/lib/utils/path.ts", "../../src/lib/native-federation.error.ts", "../../src/lib/utils/clone-entry.ts"],
4
- "sourcesContent": ["import type { SharedVersion, ScopedVersion } from './version.contract';\n\nexport type ExternalName = string;\n\nexport type ScopedExternals = Record<string, ScopedExternal>;\n\nexport const GLOBAL_SCOPE = '__GLOBAL__';\n\nexport const STRICT_SCOPE = 'strict';\n\nexport type SharedExternal = {\n dirty: boolean;\n versions: SharedVersion[];\n};\n\nexport type shareScope = Record<string, SharedExternal>;\n\nexport type SharedExternals = Record<string, shareScope> & { [GLOBAL_SCOPE]: shareScope };\n\nexport type ScopedExternal = Record<string, ScopedVersion>;\n", "export class Optional<T> {\n private constructor(private item?: T) {}\n\n public static of<T>(item?: T): Optional<T> {\n return new Optional(item);\n }\n public static empty<U>(): Optional<U> {\n return Optional.of<U>(undefined);\n }\n\n public isPresent() {\n return typeof this.item !== 'undefined' && this.item !== null;\n }\n public set<U>(other: U) {\n return Optional.of(other);\n }\n\n public ifPresent(callback: (_: T) => void): void {\n if (this.isPresent()) callback(this.item as T);\n }\n\n public map<U>(callback: (_: NonNullable<T>) => U | Optional<U>): Optional<U> {\n if (!this.isPresent()) return Optional.empty();\n\n const result = callback(this.item as NonNullable<T>);\n return result instanceof Optional ? result : Optional.of(result);\n }\n\n public orElse(other: Required<T>): NonNullable<T> {\n return this.isPresent() ? (this.item as NonNullable<T>) : (other as NonNullable<T>);\n }\n\n public orThrow(error: Error | string | (() => Error)): NonNullable<T> {\n if (this.isPresent()) return this.item as NonNullable<T>;\n if (typeof error === 'function') throw error();\n throw typeof error === 'string' ? new Error(error) : error;\n }\n\n public get(): T | undefined {\n return this.item;\n }\n}\n", "function join(pathA: string, pathB: string): string {\n pathA = pathA.endsWith('/') ? pathA.slice(0, -1) : pathA;\n pathB = pathB.startsWith('/') ? pathB.slice(1) : pathB;\n return `${pathA}/${pathB}`;\n}\n\nfunction getScope(path: string) {\n if (!path) return '';\n\n const parts = path.split('/');\n\n if (parts[parts.length - 1] === '' || parts[parts.length - 1]!.includes('.')) {\n parts.pop();\n }\n if (parts.length < 1) return '';\n\n return `${parts.join('/')}/`;\n}\n\nexport { join, getScope };\n", "class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "import type { StorageEntryKey } from 'lib/2.app/config/storage.contract';\nimport { NFError } from 'lib/native-federation.error';\n\ntype CloneEntry = <T>(name: StorageEntryKey, raw: T) => T;\n\nconst cloneEntry: CloneEntry = <T>(name: StorageEntryKey, raw: T) => {\n try {\n if (typeof structuredClone === 'function') {\n return structuredClone(raw);\n }\n } catch {\n /* structured clone is unavailable */\n }\n try {\n return JSON.parse(JSON.stringify(raw));\n } catch {\n /* object is not stringifyable */\n }\n throw new NFError(`Could not parse storage entry '${String(name)}'`);\n};\n\nexport { CloneEntry, cloneEntry };\n"],
5
- "mappings": ";;;;;;;AAMO,IAAM,eAAe;AAErB,IAAM,eAAe;;;ACRrB,IAAM,WAAN,MAAM,UAAY;AAAA,EACf,YAAoB,MAAU;AAAV;AAAA,EAAW;AAAA,EAAX;AAAA,EAE5B,OAAc,GAAM,MAAuB;AACzC,WAAO,IAAI,UAAS,IAAI;AAAA,EAC1B;AAAA,EACA,OAAc,QAAwB;AACpC,WAAO,UAAS,GAAM,MAAS;AAAA,EACjC;AAAA,EAEO,YAAY;AACjB,WAAO,OAAO,KAAK,SAAS,eAAe,KAAK,SAAS;AAAA,EAC3D;AAAA,EACO,IAAO,OAAU;AACtB,WAAO,UAAS,GAAG,KAAK;AAAA,EAC1B;AAAA,EAEO,UAAU,UAAgC;AAC/C,QAAI,KAAK,UAAU,EAAG,UAAS,KAAK,IAAS;AAAA,EAC/C;AAAA,EAEO,IAAO,UAA+D;AAC3E,QAAI,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GAAG;AAAA,IAC5B;AAAA,EACF,QAAQ;AAAA,EAER;AACA,MAAI;AACF,WAAO,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC;AAAA,EACvC,QAAQ;AAAA,EAER;AACA,QAAM,IAAI,QAAQ,kCAAkC,OAAO,IAAI,CAAC,GAAG;AACrE;",
4
+ "sourcesContent": ["import type { SharedVersion, ScopedVersion } from './version.contract';\n\nexport type ExternalName = string;\n\nexport type ScopedExternals = Record<string, ScopedExternal>;\n\nexport const GLOBAL_SCOPE = '__GLOBAL__';\n\nexport const STRICT_SCOPE = 'strict';\n\nexport type SharedExternal = {\n dirty: boolean;\n versions: SharedVersion[];\n};\n\nexport type shareScope = Record<string, SharedExternal>;\n\nexport type SharedExternals = Record<string, shareScope> & { [GLOBAL_SCOPE]: shareScope };\n\nexport type ScopedExternal = Record<string, ScopedVersion>;\n", "export class Optional<T> {\n private constructor(private item?: T) {}\n\n public static of<T>(item?: T): Optional<T> {\n return new Optional(item);\n }\n public static empty<U>(): Optional<U> {\n return Optional.of<U>(undefined);\n }\n\n public isPresent() {\n return typeof this.item !== 'undefined' && this.item !== null;\n }\n public set<U>(other: U) {\n return Optional.of(other);\n }\n\n public ifPresent(callback: (_: T) => void): void {\n if (this.isPresent()) callback(this.item as T);\n }\n\n public map<U>(callback: (_: NonNullable<T>) => U | Optional<U>): Optional<U> {\n if (!this.isPresent()) return Optional.empty();\n\n const result = callback(this.item as NonNullable<T>);\n return result instanceof Optional ? result : Optional.of(result);\n }\n\n public orElse(other: Required<T>): NonNullable<T> {\n return this.isPresent() ? (this.item as NonNullable<T>) : (other as NonNullable<T>);\n }\n\n public orThrow(error: Error | string | (() => Error)): NonNullable<T> {\n if (this.isPresent()) return this.item as NonNullable<T>;\n if (typeof error === 'function') throw error();\n throw typeof error === 'string' ? new Error(error) : error;\n }\n\n public get(): T | undefined {\n return this.item;\n }\n}\n", "function join(pathA: string, pathB: string): string {\n pathA = pathA.endsWith('/') ? pathA.slice(0, -1) : pathA;\n pathB = pathB.startsWith('/') ? pathB.slice(1) : pathB;\n return `${pathA}/${pathB}`;\n}\n\nfunction getScope(path: string) {\n if (!path) return '';\n\n const parts = path.split('/');\n\n if (parts[parts.length - 1] === '' || parts[parts.length - 1]!.includes('.')) {\n parts.pop();\n }\n if (parts.length < 1) return '';\n\n return `${parts.join('/')}/`;\n}\n\nexport { join, getScope };\n", "class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "import type { StorageEntryKey } from 'lib/2.app/config/storage.contract';\nimport { NFError } from 'lib/native-federation.error';\n\ntype CloneEntry = <T>(name: StorageEntryKey, raw: T) => T;\n\nconst cloneEntry: CloneEntry = <T>(name: StorageEntryKey, raw: T) => {\n try {\n if (typeof structuredClone === 'function') {\n return structuredClone(raw);\n }\n } catch {\n /* structured clone is unavailable */\n }\n try {\n return JSON.parse(JSON.stringify(raw));\n } catch {\n /* object is not stringifyable */\n }\n throw new NFError(`Could not clone entry '${String(name)}'`);\n};\n\nexport { CloneEntry, cloneEntry };\n"],
5
+ "mappings": ";;;;;;;AAMO,IAAM,eAAe;AAErB,IAAM,eAAe;;;ACRrB,IAAM,WAAN,MAAM,UAAY;AAAA,EACf,YAAoB,MAAU;AAAV;AAAA,EAAW;AAAA,EAAX;AAAA,EAE5B,OAAc,GAAM,MAAuB;AACzC,WAAO,IAAI,UAAS,IAAI;AAAA,EAC1B;AAAA,EACA,OAAc,QAAwB;AACpC,WAAO,UAAS,GAAM,MAAS;AAAA,EACjC;AAAA,EAEO,YAAY;AACjB,WAAO,OAAO,KAAK,SAAS,eAAe,KAAK,SAAS;AAAA,EAC3D;AAAA,EACO,IAAO,OAAU;AACtB,WAAO,UAAS,GAAG,KAAK;AAAA,EAC1B;AAAA,EAEO,UAAU,UAAgC;AAC/C,QAAI,KAAK,UAAU,EAAG,UAAS,KAAK,IAAS;AAAA,EAC/C;AAAA,EAEO,IAAO,UAA+D;AAC3E,QAA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B,GAAG;AAAA,IAC5B;AAAA,EACF,QAAQ;AAAA,EAER;AACA,MAAI;AACF,WAAO,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC;AAAA,EACvC,QAAQ;AAAA,EAER;AACA,QAAM,IAAI,QAAQ,0BAA0B,OAAO,IAAI,CAAC,GAAG;AAC7D;",
6
6
  "names": []
7
7
  }
package/init-registry.mjs CHANGED
@@ -1 +1 @@
1
- function d(r){let g=new Map,o=new Map,v=new Map,m=new Map,a=new Set,E=Math.ceil(r.maxEvents*r.removePercentage),f=async(e,n)=>{let i=typeof n=="function"?await n():n;g.set(e,i);let t=o.get(e);t&&(o.delete(e),t.forEach(s=>s(i)))},l=(e,n)=>{let i=g.get(e);if(i!==void 0)return n(i),()=>{};let t=o.get(e);return t||(t=new Set,o.set(e,t)),t.add(n),()=>{t.delete(n),t.size===0&&o.delete(e)}},N=(e,n)=>{let i=v.get(e),t=i?[...i]:null,s=m.get(e);return s||(s=new Set,m.set(e,s)),s.add(n),t&&t.length>0&&queueMicrotask(()=>{t.forEach(c=>n(c))}),()=>{s.delete(n),s.size===0&&m.delete(e)}},u=(e,n)=>{let i={data:n,timestamp:Date.now()};if(a.delete(e),a.add(e),a.size>r.maxStreams){let c=a.values().next().value;c&&(a.delete(c),v.delete(c))}let t=v.get(e)||[];t.push(i),t.length>r.maxEvents&&(t=t.slice(-(r.maxEvents-E))),v.set(e,t);let s=m.get(e);s&&s.size>0&&s.forEach(c=>c(i))},F=e=>{e?(v.delete(e),m.delete(e),g.delete(e),o.delete(e),a.delete(e)):(v.clear(),m.clear(),o.clear(),g.clear(),a.clear())};return()=>({register:f,onReady:l,emit:u,on:N,clear:F})}(function(){let r=document.currentScript,g={maxStreams:r?.dataset?.maxStreams?Number(r.dataset.maxStreams):50,maxEvents:r?.dataset?.maxEvents?Number(r.dataset.maxEvents):50,removePercentage:r?.dataset?.removePercentage?Number(r.dataset.removePercentage)/100:.5},o=d(g);window.__NF_REGISTRY__=Object.freeze(o())})();
1
+ var f=class extends Error{constructor(o,a){super(o,a),this.name="NFError"}};var l=(s,o)=>{try{if(typeof structuredClone=="function")return structuredClone(o)}catch{}try{return JSON.parse(JSON.stringify(o))}catch{}throw new f(`Could not clone entry '${String(s)}'`)};function u(s){let o={maxStreams:s.maxStreams,maxEvents:s.maxEvents??1,removePercentage:s.removePercentage},a=new Map,c=new Map,m=new Map,d=new Map,g=new Set,N=Math.min(o.maxEvents-1,o.removePercentage?Math.ceil(o.maxEvents*o.removePercentage):1),p=e=>{if(o.maxStreams&&(g.delete(e),g.add(e),g.size>o.maxStreams)){let t=g.values().next().value;t&&(g.delete(t),m.delete(t))}},y=(e,t)=>{let r=m.get(e)??[];r.push(t),r.length>o.maxEvents&&(r=r.slice(-(o.maxEvents-N))),m.set(e,r);let n=d.get(e);n&&n.size>0&&n.forEach(i=>i(t))},x=async(e,t)=>{let r=typeof t=="function"?await t():t;a.set(e,r);let n=c.get(e);n&&(c.delete(e),n.forEach(i=>i(r)))},F=(e,t)=>{let r=a.get(e);if(r!==void 0)return t(r),()=>{};let n=c.get(e);return n||(n=new Set,c.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&c.delete(e)}},T=(e,t,r={})=>{let n=r.replay??1,i=m.get(e),v=d.get(e);return v||(v=new Set,d.set(e,v)),v.add(t),i&&i.length>0&&n>0&&queueMicrotask(()=>{let w=Math.max(0,i.length-n);for(let E=w;E<i.length;E++)t(l("event channel "+e,i[E]))}),()=>{v.delete(t),v.size===0&&d.delete(e)}},S=(e,t)=>{p(e),y(e,{data:t,timestamp:Date.now()})},h=(e,t)=>{p(e);let r=m.get(e)??[],n=r[r.length-1],i=n===void 0?void 0:l("event channel "+e,n.data);y(e,{data:t(i),timestamp:Date.now()})},R=e=>{e?(m.delete(e),d.delete(e),a.delete(e),c.delete(e),g.delete(e)):(m.clear(),d.clear(),c.clear(),a.clear(),g.clear())};return()=>({register:x,onReady:F,emit:S,update:h,on:T,clear:R})}(function(){let s=document.currentScript,o={maxStreams:s?.dataset?.maxStreams?Number(s.dataset.maxStreams):void 0,maxEvents:s?.dataset?.maxEvents?Number(s.dataset.maxEvents):void 0,removePercentage:s?.dataset?.removePercentage?Number(s.dataset.removePercentage)/100:void 0},a=u(o);window.__NF_REGISTRY__=Object.freeze(a())})();
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.2.0",
2
+ "version": "4.2.1",
3
3
  "name": "@softarc/native-federation-orchestrator",
4
4
  "author": "Aukevanoost",
5
5
  "keywords": [
package/quickstart.mjs CHANGED
@@ -9,7 +9,7 @@ var ss=Object.create;var vo=Object.defineProperty;var as=Object.getOwnPropertyDe
9
9
  //# sourceURL=`,no=`
10
10
  //# sourceMappingURL=`,Ci=/url\(\s*(?:(["'])((?:\\.|[^\n\\"'])+)\1|((?:\\.|[^\s,"'()\\])+))\s*\)/g,mr=[],io=0,Ii=()=>{if(++io>100)return new Promise(n=>mr.push(n))},ki=()=>{io--,mr.length&&mr.shift()()},so=async(n,p,d)=>{if(ie&&!p.integrity)throw Error(`No integrity for ${n}${pt(d)}.`);let g,b=Ii();b&&await b;try{g=await ae(n,p)}catch($){throw $.message=`Unable to fetch ${n}${pt(d)} - see network log for details.
11
11
  `+$.message,$}finally{ki()}if(!g.ok){let $=new TypeError(`${g.status} ${g.statusText} ${g.url}${pt(d)}`);throw $.response=g,$}return g},nt,ao=async()=>{let n=await import(P);nt||(nt=n.transform)};async function co(n,p,d){let g=await so(n,p,d),b,[,$,k,I]=(b=g.headers.get("content-type")||"").match(/^(?:[^/;]+\/(?:[^/+;]+\+)?(json)|(?:text|application)\/(?:x-)?((java|type)script|wasm|css))(?:;|$)/)||[];if(!(k=$||(I?I[0]+"s":k||/\.m?ts(\?|#|$)/.test(n)&&"ts")))throw Error(`Unsupported Content-Type "${b}" loading ${n}${pt(d)}. Modules must be served with a valid MIME type like application/javascript.`);return{url:g.url,source:await(k>"v"?WebAssembly.compileStreaming(g):g.text()),type:k}}let dr="var h=import.meta.hot,",lo=async(n,p,d)=>{let g=je.integrity[n];p=g&&!p.integrity?{...p,integrity:g}:p;let{url:b=n,source:$,type:k}=await(pe||co)(n,p,d,co)||{};if(k==="wasm"){let I=WebAssembly.Module.exports(wi[b]=$),j=WebAssembly.Module.imports($),N=yt(b);$=`import*as $_ns from${N};`;let F=0,E="";for(let{module:o,kind:me}of j){let be=yt(o);$+=`import*as impt${F} from${be};
12
- `,E+=`${be}:${me==="global"?`importShim._i.get(impt${F})||impt${F++}`:`impt${F++}`},`}$+=`${dr}i=await WebAssembly.instantiate(importShim._s[${N}],{${E}});importShim._i.set($_ns,i);`,E="";for(let{name:o,kind:me}of I)$+=`export let ${o}=i.exports['${o}'];`,me==="global"&&($+=`try{${o}=${o}.value}catch(_){${o}=undefined}`),E+=`${o},`;$+=`if(h)h.accept(m=>({${E}}=m))`}else if(k==="json")$=`${dr}j=JSON.parse(${JSON.stringify($)});export{j as default};if(h)h.accept(m=>j=m.default)`;else if(k==="css")$=`${dr}s=h&&h.data.s||new CSSStyleSheet();s.replaceSync(${JSON.stringify($.replace(Ci,(I,j="",N,F)=>`url(${j}${Ur(N||F,b)}${j})`))});if(h){h.data.s=s;h.accept(()=>{})}export default s`;else if(k==="ts"){nt||await ao();let I=nt($,b);$=I===void 0?$:I}return{url:b,source:$,type:k}},hr=(n,p,d,g)=>{if(g&&ht[n]){let $=0;for(;ht[n+"#"+ ++$];);n+="#"+$}let b=ht[n];return b||(ht[n]=b={u:n,r:g?n:void 0,f:void 0,S:g,L:void 0,a:void 0,d:void 0,b:void 0,s:void 0,n:!1,N:!1,t:null,m:null},b.f=(async()=>{b.S===void 0&&({url:b.r,source:b.S,type:b.t}=await(br[n]||lo(n,p,d)),!b.n&&b.t!=="js"&&!w&&(b.t==="css"&&!rt||b.t==="json"&&!tt||b.t==="wasm"&&!At&&!ut||b.t==="ts")&&(b.n=!0));try{b.a=bi(b.S,b.u)}catch($){ft($),b.a=[[],[],!1]}return b})(),b)},Ti=n=>Error(`${n} feature must be enabled via <script type="esms-options">{ "polyfillEnable": ["${n}"] }<\/script>`),fo=(n,p)=>{n.L||(n.L=n.f.then(()=>{let d=p;n.d=n.a[0].map(({n:g,d:b,t:$,a:k,se:I})=>{let j=$>=4,N=j&&$<6;if(j){if(!w&&(N?!He:!ir))throw Ti(N?"wasm-module-sources":"import-defer");(!N||!ut)&&(n.n=!0)}let F;if(k>0&&!w&&we){let me=n.S.slice(k,I-1);me.includes("json")?tt?F="":n.n=!0:me.includes("css")&&(rt?F="":n.n=!0)}if(b!==-1||!g)return;let E=dt(g,n.r||n.u);if((E.n||B)&&(n.n=!0),(b>=0||E.N)&&(n.N=!0),b!==-1)return;if(Ae&&Ae(E.r)&&!N)return{l:{b:E.r},s:!1};d.integrity&&(d={...d,integrity:void 0});let o={l:hr(E.r,d,n.r,F),s:N};return F===""&&(o.l.b=o.l.u),o.s||fo(o.l,p),o}).filter(g=>g)}))},bt=()=>{for(let n of document.querySelectorAll(w?"link[rel=modulepreload-shim]":"link[rel=modulepreload]"))n.ep||So(n);for(let n of document.querySelectorAll("script[type]"))n.type==="importmap"+(w?"-shim":"")?n.ep||bo(n):n.type==="module"+(w?"-shim":"")&&(ot=!1,n.ep||Ro(n))},Dt=n=>{let p={};return n.integrity&&(p.integrity=n.integrity),n.referrerPolicy&&(p.referrerPolicy=n.referrerPolicy),n.fetchPriority&&(p.priority=n.fetchPriority),n.crossOrigin==="use-credentials"?p.credentials="include":n.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p},gr=Promise.resolve(),po=!1,Vt=1,Gt=n=>{if(n===void 0){if(po)return;po=!0,Vt--}--Vt===0&&!z&&(w||!Fe)&&(document.removeEventListener("DOMContentLoaded",mo),document.dispatchEvent(new Event("DOMContentLoaded")))},Er=1,uo=()=>{--Er===0&&!z&&(w||!Fe)&&(window.removeEventListener("load",ho),window.dispatchEvent(new Event("load")))},mo=async()=>{await We,Gt()},ho=async()=>{await We,Gt(),uo()};c&&(document.addEventListener("DOMContentLoaded",mo),window.addEventListener("load",ho));let go=async()=>{await We,bt(),document.readyState==="complete"&&yr()},Rt=1,yr=()=>{--Rt===0&&(Gt(),!z&&(w||!Fe)&&(document.removeEventListener("readystatechange",go),document.dispatchEvent(new Event("readystatechange"))))},Eo=n=>n.nextSibling||n.parentNode&&Eo(n.parentNode),yo=(n,p)=>n.ep||!p&&(!n.src&&!n.innerHTML||!Eo(n))||n.getAttribute("noshim")!==null||!(n.ep=!0),bo=(n,p=Rt>0)=>{if(!yo(n,p)){if(n.src){if(!w)return;to=!0}Et=Et.then(async()=>{je=qr(n.src?await(await so(n.src,Dt(n))).json():JSON.parse(n.innerHTML),n.src||Te,je)}).catch(d=>{d instanceof SyntaxError&&(d=new Error(`Unable to parse import map ${d.message} in: ${n.src||n.innerHTML}`)),ft(d)}),!gt&&ot&&Et.then(()=>gt=je),!ot&&!fr&&(fr=!0,!w&&Fe&&!Ft&&(Fe=!1,c&&ro())),ot=!1}},Ro=(n,p=Rt>0)=>{if(yo(n,p))return;let d=n.getAttribute("async")===null&&Rt>0,g=Vt>0,b=Er>0;b&&Er++,d&&Rt++,g&&Vt++;let $,k=n.lang==="ts";k&&!n.src?$=Promise.resolve(nt||ao()).then(()=>{let I=nt(n.innerHTML,Te);return I!==void 0&&(Vr(),pr=!1),_t(n.src||Te,Te,Dt(n),I===void 0?n.innerHTML:I,!w&&I===void 0,d&&gr,"ts")}).catch(ft):$=_t(n.src||Te,Te,Dt(n),n.src?void 0:n.innerHTML,!w,d&&gr,k?"ts":void 0).catch(ft),z||$.then(()=>n.dispatchEvent(new Event("load"))),d&&!k&&(gr=$.then(yr)),g&&$.then(Gt),b&&$.then(uo)},br={},So=n=>{n.ep=!0,We.then(()=>{Fe&&!w||br[n.href]||(br[n.href]=lo(n.href,Dt(n)))})}})();var X=class extends Error{constructor(t,i){super(t,i),this.name="NFError"}};function J(r,t){return r=r.endsWith("/")?r.slice(0,-1):r,t=t.startsWith("/")?t.slice(1):t,`${r}/${t}`}function Me(r){if(!r)return"";let t=r.split("/");return(t[t.length-1]===""||t[t.length-1].includes("."))&&t.pop(),t.length<1?"":`${t.join("/")}/`}function Co(r,t){return(f={})=>(r.manifestIntegrity?t.manifestProvider.provide(f,{integrity:r.manifestIntegrity}):t.manifestProvider.provide(f)).catch(T=>(r.log.error(1,"Could not fetch manifest.",T),Promise.reject(new X("Failed to fetch manifest")))).then(i).then(c).then(S).then(h);function i(f){if(!r.hostRemoteEntry)return f;let{name:y,url:T,cacheTag:M,integrity:w}=r.hostRemoteEntry,K=M?`${T}?cacheTag=${M}`:T;return{...f,[y]:w?{url:K,integrity:w}:K}}function s(f){return typeof f=="string"?{url:f}:f}async function c(f){let y=Object.entries(f).map(([T,M])=>m(T,M));return Promise.all(y)}async function m(f,y){let{url:T,integrity:M}=s(y),w=!1,K=!1;if(t.remoteInfoRepo.tryGet(f).ifPresent(H=>{r.profile.overrideCachedRemotes!=="never"&&(T!==J(H.scopeUrl,"remoteEntry.json")||r.profile.overrideCachedRemotesIfURLMatches)?(r.log.debug(1,`Overriding existing remote '${f}' with '${T}'.`),w=!0):(r.log.debug(1,`Found remote '${f}' in storage, omitting fetch.`),K=!0)}),K)return!1;try{let H=M?await t.remoteEntryProvider.provide(T,{integrity:M}):await t.remoteEntryProvider.provide(T);return r.log.debug(1,`Fetched '${H.name}' from '${H.url}', exposing: ${JSON.stringify(H.exposes)}`),R(H,f,w)}catch(H){return r.strict.strictRemoteEntry?(r.log.error(1,`Could not fetch remote '${f}'.`,H),Promise.reject(new X(`Could not fetch remote '${f}'`))):(r.log.warn(1,`Could not fetch remote '${f}'. skipping init.`,H),Promise.resolve(!1))}}function R(f,y,T){if(T&&(f.override=T),r.hostRemoteEntry&&y===r.hostRemoteEntry.name&&(f.host=!0,f.name=r.hostRemoteEntry.name),f.name!==y){let M=`Fetched remote '${f.name}' does not match requested '${y}'.`;if(r.strict.strictRemoteEntry)throw new X(M);r.log.warn(1,`${M} Omitting expected name.`)}return f}function S(f){return f.filter(y=>y!==!1)}function h(f){return r.sse&&f.forEach(y=>{if(y.buildNotificationsEndpoint){t.sse.watchRemoteBuilds(J(Me(y.url),y.buildNotificationsEndpoint)),r.log.debug(1,`Registered SSE endpoint of remote '${y.name}' `);return}r.log.debug(1,`Remote ${y.name} has no defined 'buildNotificationsEndpoint'`)}),f}}function Io(r,t){return h=>{try{return h.forEach(f=>{f?.override&&i(f),s(f),c(f),m(f)}),Promise.resolve(h)}catch(f){return Promise.reject(f)}};function i(h){t.remoteInfoRepo.remove(h.name),t.scopedExternalsRepo.remove(h.name),t.sharedExternalsRepo.removeFromAllScopes(h.name)}function s({name:h,url:f,exposes:y,integrity:T}){t.remoteInfoRepo.addOrUpdate(h,{scopeUrl:Me(f),exposes:Object.values(y??[]).map(M=>({moduleName:M.key,file:M.outFileName})),...T?{integrity:T}:{}})}function c(h){h.shared.forEach(f=>{if(!f.version||!t.versionCheck.isValidSemver(f.version)){let y=`[${h.name}][${f.packageName}] Version '${f.version}' is not a valid version.`;if(r.strict.strictExternalVersion)throw r.log.error(2,y),new X(`Could not process remote '${h.name}'`);r.log.warn(2,y)}f.singleton?R(h.name,f,h):S(h.name,f)})}function m(h){h.chunks&&(r.log.debug(2,`Adding chunks for remote "${h.name}", bundles: [${Object.keys(h.chunks).join(", ")}]`),Object.entries(h.chunks).forEach(([f,y])=>{t.sharedChunksRepo.addOrReplace(h.name,f,y)}))}function R(h,f,y){let T="skip",M=f.version??t.versionCheck.smallestVersion(f.requiredVersion),w={file:f.outFileName,name:h,bundle:f.bundle,strictVersion:f.strictVersion,cached:!1,requiredVersion:f.requiredVersion||M},K=t.sharedExternalsRepo.scopeType(f.shareScope);K==="strict"&&(T="share",w.requiredVersion=M);let H=t.sharedExternalsRepo.tryGet(f.packageName,f.shareScope).orElse({dirty:!1,versions:[]}),ae=H.versions.find(v=>v.tag===f.version),pe=H.dirty;if(ae){if(w.strictVersion&&ae.remotes[0].requiredVersion!==w.requiredVersion){let v=`[${h}][${f.packageName}@${f.version}] Required version-range '${w.requiredVersion}' does not match cached version-range '${ae.remotes[0].requiredVersion}'`;if(r.strict.strictExternalSameVersionCompatibility)throw r.log.error(2,v),new X(`Could not process remote '${y.name}'`);r.log.warn(2,v)}!ae.host&&y?.host?(ae.host=!0,ae.remotes.unshift(w)):ae.remotes.push(w)}else K!=="strict"&&(pe=!0),H.versions.push({tag:M,action:T,host:!!y?.host,remotes:[w]});t.sharedExternalsRepo.addOrUpdate(f.packageName,{dirty:pe,versions:H.versions.sort((v,P)=>t.versionCheck.compare(P.tag,v.tag))},f.shareScope)}function S(h,f){t.scopedExternalsRepo.addExternal(h,f.packageName,{tag:f.version??t.versionCheck.smallestVersion(f.requiredVersion),file:f.outFileName,bundle:f.bundle})}}var Ee="__GLOBAL__",ko="strict";function To(r,t){return()=>{for(let s of t.sharedExternalsRepo.getScopes()){let c=t.sharedExternalsRepo.getFromScope(s);try{Object.entries(c).filter(([m,R])=>R.dirty).forEach(([m,R])=>t.sharedExternalsRepo.addOrUpdate(m,i(m,R),s))}catch(m){return r.log.error(3,`[${s??Ee}] failed to determine shared externals.`,{sharedExternals:c,error:m}),Promise.reject(new X(`Could not determine shared externals in scope ${s}.`,m))}}return Promise.resolve()};function i(s,c){if(c.versions.length===1)return c.versions[0].action="share",c.dirty=!1,c;let m=c.versions.find(R=>R.host);if(!m&&r.profile.latestSharedExternal&&(m=c.versions[0]),!m){let R=Number.MAX_VALUE;c.versions.forEach(S=>{let h=c.versions.filter(f=>!f.remotes[0].cached&&f.remotes[0].strictVersion&&!t.versionCheck.isCompatible(S.tag,f.remotes[0].requiredVersion)).length;h<R&&(R=h,m=S)})}if(!m)throw new X(`[${s}] Could not determine shared version!`);return c.versions.forEach(R=>{if(t.versionCheck.isCompatible(m.tag,R.remotes[0].requiredVersion)){R.action="skip";return}if(r.strict.strictExternalCompatibility&&R.remotes[0].strictVersion)throw r.log.error(3,`[${R.remotes[0].name}][${s}@${R.tag}] Is not compatible with requiredRange '${m.remotes[0]?.requiredVersion}' from remote '${m.remotes[0].name}'.`),new X(`External ${s}@${R.tag} could not be shared.`);R.action=R.remotes[0].strictVersion?"scope":"skip"}),m.action="share",c.dirty=!1,c}}var kt;(function(r){r.COMPLETED="federation-rebuild-complete",r.ERROR="federation-rebuild-error",r.CANCELLED="federation-rebuild-cancelled"})(kt||(kt={}));var Lo="@nf-internal";function Tt(r){r.startsWith("./")&&(r=r.slice(2));let t=r.replace(/.(m|c)?js$/,"");return Lo+"/"+t}function Oo(r,t){return()=>{let v={imports:{}},P={};try{return i(v,P),c(v,P),h(v,P),M(v,P),H(v,P),Promise.resolve(v)}catch(q){return Promise.reject(q)}};function i(v,P){let q=t.scopedExternalsRepo.getAll();for(let[V,B]of Object.entries(q)){let z=t.remoteInfoRepo.tryGet(V).orThrow(()=>(r.log.error(4,`[scoped][${V}] Remote name not found in cache.`),new X("Could not create ImportMap.")));y(v,z.scopeUrl,s(B,z.scopeUrl));for(let ie of Object.values(B))ae(v,J(z.scopeUrl,ie.file),V,ie.file);Object.values(B).filter(ie=>!!ie.bundle).forEach(ie=>K(P,V,ie.bundle))}return v}function s(v,P){let q={};for(let[V,B]of Object.entries(v))q[V]=J(P,B.file);return q}function c(v,P){let q=t.sharedExternalsRepo.getScopes({includeGlobal:!1});for(let V of q)m(v,V,P);return v}function m(v,P,q){let V=t.sharedExternalsRepo.getFromScope(P);for(let[B,z]of Object.entries(V)){let ie,Ne;for(let te of z.versions){if(te.action==="scope"){for(let ue of te.remotes){let et=pe(P,ue.name,B),Ve=J(et,ue.file);y(v,et,{[B]:Ve}),ae(v,Ve,ue.name,ue.file),K(q,ue.name,ue.bundle),ue.cached=!0}continue}let we=pe(P,te.remotes[0].name,B),xe=J(we,te.remotes[0].file),Qe={name:te.remotes[0].name,file:te.remotes[0].file};te.remotes[0].cached=!0,te.action==="share"&&K(q,te.remotes[0].name,te.remotes[0].bundle),te.action==="skip"&&(ie||(ie=R(z,P,B)??"NOT_AVAILABLE"),ie!=="NOT_AVAILABLE"&&(Ne||(Ne=pe(P,ie.remotes[0].name,B)),xe=J(Ne,ie.remotes[0].file),Qe={name:ie.remotes[0].name,file:ie.remotes[0].file},ie.remotes[0].cached=!0,te.remotes[0].cached=!1)),te.remotes.forEach(ue=>{let et=pe(P,ue.name,B);y(v,et,{[B]:xe})}),ae(v,xe,Qe.name,Qe.file)}t.sharedExternalsRepo.addOrUpdate(B,z,P)}}function R(v,P,q){let V=v.versions.filter(z=>z.action==="share"),B=`${P}.${q}`;if(V.length>1&&S(B),V.length<1){if(r.strict.strictImportMap)throw r.log.error(4,`[${P}][${q}] shareScope has no override version.`),new X("Could not create ImportMap.");r.log.debug(4,`[${P}][${q}] shareScope has no override version, scoping override versions.`)}return V[0]}function S(v){if(r.strict.strictImportMap)throw r.log.error(4,`[${v}] ShareScope external has multiple shared versions.`),new X("Could not create ImportMap.");r.log.warn(4,`ShareScope external ${v} has multiple shared versions.`)}function h(v,P){let q=t.sharedExternalsRepo.getFromScope();for(let[V,B]of Object.entries(q)){for(let z of B.versions){if(z.action==="skip")continue;if(z.action==="scope"){for(let te of z.remotes){let we=pe(Ee,te.name,V),xe=J(we,te.file);y(v,we,{[V]:xe}),ae(v,xe,te.name,te.file),te.cached=!0,K(P,te.name,te.bundle)}continue}if(v.imports[V]){f(V);continue}let ie=pe(Ee,z.remotes[0].name,V),Ne=J(ie,z.remotes[0].file);T(v,{[V]:Ne}),ae(v,Ne,z.remotes[0].name,z.remotes[0].file),K(P,z.remotes[0].name,z.remotes[0].bundle),z.remotes[0].cached=!0}t.sharedExternalsRepo.addOrUpdate(V,B)}return v}function f(v){if(r.strict.strictImportMap)throw r.log.error(4,`[${v}] Shared external has multiple shared versions.`),new X("Could not create ImportMap.");r.log.warn(4,`Singleton external ${v} has multiple shared versions.`)}function y(v,P,q){v.scopes||(v.scopes={}),v.scopes[P]||(v.scopes[P]={}),v.scopes[P]=Object.assign(v.scopes[P],q)}function T(v,P){v.imports=Object.assign(v.imports,P)}function M(v,P){let q=t.remoteInfoRepo.getAll();for(let[V,B]of Object.entries(q))w(v,V,B),K(P,V,"mapping-or-exposed")}function w(v,P,q){for(let V of q.exposes){let B=J(P,V.moduleName),z=J(q.scopeUrl,V.file);v.imports[B]=z,ae(v,z,P,V.file)}}function K(v,P,q){return q&&(v[P]||(v[P]=new Set),v[P].add(q)),v}function H(v,P){return Object.entries(P).forEach(([q,V])=>{let B=pe("CHUNKS",q),z=Array.from(V).reduce((ie,Ne)=>(t.sharedChunksRepo.tryGet(q,Ne).ifPresent(te=>{te.forEach(we=>{let xe=J(B,we);ie[Tt(we)]=xe,ae(v,xe,q,we)})}),ie),{});Object.keys(z).length>0&&y(v,B,z)}),v}function ae(v,P,q,V){let B=t.remoteInfoRepo.tryGet(q).get()?.integrity?.[V];B&&(v.integrity||(v.integrity={}),v.integrity[P]=B)}function pe(v,P,q){return t.remoteInfoRepo.tryGet(P).map(V=>V.scopeUrl).orThrow(()=>(q?r.log.error(4,`[${v}][${q}][${P}] Remote name not found in cache.`):r.log.error(4,`[${v}][${P}] Remote name not found in cache.`),new X("Could not create ImportMap.")))}}function Xt(r,t){return c=>Promise.resolve(c).then(i).then(s);function i(c){return t.browser.setImportMapFn(c),r.log.debug(5,"Added import map to browser.",c),c}function s(){t.remoteInfoRepo.commit(),t.scopedExternalsRepo.commit(),t.sharedExternalsRepo.commit(),t.sharedChunksRepo.commit()}}function No(r,t){let i=(s,c)=>{try{if(!t.remoteInfoRepo.contains(s))throw new X(`Remote '${s}' is not initialized.`);let m=t.remoteInfoRepo.tryGetModule(s,c).orThrow(new X(`Exposed module '${c}' from remote '${s}' not found in storage.`));return r.log.debug(6,`Loading initialized module '${m}'`),t.browser.importModule(m)}catch(m){return r.log.error(6,`Failed to load module ${J(s,c)}: `,{error:m}),Promise.reject(new X(`Failed to load module ${J(s,c)}`))}};return()=>Promise.resolve(i)}var us=({config:r,adapters:t})=>({getRemoteEntries:Co(r,t),processRemoteEntries:Io(r,t),determineSharedExternals:To(r,t),generateImportMap:Oo(r,t),commitChanges:Xt(r,t),exposeModuleLoader:No(r,t)}),xo=({config:r,adapters:t})=>({flow:us({config:r,adapters:t}),adapters:t,config:r}),Ao=({flow:r,adapters:t,config:i})=>s=>r.getRemoteEntries(s).then(r.processRemoteEntries).then(r.determineSharedExternals).then(r.generateImportMap).then(r.commitChanges).then(r.exposeModuleLoader).then(c=>({config:i,adapters:t,loadRemoteModule:c}));var Fo=r=>({setImportMapFn:r.setImportMapFn,importModule:r.loadModuleFn});var xn=It(Jo()),An=It(In()),Fn=It(Ye()),Pn=It(Ln()),Mn=It(Nn()),_n=()=>({isValidSemver:function(r){return(0,xn.default)(r)!==null},isCompatible:function(r,t){return(0,An.default)(r,t)},compare:function(r,t){return(0,Fn.default)(r,t,!0)},smallestVersion:function(r){return(0,Mn.default)(r)?(0,Pn.default)(r)?.raw??"0.0.0":"0.0.0"}});var jn={"sha256-":"SHA-256","sha384-":"SHA-384","sha512-":"SHA-512"},La=r=>{for(let t of Object.keys(jn))if(r.startsWith(t))return{algorithm:jn[t],expected:r};return null},Oa=r=>{let t=new Uint8Array(r),i="";for(let s=0;s<t.length;s++)i+=String.fromCharCode(t[s]);return btoa(i)},Qt=async(r,t)=>{let i=La(t);if(!i)throw new TypeError(`Unsupported integrity prefix in '${t}'. Expected sha256-, sha384-, or sha512-.`);let s=typeof crypto<"u"&&crypto.subtle?crypto.subtle:void 0;if(!s)throw new Error("SubtleCrypto is not available in this environment.");let c=await s.digest(i.algorithm,r),m=t.substring(0,t.indexOf("-")+1)+Oa(c);if(m!==i.expected)throw new Error(`Integrity mismatch: expected ${i.expected}, got ${m}`)};var Dn=()=>{let r=i=>i.ok?i:Promise.reject(new X(`${i.status} - ${i.statusText}`)),t=i=>s=>{let c=s instanceof Error?s.message:String(s);throw new X(`Fetch of '${i}' returned ${c}`)};return{provide:async function(i,s={}){if(typeof i!="string")return Promise.resolve(i);let c=async m=>{if(!s.integrity)return m.json();let R=await m.arrayBuffer();return await Qt(R,s.integrity),JSON.parse(new TextDecoder().decode(R))};return fetch(i).then(r).then(c).catch(t(i))}}};var Vn=()=>{let r=s=>s.ok?s:Promise.reject(new Error(`${s.status} - ${s.statusText}`)),t=s=>c=>(c.exposes||(c.exposes=[]),c.shared||(c.shared=[]),c.url||(c.url=s),c),i=s=>c=>{let m=c instanceof Error?c.message:String(c);throw new X(`Fetch of '${s}' returned ${m}`)};return{provide:async function(s,c={}){let m=async R=>{if(!c.integrity)return R.json();let S=await R.arrayBuffer();return await Qt(S,c.integrity),JSON.parse(new TextDecoder().decode(S))};return fetch(s).then(r).then(m).then(t(s)).catch(i(s))}}};var $e=class r{constructor(t){this.item=t}item;static of(t){return new r(t)}static empty(){return r.of(void 0)}isPresent(){return typeof this.item<"u"&&this.item!==null}set(t){return r.of(t)}ifPresent(t){this.isPresent()&&t(this.item)}map(t){if(!this.isPresent())return r.empty();let i=t(this.item);return i instanceof r?i:r.of(i)}orElse(t){return this.isPresent()?this.item:t}orThrow(t){if(this.isPresent())return this.item;throw typeof t=="function"?t():typeof t=="string"?new Error(t):t}get(){return this.item}};var Gn=r=>{let t=r.storage("remotes",{});r.clearStorage&&t.clear();let i=t.get()??{};return{contains:function(s){return!!i[s]},remove:function(s){return delete i[s],this},addOrUpdate:function(s,c){return i[s]=c,this},tryGet:function(s){return $e.of(i[s])},tryGetModule:function(s,c){return $e.of(i[s]?.exposes.find(m=>m.moduleName===c)).map(m=>J(i[s].scopeUrl,m.file))},getAll:function(){return i},commit:function(){return t.set(i),this}}};var Un=r=>{let t=r.storage("scoped-externals",{});r.clearStorage&&t.clear();let i=t.get()??{};return{addExternal:function(s,c,m){return i[s]||(i[s]={}),i[s][c]=m,this},remove:function(s){return delete i[s],this},getAll:function(){return i},tryGet:function(s){return $e.of(i[s])},commit:function(){return t.set(i),this}}};var qn=r=>{let t=r.storage("shared-externals",{[Ee]:{}});r.clearStorage&&t.clear();let i=t.get();return{getFromScope:function(s){return{...i[s??Ee]}},addOrUpdate:function(s,c,m){return i[m??Ee]||(i[m??Ee]={}),i[m??Ee][s]=c,this},getScopes:function(s={includeGlobal:!0}){return s.includeGlobal?Object.keys(i):Object.keys(i).filter(c=>c!==Ee)},removeFromAllScopes:function(s){Object.values(i).forEach(c=>{let m=[];Object.entries(c).forEach(([R,S])=>{let h=[];if(S.versions.forEach((f,y)=>{let T=f.remotes.findIndex(M=>M.name===s);~T&&f.remotes.splice(T,1),f.remotes.length===0&&h.push(y)}),h.length>0){for(let f=h.length-1;f>=0;f--)S.versions.splice(h[f],1);S.dirty=!0,S.versions.length===0&&m.push(R)}}),m.forEach(R=>delete c[R])})},scopeType:function(s){switch(s){case Ee:case null:case void 0:return"global";case ko:return"strict";default:return"shareScope"}},tryGet:function(s,c){return $e.of(i[c??Ee]?.[s])},commit:function(){return t.set(i),this}}};var Hn=r=>{let t=[];return{watchRemoteBuilds:function(i){let s=new EventSource(i);s.onmessage=function(c){JSON.parse(c.data).type===kt.COMPLETED&&(t.forEach(R=>R.close()),r.log.debug(0,"[SSE] Rebuild completed, reloading..."),r.reloadBrowserFn())},s.onerror=function(c){r.log.error(0,"[SSE] Connection error:",c)},t.push(s)},closeAll:function(){t.forEach(i=>i.close()),t.length=0}}};var er=(r,t)=>{try{if(typeof structuredClone=="function")return structuredClone(t)}catch{}try{return JSON.parse(JSON.stringify(t))}catch{}throw new X(`Could not parse storage entry '${String(r)}'`)};var Xn=r=>{let t=r.storage("shared-chunks",{});r.clearStorage&&t.clear();let i=t.get()??{};return{addOrReplace:function(s,c,m){return i[s]||(i[s]={}),i[s][c]=m,this},tryGet:function(s,c){return $e.of(i[s]?.[c])},commit:function(){return t.set(i),this}}};var Wn=r=>({adapters:{versionCheck:_n(),manifestProvider:Dn(),remoteEntryProvider:Vn(),remoteInfoRepo:Gn(r),scopedExternalsRepo:Un(r),sharedExternalsRepo:qn(r),sharedChunksRepo:Xn(r),browser:Fo(r),sse:Hn(r)},config:r});var Na=new Set(["imports","scopes","integrity"]),xa=r=>{let t;try{t=JSON.parse(r)}catch{throw new TypeError("[nf-orchestrator] trusted-types: import map is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("[nf-orchestrator] trusted-types: import map must be a plain object");for(let i of Object.keys(t))if(!Na.has(i))throw new TypeError(`[nf-orchestrator] trusted-types: unexpected key "${i}" in import map`);return r},Aa=r=>{let t=typeof location<"u"?location.href:"http://localhost/",i;try{i=new URL(r,t)}catch{throw new TypeError(`[nf-orchestrator] trusted-types: invalid script URL "${r}"`)}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new TypeError(`[nf-orchestrator] trusted-types: disallowed protocol "${i.protocol}" for script URL`);return r},Bn={createScript:r=>r,createScriptURL:r=>r},ct=null,lt=(r="nfo")=>{if(r===!1)return Bn;if(ct)return ct;let t=globalThis.trustedTypes;if(!t)return ct=Bn,ct;let i=t.createPolicy(r,{createScript:xa,createScriptURL:Aa});return ct={createScript:s=>i.createScript(s),createScriptURL:s=>i.createScriptURL(s)},ct};var tr=(r,t="nfo")=>(i,s={})=>{s?.override&&document.head.querySelectorAll(`script[type="${r}"]`).forEach(m=>m.remove());let c=lt(t);return document.head.appendChild(Object.assign(document.createElement("script"),{type:r,text:c.createScript(JSON.stringify(i))})),Promise.resolve(i)};var Yn=(r="nfo")=>({loadModuleFn:t=>import(lt(r).createScriptURL(t)),setImportMapFn:tr("importmap",r),reloadBrowserFn:()=>{window.location.reload()}});var Jn=r=>{let t=Yn(r.trustedTypesPolicyName);return{setImportMapFn:r.setImportMapFn??t.setImportMapFn,loadModuleFn:r.loadModuleFn??t.loadModuleFn,reloadBrowserFn:r.reloadBrowserFn??t.reloadBrowserFn}};var zn=r=>{let t=r?.manifestIntegrity?{manifestIntegrity:r.manifestIntegrity}:{};return r?.hostRemoteEntry?typeof r.hostRemoteEntry=="string"?{hostRemoteEntry:{name:"__NF-HOST__",url:r.hostRemoteEntry},...t}:{hostRemoteEntry:{name:"__NF-HOST__",...r.hostRemoteEntry},...t}:{hostRemoteEntry:!1,...t}};var Kn={debug:()=>{},error:()=>{},warn:()=>{}};var rr={debug:0,warn:1,error:2};var Zn=(r,t)=>Object.keys(rr).filter(s=>isNaN(Number(s))).reduce((s,c)=>({...s,[c]:(m,R,S)=>{rr[c]>=rr[t]&&r[c](m,R,S)}}),{level:t});var Qn=({logger:r,logLevel:t,sse:i})=>({log:Zn(r??Kn,t??"error"),sse:!!i});var ei=r=>(t,i)=>{globalThis[r]||(globalThis[r]={});let s=globalThis[r];s[t]||(s[t]=i);let c={get(){return er(t,s[t])},set(m){return s[t]=er(t,m),c},clear(){return s[t]=er(t,i),this}};return c};var ti=r=>({storage:r.storage?r.storage(r.storageNamespace??"__NATIVE_FEDERATION__"):ei(r.storageNamespace??"__NATIVE_FEDERATION__"),clearStorage:r.clearStorage??!1});var ri={latestSharedExternal:!1,overrideCachedRemotes:"init-only",overrideCachedRemotesIfURLMatches:!1};var oi=r=>({strict:typeof r.strict=="boolean"?{strictRemoteEntry:r.strict,strictExternalCompatibility:r.strict,strictExternalSameVersionCompatibility:r.strict,strictExternalVersion:r.strict,strictImportMap:r.strict}:{strictRemoteEntry:r.strict?.strictRemoteEntry??!1,strictExternalCompatibility:r.strict?.strictExternalCompatibility??!1,strictExternalSameVersionCompatibility:r.strict?.strictExternalSameVersionCompatibility??!1,strictExternalVersion:r.strict?.strictExternalVersion??!1,strictImportMap:r.strict?.strictImportMap??!1},profile:{...ri,...r.profile??{}}});var ni=r=>({...Jn(r),...zn(r),...Qn(r),...ti(r),...oi(r)});function ii({log:r},t){return({entry:S,actions:h})=>{let f={imports:{}};return i(S,h,f),c(S,f),r.debug(9,`[${S.name}] Processed actions:`,h),Promise.resolve(f)};function i(S,h,f){if(!S.shared)return;let y=Me(S.url),T=S.integrity,M=new Set(["mapping-or-exposed"]);S.shared.forEach(w=>{if(!w.singleton){let H=J(y,w.outFileName);s(y,w.packageName,H,f),R(f,H,T,w.outFileName),w?.bundle&&M.add(w?.bundle);return}if(!h[w.packageName]){r.warn(9,`[${S.name}] No action defined for shared external '${w.packageName}', skipping.`);return}if(h[w.packageName].action==="skip"){if(!w.shareScope)return;if(h[w.packageName].override){s(y,w.packageName,h[w.packageName].override,f);return}}if(w?.bundle&&M.add(w?.bundle),h[w.packageName].action==="scope"){let H=J(y,w.outFileName);s(y,w.packageName,H,f),R(f,H,T,w.outFileName);return}if(w.shareScope){let H=J(y,w.outFileName);s(y,w.packageName,H,f),R(f,H,T,w.outFileName);return}let K=J(y,w.outFileName);f.imports[w.packageName]=K,R(f,K,T,w.outFileName)}),m(f,S,y,M)}function s(S,h,f,y){y.scopes||(y.scopes={}),y.scopes[S]||(y.scopes[S]={}),y.scopes[S][h]=f}function c(S,h){if(!S.exposes)return;let f=Me(S.url);S.exposes.forEach(y=>{let T=J(S.name,y.key),M=J(f,y.outFileName);h.imports[T]=M,R(h,M,S.integrity,y.outFileName)})}function m(S,h,f,y){return Array.from(y).forEach(T=>{t.sharedChunksRepo.tryGet(h.name,T).ifPresent(M=>{M.forEach(w=>{let K=J(f,w);s(f,Tt(w),K,S),R(S,K,h.integrity,w)})})}),S}function R(S,h,f,y){let T=f?.[y];T&&(S.integrity||(S.integrity={}),S.integrity[h]=T)}}var Fa=r=>r?typeof r=="string"?{name:r}:r:{};function si(r,t){return async(c,m)=>{let{name:R,integrity:S}=Fa(m);if(R&&i(c,R))return r.log.debug(7,`Found remote '${R}' in storage, omitting fetch.`),$e.empty();try{let h=S?await t.remoteEntryProvider.provide(c,{integrity:S}):await t.remoteEntryProvider.provide(c);if(r.log.debug(7,`[${h.name}] Fetched from '${h.url}', exposing: ${JSON.stringify(h.exposes)}`),R&&h.name!==R){let f=`Fetched remote '${h.name}' does not match requested '${R}'.`;if(r.strict.strictRemoteEntry)throw r.log.error(7,f),new X("Could not fetch remote entry");r.log.warn(7,f+" Omitting expected name.")}return t.remoteInfoRepo.contains(h.name)&&(h.override=!0,r.log.debug(7,`Overriding existing remote '${R}' with '${c}'.`)),$e.of(s(h))}catch(h){return r.log.error(7,`[${R??"unknown"}] Could not fetch remoteEntry from ${c}.`,h),Promise.reject(new X(`[${R??c}] Could not fetch remoteEntry.`))}};function i(c,m){return t.remoteInfoRepo.tryGet(m).map(R=>r.profile.overrideCachedRemotes!=="always"||!r.profile.overrideCachedRemotesIfURLMatches&&c===J(R.scopeUrl,"remoteEntry.json")).orElse(!1)}function s(c){return r.sse&&(c.buildNotificationsEndpoint?(t.sse.watchRemoteBuilds(J(Me(c.url),c.buildNotificationsEndpoint)),r.log.debug(7,`Registered SSE endpoint of remote '${c.name}' `)):r.log.debug(7,`Remote ${c.name} has no defined 'buildNotificationsEndpoint'`)),c}}function ai(r,t){return h=>{try{h?.override&&i(h),s(h);let f=c(h);return m(h),Promise.resolve({entry:h,actions:f})}catch(f){return Promise.reject(f)}};function i(h){t.remoteInfoRepo.remove(h.name),t.scopedExternalsRepo.remove(h.name),t.sharedExternalsRepo.removeFromAllScopes(h.name)}function s({name:h,url:f,exposes:y}){t.remoteInfoRepo.addOrUpdate(h,{scopeUrl:Me(f),exposes:Object.values(y??[]).map(T=>({moduleName:T.key,file:T.outFileName}))})}function c(h){let f={};return h.shared.forEach(y=>{if(!y.version||!t.versionCheck.isValidSemver(y.version)){let T=`[${h.name}][${y.packageName}] Version '${y.version}' is not a valid version.`;if(r.strict.strictExternalVersion)throw r.log.error(8,T),new X(`Could not process remote '${h.name}'`);r.log.warn(8,T)}if(y.singleton){let{action:T,sharedVersion:M}=R(h.name,y);f[y.packageName]={action:T},T==="skip"&&y.shareScope&&M?.remotes[0]?.file&&(f[y.packageName].override=t.remoteInfoRepo.tryGet(M.remotes[0].name).map(w=>J(w.scopeUrl,M.remotes[0].file)).orThrow(()=>(r.log.error(8,`[${y.shareScope??Ee}][${h.name}][${y.packageName}@${y.version}][override] Remote name not found in cache.`),new X(`Could not find override url from remote ${M.remotes[0].name}`))))}else S(h.name,y)}),f}function m(h){h.chunks&&(r.log.debug(8,`Adding chunks for remote "${h.name}", bundles: [${Object.keys(h.chunks).join(", ")}]`),Object.entries(h.chunks).forEach(([f,y])=>{t.sharedChunksRepo.addOrReplace(h.name,f,y)}))}function R(h,f){let y=t.sharedExternalsRepo.tryGet(f.packageName,f.shareScope).orElse({dirty:!1,versions:[]}),T="skip",M=f.version??t.versionCheck.smallestVersion(f.requiredVersion),w={file:f.outFileName,strictVersion:f.strictVersion,requiredVersion:f.requiredVersion||M,name:h,bundle:f.bundle,cached:!1};t.sharedExternalsRepo.scopeType(f.shareScope)==="strict"&&(w.requiredVersion=M,T="share");let H=y.versions.find(v=>v.action==="share"),ae=!H||t.versionCheck.isCompatible(H.tag,w.requiredVersion);if(T==="skip"&&!ae&&w.strictVersion){T="scope";let v=`[${f.shareScope??Ee}][${h}] ${f.packageName}@${f.version} Is not compatible with existing ${f.packageName}@${H.tag} requiredRange '${H.remotes[0]?.requiredVersion}'`;if(r.strict.strictExternalCompatibility)throw r.log.error(8,v),new X(`Could not process remote '${h}'`);r.log.warn(8,v)}let pe=y.versions.find(v=>v.tag===M);if(pe){if(w.strictVersion&&pe.remotes[0].requiredVersion!==w.requiredVersion){let v=`[${h}][${f.packageName}@${f.version}] Required version '${w.requiredVersion}' does not match existing '${pe.remotes[0].requiredVersion}'`;if(r.strict.strictExternalCompatibility)throw r.log.error(8,v),new X(`Could not process remote '${h}'`);r.log.warn(8,v)}pe.remotes.push(w)}else H||(T="share"),w.cached=T!=="skip",y.versions.push({tag:M,action:T,host:!1,remotes:[w]});return t.sharedExternalsRepo.addOrUpdate(f.packageName,{dirty:y.dirty,versions:y.versions.sort((v,P)=>t.versionCheck.compare(P.tag,v.tag))},f.shareScope),{action:T,sharedVersion:H}}function S(h,f){t.scopedExternalsRepo.addExternal(h,f.packageName,{tag:f.version??t.versionCheck.smallestVersion(f.requiredVersion),file:f.outFileName,bundle:f.bundle})}}var Pa=({config:r,adapters:t})=>({getRemoteEntry:si(r,t),updateCache:ai(r,t),convertToImportMap:ii(r,t),commitChanges:Xt(r,t)}),ci=({config:r,adapters:t})=>({flow:Pa({config:r,adapters:t}),adapters:t,config:r}),li=({flow:r,adapters:t,config:i})=>{let s=async m=>r.updateCache(m).then(r.convertToImportMap).then(r.commitChanges),c=(m,R)=>r.getRemoteEntry(m,R).then(S=>S.map(s).orElse(Promise.resolve())).then(()=>({config:i,adapters:t,initRemoteEntry:c}));return c};var fi=(r,t={})=>{let{adapters:i,config:s}=Wn(ni(t)),c=S=>s.log.debug(0,S,{remotes:{...i.remoteInfoRepo.getAll()},"shared-externals":i.sharedExternalsRepo.getScopes({includeGlobal:!0}).reduce((h,f)=>({...h,[f]:i.sharedExternalsRepo.getFromScope(f)}),{}),"scoped-externals":i.scopedExternalsRepo.getAll()}),m=Ao(xo({adapters:i,config:s})),R=li(ci({config:s,adapters:i}));return m(r).then(({loadRemoteModule:S})=>{let h={config:s,adapters:i,loadRemoteModule:S,as:()=>({loadRemoteModule:S,load:S}),load:S},f=async(y,T)=>{let M=typeof T=="string"?T:T?.name;return R(y,T).catch(w=>(c(`[dynamic-init][${M??y}] STATE DUMP`),s.strict.strictRemoteEntry?Promise.reject(w):(console.warn("Failed to initialize remote entry, continuing anyway."),Promise.resolve()))).then(()=>({...h,initRemoteEntry:f}))};return{...h,initRemoteEntry:f}}).catch(S=>(c("[init] STATE DUMP"),Promise.reject(S)))};var pi={debug:(r,t,i)=>i?console.log(`[DEBUG][${r}]: ${t}`,i):console.log(`[DEBUG][${r}]: ${t}`),error:(r,t,i)=>i?console.error(`[NF][${r}]: ${t}`,i):console.error(`[NF][${r}]: ${t}`),warn:(r,t,i)=>i?console.warn(`[NF][${r}]: ${t}`,i):console.warn(`[NF][${r}]: ${t}`)};var ui=(r={shimMode:!1},t="nfo")=>({loadModuleFn:i=>{let s=lt(t).createScriptURL(i);return importShim(String(s))},setImportMapFn:tr(r.shimMode?"importmap-shim":"importmap",t),reloadBrowserFn:()=>{window.location.reload()}});(async()=>{let r,t=document.querySelector('meta[name="mfe-feed"]')?.getAttribute("content");t&&(r=t);let i=document.getElementById("mfe-manifest");if(!r&&i?.textContent&&(r=JSON.parse(i.textContent)),!r){console.error(`Please provide a manifest in the HTML file:
12
+ `,E+=`${be}:${me==="global"?`importShim._i.get(impt${F})||impt${F++}`:`impt${F++}`},`}$+=`${dr}i=await WebAssembly.instantiate(importShim._s[${N}],{${E}});importShim._i.set($_ns,i);`,E="";for(let{name:o,kind:me}of I)$+=`export let ${o}=i.exports['${o}'];`,me==="global"&&($+=`try{${o}=${o}.value}catch(_){${o}=undefined}`),E+=`${o},`;$+=`if(h)h.accept(m=>({${E}}=m))`}else if(k==="json")$=`${dr}j=JSON.parse(${JSON.stringify($)});export{j as default};if(h)h.accept(m=>j=m.default)`;else if(k==="css")$=`${dr}s=h&&h.data.s||new CSSStyleSheet();s.replaceSync(${JSON.stringify($.replace(Ci,(I,j="",N,F)=>`url(${j}${Ur(N||F,b)}${j})`))});if(h){h.data.s=s;h.accept(()=>{})}export default s`;else if(k==="ts"){nt||await ao();let I=nt($,b);$=I===void 0?$:I}return{url:b,source:$,type:k}},hr=(n,p,d,g)=>{if(g&&ht[n]){let $=0;for(;ht[n+"#"+ ++$];);n+="#"+$}let b=ht[n];return b||(ht[n]=b={u:n,r:g?n:void 0,f:void 0,S:g,L:void 0,a:void 0,d:void 0,b:void 0,s:void 0,n:!1,N:!1,t:null,m:null},b.f=(async()=>{b.S===void 0&&({url:b.r,source:b.S,type:b.t}=await(br[n]||lo(n,p,d)),!b.n&&b.t!=="js"&&!w&&(b.t==="css"&&!rt||b.t==="json"&&!tt||b.t==="wasm"&&!At&&!ut||b.t==="ts")&&(b.n=!0));try{b.a=bi(b.S,b.u)}catch($){ft($),b.a=[[],[],!1]}return b})(),b)},Ti=n=>Error(`${n} feature must be enabled via <script type="esms-options">{ "polyfillEnable": ["${n}"] }<\/script>`),fo=(n,p)=>{n.L||(n.L=n.f.then(()=>{let d=p;n.d=n.a[0].map(({n:g,d:b,t:$,a:k,se:I})=>{let j=$>=4,N=j&&$<6;if(j){if(!w&&(N?!He:!ir))throw Ti(N?"wasm-module-sources":"import-defer");(!N||!ut)&&(n.n=!0)}let F;if(k>0&&!w&&we){let me=n.S.slice(k,I-1);me.includes("json")?tt?F="":n.n=!0:me.includes("css")&&(rt?F="":n.n=!0)}if(b!==-1||!g)return;let E=dt(g,n.r||n.u);if((E.n||B)&&(n.n=!0),(b>=0||E.N)&&(n.N=!0),b!==-1)return;if(Ae&&Ae(E.r)&&!N)return{l:{b:E.r},s:!1};d.integrity&&(d={...d,integrity:void 0});let o={l:hr(E.r,d,n.r,F),s:N};return F===""&&(o.l.b=o.l.u),o.s||fo(o.l,p),o}).filter(g=>g)}))},bt=()=>{for(let n of document.querySelectorAll(w?"link[rel=modulepreload-shim]":"link[rel=modulepreload]"))n.ep||So(n);for(let n of document.querySelectorAll("script[type]"))n.type==="importmap"+(w?"-shim":"")?n.ep||bo(n):n.type==="module"+(w?"-shim":"")&&(ot=!1,n.ep||Ro(n))},Dt=n=>{let p={};return n.integrity&&(p.integrity=n.integrity),n.referrerPolicy&&(p.referrerPolicy=n.referrerPolicy),n.fetchPriority&&(p.priority=n.fetchPriority),n.crossOrigin==="use-credentials"?p.credentials="include":n.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p},gr=Promise.resolve(),po=!1,Vt=1,Gt=n=>{if(n===void 0){if(po)return;po=!0,Vt--}--Vt===0&&!z&&(w||!Fe)&&(document.removeEventListener("DOMContentLoaded",mo),document.dispatchEvent(new Event("DOMContentLoaded")))},Er=1,uo=()=>{--Er===0&&!z&&(w||!Fe)&&(window.removeEventListener("load",ho),window.dispatchEvent(new Event("load")))},mo=async()=>{await We,Gt()},ho=async()=>{await We,Gt(),uo()};c&&(document.addEventListener("DOMContentLoaded",mo),window.addEventListener("load",ho));let go=async()=>{await We,bt(),document.readyState==="complete"&&yr()},Rt=1,yr=()=>{--Rt===0&&(Gt(),!z&&(w||!Fe)&&(document.removeEventListener("readystatechange",go),document.dispatchEvent(new Event("readystatechange"))))},Eo=n=>n.nextSibling||n.parentNode&&Eo(n.parentNode),yo=(n,p)=>n.ep||!p&&(!n.src&&!n.innerHTML||!Eo(n))||n.getAttribute("noshim")!==null||!(n.ep=!0),bo=(n,p=Rt>0)=>{if(!yo(n,p)){if(n.src){if(!w)return;to=!0}Et=Et.then(async()=>{je=qr(n.src?await(await so(n.src,Dt(n))).json():JSON.parse(n.innerHTML),n.src||Te,je)}).catch(d=>{d instanceof SyntaxError&&(d=new Error(`Unable to parse import map ${d.message} in: ${n.src||n.innerHTML}`)),ft(d)}),!gt&&ot&&Et.then(()=>gt=je),!ot&&!fr&&(fr=!0,!w&&Fe&&!Ft&&(Fe=!1,c&&ro())),ot=!1}},Ro=(n,p=Rt>0)=>{if(yo(n,p))return;let d=n.getAttribute("async")===null&&Rt>0,g=Vt>0,b=Er>0;b&&Er++,d&&Rt++,g&&Vt++;let $,k=n.lang==="ts";k&&!n.src?$=Promise.resolve(nt||ao()).then(()=>{let I=nt(n.innerHTML,Te);return I!==void 0&&(Vr(),pr=!1),_t(n.src||Te,Te,Dt(n),I===void 0?n.innerHTML:I,!w&&I===void 0,d&&gr,"ts")}).catch(ft):$=_t(n.src||Te,Te,Dt(n),n.src?void 0:n.innerHTML,!w,d&&gr,k?"ts":void 0).catch(ft),z||$.then(()=>n.dispatchEvent(new Event("load"))),d&&!k&&(gr=$.then(yr)),g&&$.then(Gt),b&&$.then(uo)},br={},So=n=>{n.ep=!0,We.then(()=>{Fe&&!w||br[n.href]||(br[n.href]=lo(n.href,Dt(n)))})}})();var X=class extends Error{constructor(t,i){super(t,i),this.name="NFError"}};function J(r,t){return r=r.endsWith("/")?r.slice(0,-1):r,t=t.startsWith("/")?t.slice(1):t,`${r}/${t}`}function Me(r){if(!r)return"";let t=r.split("/");return(t[t.length-1]===""||t[t.length-1].includes("."))&&t.pop(),t.length<1?"":`${t.join("/")}/`}function Co(r,t){return(f={})=>(r.manifestIntegrity?t.manifestProvider.provide(f,{integrity:r.manifestIntegrity}):t.manifestProvider.provide(f)).catch(T=>(r.log.error(1,"Could not fetch manifest.",T),Promise.reject(new X("Failed to fetch manifest")))).then(i).then(c).then(S).then(h);function i(f){if(!r.hostRemoteEntry)return f;let{name:y,url:T,cacheTag:M,integrity:w}=r.hostRemoteEntry,K=M?`${T}?cacheTag=${M}`:T;return{...f,[y]:w?{url:K,integrity:w}:K}}function s(f){return typeof f=="string"?{url:f}:f}async function c(f){let y=Object.entries(f).map(([T,M])=>m(T,M));return Promise.all(y)}async function m(f,y){let{url:T,integrity:M}=s(y),w=!1,K=!1;if(t.remoteInfoRepo.tryGet(f).ifPresent(H=>{r.profile.overrideCachedRemotes!=="never"&&(T!==J(H.scopeUrl,"remoteEntry.json")||r.profile.overrideCachedRemotesIfURLMatches)?(r.log.debug(1,`Overriding existing remote '${f}' with '${T}'.`),w=!0):(r.log.debug(1,`Found remote '${f}' in storage, omitting fetch.`),K=!0)}),K)return!1;try{let H=M?await t.remoteEntryProvider.provide(T,{integrity:M}):await t.remoteEntryProvider.provide(T);return r.log.debug(1,`Fetched '${H.name}' from '${H.url}', exposing: ${JSON.stringify(H.exposes)}`),R(H,f,w)}catch(H){return r.strict.strictRemoteEntry?(r.log.error(1,`Could not fetch remote '${f}'.`,H),Promise.reject(new X(`Could not fetch remote '${f}'`))):(r.log.warn(1,`Could not fetch remote '${f}'. skipping init.`,H),Promise.resolve(!1))}}function R(f,y,T){if(T&&(f.override=T),r.hostRemoteEntry&&y===r.hostRemoteEntry.name&&(f.host=!0,f.name=r.hostRemoteEntry.name),f.name!==y){let M=`Fetched remote '${f.name}' does not match requested '${y}'.`;if(r.strict.strictRemoteEntry)throw new X(M);r.log.warn(1,`${M} Omitting expected name.`)}return f}function S(f){return f.filter(y=>y!==!1)}function h(f){return r.sse&&f.forEach(y=>{if(y.buildNotificationsEndpoint){t.sse.watchRemoteBuilds(J(Me(y.url),y.buildNotificationsEndpoint)),r.log.debug(1,`Registered SSE endpoint of remote '${y.name}' `);return}r.log.debug(1,`Remote ${y.name} has no defined 'buildNotificationsEndpoint'`)}),f}}function Io(r,t){return h=>{try{return h.forEach(f=>{f?.override&&i(f),s(f),c(f),m(f)}),Promise.resolve(h)}catch(f){return Promise.reject(f)}};function i(h){t.remoteInfoRepo.remove(h.name),t.scopedExternalsRepo.remove(h.name),t.sharedExternalsRepo.removeFromAllScopes(h.name)}function s({name:h,url:f,exposes:y,integrity:T}){t.remoteInfoRepo.addOrUpdate(h,{scopeUrl:Me(f),exposes:Object.values(y??[]).map(M=>({moduleName:M.key,file:M.outFileName})),...T?{integrity:T}:{}})}function c(h){h.shared.forEach(f=>{if(!f.version||!t.versionCheck.isValidSemver(f.version)){let y=`[${h.name}][${f.packageName}] Version '${f.version}' is not a valid version.`;if(r.strict.strictExternalVersion)throw r.log.error(2,y),new X(`Could not process remote '${h.name}'`);r.log.warn(2,y)}f.singleton?R(h.name,f,h):S(h.name,f)})}function m(h){h.chunks&&(r.log.debug(2,`Adding chunks for remote "${h.name}", bundles: [${Object.keys(h.chunks).join(", ")}]`),Object.entries(h.chunks).forEach(([f,y])=>{t.sharedChunksRepo.addOrReplace(h.name,f,y)}))}function R(h,f,y){let T="skip",M=f.version??t.versionCheck.smallestVersion(f.requiredVersion),w={file:f.outFileName,name:h,bundle:f.bundle,strictVersion:f.strictVersion,cached:!1,requiredVersion:f.requiredVersion||M},K=t.sharedExternalsRepo.scopeType(f.shareScope);K==="strict"&&(T="share",w.requiredVersion=M);let H=t.sharedExternalsRepo.tryGet(f.packageName,f.shareScope).orElse({dirty:!1,versions:[]}),ae=H.versions.find(v=>v.tag===f.version),pe=H.dirty;if(ae){if(w.strictVersion&&ae.remotes[0].requiredVersion!==w.requiredVersion){let v=`[${h}][${f.packageName}@${f.version}] Required version-range '${w.requiredVersion}' does not match cached version-range '${ae.remotes[0].requiredVersion}'`;if(r.strict.strictExternalSameVersionCompatibility)throw r.log.error(2,v),new X(`Could not process remote '${y.name}'`);r.log.warn(2,v)}!ae.host&&y?.host?(ae.host=!0,ae.remotes.unshift(w)):ae.remotes.push(w)}else K!=="strict"&&(pe=!0),H.versions.push({tag:M,action:T,host:!!y?.host,remotes:[w]});t.sharedExternalsRepo.addOrUpdate(f.packageName,{dirty:pe,versions:H.versions.sort((v,P)=>t.versionCheck.compare(P.tag,v.tag))},f.shareScope)}function S(h,f){t.scopedExternalsRepo.addExternal(h,f.packageName,{tag:f.version??t.versionCheck.smallestVersion(f.requiredVersion),file:f.outFileName,bundle:f.bundle})}}var Ee="__GLOBAL__",ko="strict";function To(r,t){return()=>{for(let s of t.sharedExternalsRepo.getScopes()){let c=t.sharedExternalsRepo.getFromScope(s);try{Object.entries(c).filter(([m,R])=>R.dirty).forEach(([m,R])=>t.sharedExternalsRepo.addOrUpdate(m,i(m,R),s))}catch(m){return r.log.error(3,`[${s??Ee}] failed to determine shared externals.`,{sharedExternals:c,error:m}),Promise.reject(new X(`Could not determine shared externals in scope ${s}.`,m))}}return Promise.resolve()};function i(s,c){if(c.versions.length===1)return c.versions[0].action="share",c.dirty=!1,c;let m=c.versions.find(R=>R.host);if(!m&&r.profile.latestSharedExternal&&(m=c.versions[0]),!m){let R=Number.MAX_VALUE;c.versions.forEach(S=>{let h=c.versions.filter(f=>!f.remotes[0].cached&&f.remotes[0].strictVersion&&!t.versionCheck.isCompatible(S.tag,f.remotes[0].requiredVersion)).length;h<R&&(R=h,m=S)})}if(!m)throw new X(`[${s}] Could not determine shared version!`);return c.versions.forEach(R=>{if(t.versionCheck.isCompatible(m.tag,R.remotes[0].requiredVersion)){R.action="skip";return}if(r.strict.strictExternalCompatibility&&R.remotes[0].strictVersion)throw r.log.error(3,`[${R.remotes[0].name}][${s}@${R.tag}] Is not compatible with requiredRange '${m.remotes[0]?.requiredVersion}' from remote '${m.remotes[0].name}'.`),new X(`External ${s}@${R.tag} could not be shared.`);R.action=R.remotes[0].strictVersion?"scope":"skip"}),m.action="share",c.dirty=!1,c}}var kt;(function(r){r.COMPLETED="federation-rebuild-complete",r.ERROR="federation-rebuild-error",r.CANCELLED="federation-rebuild-cancelled"})(kt||(kt={}));var Lo="@nf-internal";function Tt(r){r.startsWith("./")&&(r=r.slice(2));let t=r.replace(/.(m|c)?js$/,"");return Lo+"/"+t}function Oo(r,t){return()=>{let v={imports:{}},P={};try{return i(v,P),c(v,P),h(v,P),M(v,P),H(v,P),Promise.resolve(v)}catch(q){return Promise.reject(q)}};function i(v,P){let q=t.scopedExternalsRepo.getAll();for(let[V,B]of Object.entries(q)){let z=t.remoteInfoRepo.tryGet(V).orThrow(()=>(r.log.error(4,`[scoped][${V}] Remote name not found in cache.`),new X("Could not create ImportMap.")));y(v,z.scopeUrl,s(B,z.scopeUrl));for(let ie of Object.values(B))ae(v,J(z.scopeUrl,ie.file),V,ie.file);Object.values(B).filter(ie=>!!ie.bundle).forEach(ie=>K(P,V,ie.bundle))}return v}function s(v,P){let q={};for(let[V,B]of Object.entries(v))q[V]=J(P,B.file);return q}function c(v,P){let q=t.sharedExternalsRepo.getScopes({includeGlobal:!1});for(let V of q)m(v,V,P);return v}function m(v,P,q){let V=t.sharedExternalsRepo.getFromScope(P);for(let[B,z]of Object.entries(V)){let ie,Ne;for(let te of z.versions){if(te.action==="scope"){for(let ue of te.remotes){let et=pe(P,ue.name,B),Ve=J(et,ue.file);y(v,et,{[B]:Ve}),ae(v,Ve,ue.name,ue.file),K(q,ue.name,ue.bundle),ue.cached=!0}continue}let we=pe(P,te.remotes[0].name,B),xe=J(we,te.remotes[0].file),Qe={name:te.remotes[0].name,file:te.remotes[0].file};te.remotes[0].cached=!0,te.action==="share"&&K(q,te.remotes[0].name,te.remotes[0].bundle),te.action==="skip"&&(ie||(ie=R(z,P,B)??"NOT_AVAILABLE"),ie!=="NOT_AVAILABLE"&&(Ne||(Ne=pe(P,ie.remotes[0].name,B)),xe=J(Ne,ie.remotes[0].file),Qe={name:ie.remotes[0].name,file:ie.remotes[0].file},ie.remotes[0].cached=!0,te.remotes[0].cached=!1)),te.remotes.forEach(ue=>{let et=pe(P,ue.name,B);y(v,et,{[B]:xe})}),ae(v,xe,Qe.name,Qe.file)}t.sharedExternalsRepo.addOrUpdate(B,z,P)}}function R(v,P,q){let V=v.versions.filter(z=>z.action==="share"),B=`${P}.${q}`;if(V.length>1&&S(B),V.length<1){if(r.strict.strictImportMap)throw r.log.error(4,`[${P}][${q}] shareScope has no override version.`),new X("Could not create ImportMap.");r.log.debug(4,`[${P}][${q}] shareScope has no override version, scoping override versions.`)}return V[0]}function S(v){if(r.strict.strictImportMap)throw r.log.error(4,`[${v}] ShareScope external has multiple shared versions.`),new X("Could not create ImportMap.");r.log.warn(4,`ShareScope external ${v} has multiple shared versions.`)}function h(v,P){let q=t.sharedExternalsRepo.getFromScope();for(let[V,B]of Object.entries(q)){for(let z of B.versions){if(z.action==="skip")continue;if(z.action==="scope"){for(let te of z.remotes){let we=pe(Ee,te.name,V),xe=J(we,te.file);y(v,we,{[V]:xe}),ae(v,xe,te.name,te.file),te.cached=!0,K(P,te.name,te.bundle)}continue}if(v.imports[V]){f(V);continue}let ie=pe(Ee,z.remotes[0].name,V),Ne=J(ie,z.remotes[0].file);T(v,{[V]:Ne}),ae(v,Ne,z.remotes[0].name,z.remotes[0].file),K(P,z.remotes[0].name,z.remotes[0].bundle),z.remotes[0].cached=!0}t.sharedExternalsRepo.addOrUpdate(V,B)}return v}function f(v){if(r.strict.strictImportMap)throw r.log.error(4,`[${v}] Shared external has multiple shared versions.`),new X("Could not create ImportMap.");r.log.warn(4,`Singleton external ${v} has multiple shared versions.`)}function y(v,P,q){v.scopes||(v.scopes={}),v.scopes[P]||(v.scopes[P]={}),v.scopes[P]=Object.assign(v.scopes[P],q)}function T(v,P){v.imports=Object.assign(v.imports,P)}function M(v,P){let q=t.remoteInfoRepo.getAll();for(let[V,B]of Object.entries(q))w(v,V,B),K(P,V,"mapping-or-exposed")}function w(v,P,q){for(let V of q.exposes){let B=J(P,V.moduleName),z=J(q.scopeUrl,V.file);v.imports[B]=z,ae(v,z,P,V.file)}}function K(v,P,q){return q&&(v[P]||(v[P]=new Set),v[P].add(q)),v}function H(v,P){return Object.entries(P).forEach(([q,V])=>{let B=pe("CHUNKS",q),z=Array.from(V).reduce((ie,Ne)=>(t.sharedChunksRepo.tryGet(q,Ne).ifPresent(te=>{te.forEach(we=>{let xe=J(B,we);ie[Tt(we)]=xe,ae(v,xe,q,we)})}),ie),{});Object.keys(z).length>0&&y(v,B,z)}),v}function ae(v,P,q,V){let B=t.remoteInfoRepo.tryGet(q).get()?.integrity?.[V];B&&(v.integrity||(v.integrity={}),v.integrity[P]=B)}function pe(v,P,q){return t.remoteInfoRepo.tryGet(P).map(V=>V.scopeUrl).orThrow(()=>(q?r.log.error(4,`[${v}][${q}][${P}] Remote name not found in cache.`):r.log.error(4,`[${v}][${P}] Remote name not found in cache.`),new X("Could not create ImportMap.")))}}function Xt(r,t){return c=>Promise.resolve(c).then(i).then(s);function i(c){return t.browser.setImportMapFn(c),r.log.debug(5,"Added import map to browser.",c),c}function s(){t.remoteInfoRepo.commit(),t.scopedExternalsRepo.commit(),t.sharedExternalsRepo.commit(),t.sharedChunksRepo.commit()}}function No(r,t){let i=(s,c)=>{try{if(!t.remoteInfoRepo.contains(s))throw new X(`Remote '${s}' is not initialized.`);let m=t.remoteInfoRepo.tryGetModule(s,c).orThrow(new X(`Exposed module '${c}' from remote '${s}' not found in storage.`));return r.log.debug(6,`Loading initialized module '${m}'`),t.browser.importModule(m)}catch(m){return r.log.error(6,`Failed to load module ${J(s,c)}: `,{error:m}),Promise.reject(new X(`Failed to load module ${J(s,c)}`))}};return()=>Promise.resolve(i)}var us=({config:r,adapters:t})=>({getRemoteEntries:Co(r,t),processRemoteEntries:Io(r,t),determineSharedExternals:To(r,t),generateImportMap:Oo(r,t),commitChanges:Xt(r,t),exposeModuleLoader:No(r,t)}),xo=({config:r,adapters:t})=>({flow:us({config:r,adapters:t}),adapters:t,config:r}),Ao=({flow:r,adapters:t,config:i})=>s=>r.getRemoteEntries(s).then(r.processRemoteEntries).then(r.determineSharedExternals).then(r.generateImportMap).then(r.commitChanges).then(r.exposeModuleLoader).then(c=>({config:i,adapters:t,loadRemoteModule:c}));var Fo=r=>({setImportMapFn:r.setImportMapFn,importModule:r.loadModuleFn});var xn=It(Jo()),An=It(In()),Fn=It(Ye()),Pn=It(Ln()),Mn=It(Nn()),_n=()=>({isValidSemver:function(r){return(0,xn.default)(r)!==null},isCompatible:function(r,t){return(0,An.default)(r,t)},compare:function(r,t){return(0,Fn.default)(r,t,!0)},smallestVersion:function(r){return(0,Mn.default)(r)?(0,Pn.default)(r)?.raw??"0.0.0":"0.0.0"}});var jn={"sha256-":"SHA-256","sha384-":"SHA-384","sha512-":"SHA-512"},La=r=>{for(let t of Object.keys(jn))if(r.startsWith(t))return{algorithm:jn[t],expected:r};return null},Oa=r=>{let t=new Uint8Array(r),i="";for(let s=0;s<t.length;s++)i+=String.fromCharCode(t[s]);return btoa(i)},Qt=async(r,t)=>{let i=La(t);if(!i)throw new TypeError(`Unsupported integrity prefix in '${t}'. Expected sha256-, sha384-, or sha512-.`);let s=typeof crypto<"u"&&crypto.subtle?crypto.subtle:void 0;if(!s)throw new Error("SubtleCrypto is not available in this environment.");let c=await s.digest(i.algorithm,r),m=t.substring(0,t.indexOf("-")+1)+Oa(c);if(m!==i.expected)throw new Error(`Integrity mismatch: expected ${i.expected}, got ${m}`)};var Dn=()=>{let r=i=>i.ok?i:Promise.reject(new X(`${i.status} - ${i.statusText}`)),t=i=>s=>{let c=s instanceof Error?s.message:String(s);throw new X(`Fetch of '${i}' returned ${c}`)};return{provide:async function(i,s={}){if(typeof i!="string")return Promise.resolve(i);let c=async m=>{if(!s.integrity)return m.json();let R=await m.arrayBuffer();return await Qt(R,s.integrity),JSON.parse(new TextDecoder().decode(R))};return fetch(i).then(r).then(c).catch(t(i))}}};var Vn=()=>{let r=s=>s.ok?s:Promise.reject(new Error(`${s.status} - ${s.statusText}`)),t=s=>c=>(c.exposes||(c.exposes=[]),c.shared||(c.shared=[]),c.url||(c.url=s),c),i=s=>c=>{let m=c instanceof Error?c.message:String(c);throw new X(`Fetch of '${s}' returned ${m}`)};return{provide:async function(s,c={}){let m=async R=>{if(!c.integrity)return R.json();let S=await R.arrayBuffer();return await Qt(S,c.integrity),JSON.parse(new TextDecoder().decode(S))};return fetch(s).then(r).then(m).then(t(s)).catch(i(s))}}};var $e=class r{constructor(t){this.item=t}item;static of(t){return new r(t)}static empty(){return r.of(void 0)}isPresent(){return typeof this.item<"u"&&this.item!==null}set(t){return r.of(t)}ifPresent(t){this.isPresent()&&t(this.item)}map(t){if(!this.isPresent())return r.empty();let i=t(this.item);return i instanceof r?i:r.of(i)}orElse(t){return this.isPresent()?this.item:t}orThrow(t){if(this.isPresent())return this.item;throw typeof t=="function"?t():typeof t=="string"?new Error(t):t}get(){return this.item}};var Gn=r=>{let t=r.storage("remotes",{});r.clearStorage&&t.clear();let i=t.get()??{};return{contains:function(s){return!!i[s]},remove:function(s){return delete i[s],this},addOrUpdate:function(s,c){return i[s]=c,this},tryGet:function(s){return $e.of(i[s])},tryGetModule:function(s,c){return $e.of(i[s]?.exposes.find(m=>m.moduleName===c)).map(m=>J(i[s].scopeUrl,m.file))},getAll:function(){return i},commit:function(){return t.set(i),this}}};var Un=r=>{let t=r.storage("scoped-externals",{});r.clearStorage&&t.clear();let i=t.get()??{};return{addExternal:function(s,c,m){return i[s]||(i[s]={}),i[s][c]=m,this},remove:function(s){return delete i[s],this},getAll:function(){return i},tryGet:function(s){return $e.of(i[s])},commit:function(){return t.set(i),this}}};var qn=r=>{let t=r.storage("shared-externals",{[Ee]:{}});r.clearStorage&&t.clear();let i=t.get();return{getFromScope:function(s){return{...i[s??Ee]}},addOrUpdate:function(s,c,m){return i[m??Ee]||(i[m??Ee]={}),i[m??Ee][s]=c,this},getScopes:function(s={includeGlobal:!0}){return s.includeGlobal?Object.keys(i):Object.keys(i).filter(c=>c!==Ee)},removeFromAllScopes:function(s){Object.values(i).forEach(c=>{let m=[];Object.entries(c).forEach(([R,S])=>{let h=[];if(S.versions.forEach((f,y)=>{let T=f.remotes.findIndex(M=>M.name===s);~T&&f.remotes.splice(T,1),f.remotes.length===0&&h.push(y)}),h.length>0){for(let f=h.length-1;f>=0;f--)S.versions.splice(h[f],1);S.dirty=!0,S.versions.length===0&&m.push(R)}}),m.forEach(R=>delete c[R])})},scopeType:function(s){switch(s){case Ee:case null:case void 0:return"global";case ko:return"strict";default:return"shareScope"}},tryGet:function(s,c){return $e.of(i[c??Ee]?.[s])},commit:function(){return t.set(i),this}}};var Hn=r=>{let t=[];return{watchRemoteBuilds:function(i){let s=new EventSource(i);s.onmessage=function(c){JSON.parse(c.data).type===kt.COMPLETED&&(t.forEach(R=>R.close()),r.log.debug(0,"[SSE] Rebuild completed, reloading..."),r.reloadBrowserFn())},s.onerror=function(c){r.log.error(0,"[SSE] Connection error:",c)},t.push(s)},closeAll:function(){t.forEach(i=>i.close()),t.length=0}}};var er=(r,t)=>{try{if(typeof structuredClone=="function")return structuredClone(t)}catch{}try{return JSON.parse(JSON.stringify(t))}catch{}throw new X(`Could not clone entry '${String(r)}'`)};var Xn=r=>{let t=r.storage("shared-chunks",{});r.clearStorage&&t.clear();let i=t.get()??{};return{addOrReplace:function(s,c,m){return i[s]||(i[s]={}),i[s][c]=m,this},tryGet:function(s,c){return $e.of(i[s]?.[c])},commit:function(){return t.set(i),this}}};var Wn=r=>({adapters:{versionCheck:_n(),manifestProvider:Dn(),remoteEntryProvider:Vn(),remoteInfoRepo:Gn(r),scopedExternalsRepo:Un(r),sharedExternalsRepo:qn(r),sharedChunksRepo:Xn(r),browser:Fo(r),sse:Hn(r)},config:r});var Na=new Set(["imports","scopes","integrity"]),xa=r=>{let t;try{t=JSON.parse(r)}catch{throw new TypeError("[nf-orchestrator] trusted-types: import map is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("[nf-orchestrator] trusted-types: import map must be a plain object");for(let i of Object.keys(t))if(!Na.has(i))throw new TypeError(`[nf-orchestrator] trusted-types: unexpected key "${i}" in import map`);return r},Aa=r=>{let t=typeof location<"u"?location.href:"http://localhost/",i;try{i=new URL(r,t)}catch{throw new TypeError(`[nf-orchestrator] trusted-types: invalid script URL "${r}"`)}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new TypeError(`[nf-orchestrator] trusted-types: disallowed protocol "${i.protocol}" for script URL`);return r},Bn={createScript:r=>r,createScriptURL:r=>r},ct=null,lt=(r="nfo")=>{if(r===!1)return Bn;if(ct)return ct;let t=globalThis.trustedTypes;if(!t)return ct=Bn,ct;let i=t.createPolicy(r,{createScript:xa,createScriptURL:Aa});return ct={createScript:s=>i.createScript(s),createScriptURL:s=>i.createScriptURL(s)},ct};var tr=(r,t="nfo")=>(i,s={})=>{s?.override&&document.head.querySelectorAll(`script[type="${r}"]`).forEach(m=>m.remove());let c=lt(t);return document.head.appendChild(Object.assign(document.createElement("script"),{type:r,text:c.createScript(JSON.stringify(i))})),Promise.resolve(i)};var Yn=(r="nfo")=>({loadModuleFn:t=>import(lt(r).createScriptURL(t)),setImportMapFn:tr("importmap",r),reloadBrowserFn:()=>{window.location.reload()}});var Jn=r=>{let t=Yn(r.trustedTypesPolicyName);return{setImportMapFn:r.setImportMapFn??t.setImportMapFn,loadModuleFn:r.loadModuleFn??t.loadModuleFn,reloadBrowserFn:r.reloadBrowserFn??t.reloadBrowserFn}};var zn=r=>{let t=r?.manifestIntegrity?{manifestIntegrity:r.manifestIntegrity}:{};return r?.hostRemoteEntry?typeof r.hostRemoteEntry=="string"?{hostRemoteEntry:{name:"__NF-HOST__",url:r.hostRemoteEntry},...t}:{hostRemoteEntry:{name:"__NF-HOST__",...r.hostRemoteEntry},...t}:{hostRemoteEntry:!1,...t}};var Kn={debug:()=>{},error:()=>{},warn:()=>{}};var rr={debug:0,warn:1,error:2};var Zn=(r,t)=>Object.keys(rr).filter(s=>isNaN(Number(s))).reduce((s,c)=>({...s,[c]:(m,R,S)=>{rr[c]>=rr[t]&&r[c](m,R,S)}}),{level:t});var Qn=({logger:r,logLevel:t,sse:i})=>({log:Zn(r??Kn,t??"error"),sse:!!i});var ei=r=>(t,i)=>{globalThis[r]||(globalThis[r]={});let s=globalThis[r];s[t]||(s[t]=i);let c={get(){return er(t,s[t])},set(m){return s[t]=er(t,m),c},clear(){return s[t]=er(t,i),this}};return c};var ti=r=>({storage:r.storage?r.storage(r.storageNamespace??"__NATIVE_FEDERATION__"):ei(r.storageNamespace??"__NATIVE_FEDERATION__"),clearStorage:r.clearStorage??!1});var ri={latestSharedExternal:!1,overrideCachedRemotes:"init-only",overrideCachedRemotesIfURLMatches:!1};var oi=r=>({strict:typeof r.strict=="boolean"?{strictRemoteEntry:r.strict,strictExternalCompatibility:r.strict,strictExternalSameVersionCompatibility:r.strict,strictExternalVersion:r.strict,strictImportMap:r.strict}:{strictRemoteEntry:r.strict?.strictRemoteEntry??!1,strictExternalCompatibility:r.strict?.strictExternalCompatibility??!1,strictExternalSameVersionCompatibility:r.strict?.strictExternalSameVersionCompatibility??!1,strictExternalVersion:r.strict?.strictExternalVersion??!1,strictImportMap:r.strict?.strictImportMap??!1},profile:{...ri,...r.profile??{}}});var ni=r=>({...Jn(r),...zn(r),...Qn(r),...ti(r),...oi(r)});function ii({log:r},t){return({entry:S,actions:h})=>{let f={imports:{}};return i(S,h,f),c(S,f),r.debug(9,`[${S.name}] Processed actions:`,h),Promise.resolve(f)};function i(S,h,f){if(!S.shared)return;let y=Me(S.url),T=S.integrity,M=new Set(["mapping-or-exposed"]);S.shared.forEach(w=>{if(!w.singleton){let H=J(y,w.outFileName);s(y,w.packageName,H,f),R(f,H,T,w.outFileName),w?.bundle&&M.add(w?.bundle);return}if(!h[w.packageName]){r.warn(9,`[${S.name}] No action defined for shared external '${w.packageName}', skipping.`);return}if(h[w.packageName].action==="skip"){if(!w.shareScope)return;if(h[w.packageName].override){s(y,w.packageName,h[w.packageName].override,f);return}}if(w?.bundle&&M.add(w?.bundle),h[w.packageName].action==="scope"){let H=J(y,w.outFileName);s(y,w.packageName,H,f),R(f,H,T,w.outFileName);return}if(w.shareScope){let H=J(y,w.outFileName);s(y,w.packageName,H,f),R(f,H,T,w.outFileName);return}let K=J(y,w.outFileName);f.imports[w.packageName]=K,R(f,K,T,w.outFileName)}),m(f,S,y,M)}function s(S,h,f,y){y.scopes||(y.scopes={}),y.scopes[S]||(y.scopes[S]={}),y.scopes[S][h]=f}function c(S,h){if(!S.exposes)return;let f=Me(S.url);S.exposes.forEach(y=>{let T=J(S.name,y.key),M=J(f,y.outFileName);h.imports[T]=M,R(h,M,S.integrity,y.outFileName)})}function m(S,h,f,y){return Array.from(y).forEach(T=>{t.sharedChunksRepo.tryGet(h.name,T).ifPresent(M=>{M.forEach(w=>{let K=J(f,w);s(f,Tt(w),K,S),R(S,K,h.integrity,w)})})}),S}function R(S,h,f,y){let T=f?.[y];T&&(S.integrity||(S.integrity={}),S.integrity[h]=T)}}var Fa=r=>r?typeof r=="string"?{name:r}:r:{};function si(r,t){return async(c,m)=>{let{name:R,integrity:S}=Fa(m);if(R&&i(c,R))return r.log.debug(7,`Found remote '${R}' in storage, omitting fetch.`),$e.empty();try{let h=S?await t.remoteEntryProvider.provide(c,{integrity:S}):await t.remoteEntryProvider.provide(c);if(r.log.debug(7,`[${h.name}] Fetched from '${h.url}', exposing: ${JSON.stringify(h.exposes)}`),R&&h.name!==R){let f=`Fetched remote '${h.name}' does not match requested '${R}'.`;if(r.strict.strictRemoteEntry)throw r.log.error(7,f),new X("Could not fetch remote entry");r.log.warn(7,f+" Omitting expected name.")}return t.remoteInfoRepo.contains(h.name)&&(h.override=!0,r.log.debug(7,`Overriding existing remote '${R}' with '${c}'.`)),$e.of(s(h))}catch(h){return r.log.error(7,`[${R??"unknown"}] Could not fetch remoteEntry from ${c}.`,h),Promise.reject(new X(`[${R??c}] Could not fetch remoteEntry.`))}};function i(c,m){return t.remoteInfoRepo.tryGet(m).map(R=>r.profile.overrideCachedRemotes!=="always"||!r.profile.overrideCachedRemotesIfURLMatches&&c===J(R.scopeUrl,"remoteEntry.json")).orElse(!1)}function s(c){return r.sse&&(c.buildNotificationsEndpoint?(t.sse.watchRemoteBuilds(J(Me(c.url),c.buildNotificationsEndpoint)),r.log.debug(7,`Registered SSE endpoint of remote '${c.name}' `)):r.log.debug(7,`Remote ${c.name} has no defined 'buildNotificationsEndpoint'`)),c}}function ai(r,t){return h=>{try{h?.override&&i(h),s(h);let f=c(h);return m(h),Promise.resolve({entry:h,actions:f})}catch(f){return Promise.reject(f)}};function i(h){t.remoteInfoRepo.remove(h.name),t.scopedExternalsRepo.remove(h.name),t.sharedExternalsRepo.removeFromAllScopes(h.name)}function s({name:h,url:f,exposes:y}){t.remoteInfoRepo.addOrUpdate(h,{scopeUrl:Me(f),exposes:Object.values(y??[]).map(T=>({moduleName:T.key,file:T.outFileName}))})}function c(h){let f={};return h.shared.forEach(y=>{if(!y.version||!t.versionCheck.isValidSemver(y.version)){let T=`[${h.name}][${y.packageName}] Version '${y.version}' is not a valid version.`;if(r.strict.strictExternalVersion)throw r.log.error(8,T),new X(`Could not process remote '${h.name}'`);r.log.warn(8,T)}if(y.singleton){let{action:T,sharedVersion:M}=R(h.name,y);f[y.packageName]={action:T},T==="skip"&&y.shareScope&&M?.remotes[0]?.file&&(f[y.packageName].override=t.remoteInfoRepo.tryGet(M.remotes[0].name).map(w=>J(w.scopeUrl,M.remotes[0].file)).orThrow(()=>(r.log.error(8,`[${y.shareScope??Ee}][${h.name}][${y.packageName}@${y.version}][override] Remote name not found in cache.`),new X(`Could not find override url from remote ${M.remotes[0].name}`))))}else S(h.name,y)}),f}function m(h){h.chunks&&(r.log.debug(8,`Adding chunks for remote "${h.name}", bundles: [${Object.keys(h.chunks).join(", ")}]`),Object.entries(h.chunks).forEach(([f,y])=>{t.sharedChunksRepo.addOrReplace(h.name,f,y)}))}function R(h,f){let y=t.sharedExternalsRepo.tryGet(f.packageName,f.shareScope).orElse({dirty:!1,versions:[]}),T="skip",M=f.version??t.versionCheck.smallestVersion(f.requiredVersion),w={file:f.outFileName,strictVersion:f.strictVersion,requiredVersion:f.requiredVersion||M,name:h,bundle:f.bundle,cached:!1};t.sharedExternalsRepo.scopeType(f.shareScope)==="strict"&&(w.requiredVersion=M,T="share");let H=y.versions.find(v=>v.action==="share"),ae=!H||t.versionCheck.isCompatible(H.tag,w.requiredVersion);if(T==="skip"&&!ae&&w.strictVersion){T="scope";let v=`[${f.shareScope??Ee}][${h}] ${f.packageName}@${f.version} Is not compatible with existing ${f.packageName}@${H.tag} requiredRange '${H.remotes[0]?.requiredVersion}'`;if(r.strict.strictExternalCompatibility)throw r.log.error(8,v),new X(`Could not process remote '${h}'`);r.log.warn(8,v)}let pe=y.versions.find(v=>v.tag===M);if(pe){if(w.strictVersion&&pe.remotes[0].requiredVersion!==w.requiredVersion){let v=`[${h}][${f.packageName}@${f.version}] Required version '${w.requiredVersion}' does not match existing '${pe.remotes[0].requiredVersion}'`;if(r.strict.strictExternalCompatibility)throw r.log.error(8,v),new X(`Could not process remote '${h}'`);r.log.warn(8,v)}pe.remotes.push(w)}else H||(T="share"),w.cached=T!=="skip",y.versions.push({tag:M,action:T,host:!1,remotes:[w]});return t.sharedExternalsRepo.addOrUpdate(f.packageName,{dirty:y.dirty,versions:y.versions.sort((v,P)=>t.versionCheck.compare(P.tag,v.tag))},f.shareScope),{action:T,sharedVersion:H}}function S(h,f){t.scopedExternalsRepo.addExternal(h,f.packageName,{tag:f.version??t.versionCheck.smallestVersion(f.requiredVersion),file:f.outFileName,bundle:f.bundle})}}var Pa=({config:r,adapters:t})=>({getRemoteEntry:si(r,t),updateCache:ai(r,t),convertToImportMap:ii(r,t),commitChanges:Xt(r,t)}),ci=({config:r,adapters:t})=>({flow:Pa({config:r,adapters:t}),adapters:t,config:r}),li=({flow:r,adapters:t,config:i})=>{let s=async m=>r.updateCache(m).then(r.convertToImportMap).then(r.commitChanges),c=(m,R)=>r.getRemoteEntry(m,R).then(S=>S.map(s).orElse(Promise.resolve())).then(()=>({config:i,adapters:t,initRemoteEntry:c}));return c};var fi=(r,t={})=>{let{adapters:i,config:s}=Wn(ni(t)),c=S=>s.log.debug(0,S,{remotes:{...i.remoteInfoRepo.getAll()},"shared-externals":i.sharedExternalsRepo.getScopes({includeGlobal:!0}).reduce((h,f)=>({...h,[f]:i.sharedExternalsRepo.getFromScope(f)}),{}),"scoped-externals":i.scopedExternalsRepo.getAll()}),m=Ao(xo({adapters:i,config:s})),R=li(ci({config:s,adapters:i}));return m(r).then(({loadRemoteModule:S})=>{let h={config:s,adapters:i,loadRemoteModule:S,as:()=>({loadRemoteModule:S,load:S}),load:S},f=async(y,T)=>{let M=typeof T=="string"?T:T?.name;return R(y,T).catch(w=>(c(`[dynamic-init][${M??y}] STATE DUMP`),s.strict.strictRemoteEntry?Promise.reject(w):(console.warn("Failed to initialize remote entry, continuing anyway."),Promise.resolve()))).then(()=>({...h,initRemoteEntry:f}))};return{...h,initRemoteEntry:f}}).catch(S=>(c("[init] STATE DUMP"),Promise.reject(S)))};var pi={debug:(r,t,i)=>i?console.log(`[DEBUG][${r}]: ${t}`,i):console.log(`[DEBUG][${r}]: ${t}`),error:(r,t,i)=>i?console.error(`[NF][${r}]: ${t}`,i):console.error(`[NF][${r}]: ${t}`),warn:(r,t,i)=>i?console.warn(`[NF][${r}]: ${t}`,i):console.warn(`[NF][${r}]: ${t}`)};var ui=(r={shimMode:!1},t="nfo")=>({loadModuleFn:i=>{let s=lt(t).createScriptURL(i);return importShim(String(s))},setImportMapFn:tr(r.shimMode?"importmap-shim":"importmap",t),reloadBrowserFn:()=>{window.location.reload()}});(async()=>{let r,t=document.querySelector('meta[name="mfe-feed"]')?.getAttribute("content");t&&(r=t);let i=document.getElementById("mfe-manifest");if(!r&&i?.textContent&&(r=JSON.parse(i.textContent)),!r){console.error(`Please provide a manifest in the HTML file:
13
13
  <script type="application/json" id="mfe-manifest">
14
14
  {
15
15
  "remote1": "http://localhost:3000/remoteEntry.json",
@@ -3,6 +3,9 @@ export type NFEventRegistry = {
3
3
  register<T>(type: string, resource: T | NFEventProvider<T>): Promise<void>;
4
4
  onReady<T>(type: string, callback: NFEventConsumer<T>): NFEventUnsubscribe;
5
5
  emit<T>(type: string, data: T): void;
6
- on<T>(type: string, callback: NFEventConsumer<NFEventData<T>>): NFEventUnsubscribe;
6
+ update<T>(type: string, callback: (last: T | undefined) => T): void;
7
+ on<T>(type: string, callback: NFEventConsumer<NFEventData<T>>, opts?: {
8
+ replay?: number;
9
+ }): NFEventUnsubscribe;
7
10
  clear(type?: string): void;
8
11
  };
@@ -1,3 +1,2 @@
1
1
  export { NFEventRegistry } from './event-registry.contract';
2
- export { RegistryOptions } from './registry-options.contract';
3
2
  export { NFEventProvider, NFEventConsumer, NFEventErrorHandler } from './event.contract';
@@ -1,6 +1,6 @@
1
1
  export type NFEventRegistryConfig = {
2
- maxStreams: number;
2
+ maxStreams?: number;
3
3
  maxEvents: number;
4
- removePercentage: number;
4
+ removePercentage?: number;
5
5
  };
6
6
  export type NFEventRegistryOptions = Partial<NFEventRegistryConfig>;
@@ -1,3 +1,3 @@
1
1
  import type { ForManagingEvents } from '../../driver-ports/registry/for-managing-events.port';
2
- import type { NFEventRegistryConfig } from '../../config/registry.contract';
3
- export declare function createRegistry(opts: NFEventRegistryConfig): ForManagingEvents;
2
+ import type { NFEventRegistryOptions } from '../../config/registry.contract';
3
+ export declare function createRegistry(opts: NFEventRegistryOptions): ForManagingEvents;