@softarc/native-federation-orchestrator 4.9.0 → 4.10.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.
Files changed (42) hide show
  1. package/README.md +12 -12
  2. package/fesm2022/@softarc/native-federation-orchestrator.mjs +490 -123
  3. package/fesm2022/@softarc/native-federation-orchestrator.mjs.map +4 -4
  4. package/fesm2022/module-federation.mjs.map +2 -2
  5. package/fesm2022/node.mjs +495 -123
  6. package/fesm2022/node.mjs.map +4 -4
  7. package/fesm2022/options.mjs +25 -2
  8. package/fesm2022/options.mjs.map +3 -3
  9. package/fesm2022/registry.mjs.map +2 -2
  10. package/package.json +3 -3
  11. package/quickstart.mjs +15 -13
  12. package/types/lib/core/1.domain/externals/basis.d.ts +2 -2
  13. package/types/lib/core/1.domain/externals/version.contract.d.ts +3 -0
  14. package/types/lib/core/1.domain/import-map/eager-preloads.d.ts +10 -0
  15. package/types/lib/core/1.domain/pooling/builds.d.ts +7 -1
  16. package/types/lib/core/1.domain/remote/remote-module.contract.d.ts +1 -0
  17. package/types/lib/core/1.domain/remote-entry/remote-entry.contract.d.ts +2 -2
  18. package/types/lib/core/2.app/config/import-map.contract.d.ts +4 -7
  19. package/types/lib/core/2.app/config/index.d.ts +2 -2
  20. package/types/lib/core/2.app/config/mode.contract.d.ts +1 -0
  21. package/types/lib/core/2.app/driver-ports/init/flow.contract.d.ts +2 -4
  22. package/types/lib/core/2.app/driver-ports/init/for-exposing-module-loader.port.d.ts +6 -2
  23. package/types/lib/core/2.app/driving-ports/for-browser-tasks.d.ts +1 -0
  24. package/types/lib/core/2.app/driving-ports/for-remote-info-storage.port.d.ts +1 -0
  25. package/types/lib/core/2.app/steps/collect-eager-preloads.d.ts +4 -0
  26. package/types/lib/core/2.app/steps/preload-hint.d.ts +4 -0
  27. package/types/lib/core/2.app/steps/store-remote-entry.d.ts +0 -14
  28. package/types/lib/core/4.config/import-map/index.d.ts +2 -0
  29. package/types/lib/core/4.config/import-map/no-preload.d.ts +2 -0
  30. package/types/lib/core/4.config/import-map/preload-in-dom.d.ts +2 -0
  31. package/types/lib/core/5.di/federation-result.factory.d.ts +3 -2
  32. package/types/lib/core/init-federation.contract.d.ts +2 -0
  33. package/types/lib/index.d.ts +1 -1
  34. package/types/lib/node/init-federation.node.d.ts +2 -7
  35. package/types/lib/node.index.d.ts +1 -1
  36. package/types/lib/registry/event-registry.contract.d.ts +1 -0
  37. package/types/lib/registry/event.contract.d.ts +6 -0
  38. package/types/lib/registry/for-managing-events.port.d.ts +1 -0
  39. package/types/lib/registry/registry.contract.d.ts +2 -0
  40. package/types/lib/registry/setup-registry.d.ts +1 -0
  41. package/types/scripts/announce-init-ready.d.ts +2 -0
  42. package/types/scripts/init-registry.d.ts +1 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js", "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js", "../../src/lib/core/3.adapters/browser/browser.ts", "../../src/lib/core/3.adapters/checks/version.check.ts", "../../src/lib/core/native-federation.error.ts", "../../src/lib/utils/integrity.ts", "../../src/lib/node/utils/read-source.ts", "../../src/lib/node/adapters/fs-manifest-provider.ts", "../../src/lib/core/1.domain/remote-entry/mark-dense.ts", "../../node_modules/.pnpm/@softarc+native-federation@4.9.0/node_modules/@softarc/native-federation/dist/lib/domain/core/chunk.js", "../../node_modules/.pnpm/@softarc+native-federation@4.9.0/node_modules/@softarc/native-federation/dist/lib/utils/normalize.js", "../../node_modules/.pnpm/@softarc+native-federation@4.9.0/node_modules/@softarc/native-federation/dist/lib/core/output/densify-externals.js", "../../src/lib/core/3.adapters/remote-entry/normalize-remote-entry.ts", "../../src/lib/node/adapters/fs-remote-entry-provider.ts", "../../src/lib/node/adapters/noop-sse.ts", "../../src/lib/core/2.app/config/storage.contract.ts", "../../src/lib/utils/path.ts", "../../src/lib/utils/optional.ts", "../../src/lib/core/3.adapters/storage/remote-info.repository.ts", "../../src/lib/core/3.adapters/storage/scoped-externals.repository.ts", "../../src/lib/core/1.domain/externals/external.contract.ts", "../../src/lib/core/3.adapters/storage/cache-state.ts", "../../src/lib/core/3.adapters/storage/shared-externals.repository.ts", "../../src/lib/core/3.adapters/storage/chunk.repository.ts", "../../src/lib/core/4.config/import-map/trusted-types.ts", "../../src/lib/core/4.config/import-map/replace-in-dom.ts", "../../src/lib/core/4.config/import-map/use-default.ts", "../../src/lib/core/4.config/import-map/import-map.config.ts", "../../src/lib/core/4.config/host/host.config.ts", "../../src/lib/core/4.config/logging/noop.logger.ts", "../../src/lib/core/2.app/config/log.contract.ts", "../../src/lib/core/4.config/logging/log.handler.ts", "../../src/lib/core/4.config/logging/log.config.ts", "../../src/lib/utils/clone-entry.ts", "../../src/lib/core/4.config/storage/global-this.storage.ts", "../../src/lib/core/4.config/orchestrator-version.ts", "../../src/lib/core/4.config/storage/publish-storage-info.ts", "../../src/lib/core/4.config/storage/storage.config.ts", "../../src/lib/core/4.config/mode/default.profile.ts", "../../src/lib/core/4.config/mode/mode.config.ts", "../../src/lib/core/5.di/config.factory.ts", "../../src/lib/core/2.app/flows/init.flow.ts", "../../src/lib/core/2.app/flows/init-remote-entry.flow.ts", "../../src/lib/core/2.app/steps/store-remote-entry.ts", "../../src/lib/core/2.app/steps/get-remote-entries.ts", "../../src/lib/utils/compare-strings.ts", "../../src/lib/core/1.domain/externals/basis.ts", "../../src/lib/core/1.domain/externals/rows.ts", "../../src/lib/core/2.app/steps/process-remote-entries.ts", "../../src/lib/core/1.domain/externals/compatibility.ts", "../../src/lib/core/2.app/steps/apply-winner.ts", "../../src/lib/core/2.app/steps/determine-shared-externals.ts", "../../src/lib/utils/union-find.ts", "../../src/lib/core/1.domain/externals/specifier.ts", "../../src/lib/core/1.domain/pooling/builds.ts", "../../src/lib/core/1.domain/pooling/rules.ts", "../../src/lib/core/1.domain/pooling/election.ts", "../../src/lib/core/1.domain/pooling/membership.ts", "../../src/lib/core/1.domain/pooling/pool-state.ts", "../../src/lib/core/1.domain/pooling/records.ts", "../../src/lib/core/1.domain/pooling/plan.ts", "../../src/lib/core/2.app/steps/pooling/pool-shared-externals.ts", "../../src/lib/core/1.domain/externals/serving.ts", "../../src/lib/core/2.app/steps/decide-serving-builds.ts", "../../src/lib/core/1.domain/externals/claims.ts", "../../src/lib/core/2.app/steps/generate-import-map.ts", "../../src/lib/core/2.app/steps/commit-changes.ts", "../../src/lib/core/2.app/steps/rollback-changes.ts", "../../src/lib/core/2.app/steps/expose-module-loader.ts", "../../src/lib/core/2.app/steps/get-remote-entry.ts", "../../src/lib/core/2.app/steps/update-cache.ts", "../../src/lib/core/1.domain/pooling/gate.ts", "../../src/lib/core/2.app/steps/pooling/pool-dynamic-externals.ts", "../../src/lib/core/2.app/steps/convert-to-import-map.ts", "../../src/lib/core/5.di/init.factory.ts", "../../src/lib/core/5.di/federation-result.factory.ts", "../../src/lib/node/adapters/node-loader.client.ts", "../../src/lib/node/adapters/loader-url.ts", "../../src/lib/node/use-node.ts", "../../src/lib/node/resolve-host-instances.ts", "../../src/lib/node/utils/to-url.ts", "../../src/lib/node/init-federation.node.ts"],
4
- "sourcesContent": ["'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n const identifiers = identifier.split('.')\n if (identifiers.length > prerelease.length) {\n return false\n }\n\n for (let i = 0; i < identifiers.length; i++) {\n if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n return false\n }\n }\n\n return true\n}\n\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n const prereleaseBase = this.prerelease[identifier.split('.').length]\n if (isNaN(prereleaseBase)) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // strip build metadata so it can't bleed into the version\n range = range.replace(BUILDSTRIPRE, '')\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n src,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n (isX(M) && !isX(m)) ||\n (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n // if we're including prereleases in the match, then the lower bound is\n // -0, the lowest possible prerelease value, just like x-ranges and carets.\n // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n if (invalidXRangeOrder(M, m, p)) {\n return comp\n }\n\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "import type { ForBrowserTasks } from 'lib/core/2.app/driving-ports/for-browser-tasks';\nimport type { ImportMapConfig } from 'lib/core/2.app/config/import-map.contract';\n\nconst createBrowser = (config: ImportMapConfig): ForBrowserTasks => {\n return {\n setImportMapFn: config.setImportMapFn,\n importModule: config.loadModuleFn,\n };\n};\n\nexport { createBrowser };\n", "import type { ForVersionChecking } from 'lib/core/2.app/driving-ports/for-version-checking.port';\nimport semverValid from 'semver/functions/valid';\nimport semverSatisfies from 'semver/functions/satisfies';\nimport SemVer from 'semver/classes/semver';\nimport semverMinVersion from 'semver/ranges/min-version';\nimport semverValidRange from 'semver/ranges/valid';\n\nconst createVersionCheck = (): ForVersionChecking => {\n const parsed = new Map<string, SemVer>();\n const parse = (v: string) => {\n let hit = parsed.get(v);\n if (!hit) parsed.set(v, (hit = new SemVer(v, true)));\n return hit;\n };\n const satisfied = new Map<string, Map<string, boolean>>();\n return {\n isValidSemver: function (version: string) {\n return semverValid(version) !== null;\n },\n isCompatible: function (version: string, range: string) {\n let byVersion = satisfied.get(range);\n if (!byVersion) satisfied.set(range, (byVersion = new Map()));\n let hit = byVersion.get(version);\n if (hit === undefined) byVersion.set(version, (hit = semverSatisfies(version, range)));\n return hit;\n },\n compare: function (versionA: string, versionB: string) {\n return parse(versionA).compare(parse(versionB));\n },\n smallestVersion: function (versionRange: string) {\n if (!semverValidRange(versionRange)) return '0.0.0';\n const minVersion = semverMinVersion(versionRange);\n return minVersion?.raw ?? '0.0.0';\n },\n };\n};\n\nexport { createVersionCheck };\n", "class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause ? { cause } : undefined);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "const SUPPORTED_ALGORITHMS = {\n 'sha256-': 'SHA-256',\n 'sha384-': 'SHA-384',\n 'sha512-': 'SHA-512',\n} as const;\n\ntype Prefix = keyof typeof SUPPORTED_ALGORITHMS;\n\nconst parseIntegrity = (integrity: string): { algorithm: string; expected: string } | null => {\n for (const prefix of Object.keys(SUPPORTED_ALGORITHMS) as Prefix[]) {\n if (integrity.startsWith(prefix)) {\n return { algorithm: SUPPORTED_ALGORITHMS[prefix], expected: integrity };\n }\n }\n return null;\n};\n\nconst toBase64 = (bytes: ArrayBuffer): string => {\n const view = new Uint8Array(bytes);\n let bin = '';\n for (let i = 0; i < view.length; i++) bin += String.fromCharCode(view[i]!);\n return btoa(bin);\n};\n\nexport const verifyIntegrity = async (bytes: ArrayBuffer, integrity: string): Promise<void> => {\n const parsed = parseIntegrity(integrity);\n if (!parsed) {\n throw new TypeError(\n `Unsupported integrity prefix in '${integrity}'. Expected sha256-, sha384-, or sha512-.`\n );\n }\n\n const subtle =\n typeof crypto !== 'undefined' && crypto.subtle ? crypto.subtle : undefined;\n if (!subtle) {\n throw new Error('SubtleCrypto is not available in this environment.');\n }\n\n const digest = await subtle.digest(parsed.algorithm, bytes);\n const actual =\n integrity.substring(0, integrity.indexOf('-') + 1) + toBase64(digest);\n\n if (actual !== parsed.expected) {\n throw new Error(`Integrity mismatch: expected ${parsed.expected}, got ${actual}`);\n }\n};\n", "import * as fs from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { NFError } from 'lib/core/native-federation.error';\n\nconst isHttpUrl = (input: string): boolean =>\n input.startsWith('http://') || input.startsWith('https://');\n\nconst isFileUrl = (input: string): boolean => input.startsWith('file://');\n\nexport const readSourceBytes = async (input: string): Promise<ArrayBuffer> => {\n if (isHttpUrl(input)) {\n const response = await fetch(input);\n if (!response.ok) {\n throw new NFError(`${response.status} - ${response.statusText}`);\n }\n return response.arrayBuffer();\n }\n\n const path = isFileUrl(input) ? fileURLToPath(input) : input;\n const buffer = await fs.readFile(path);\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n};\n", "import type { FederationManifest } from 'lib/core/1.domain';\nimport type { ForProvidingManifest } from 'lib/core/2.app/driving-ports/for-providing-manifest.port';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { verifyIntegrity } from 'lib/utils/integrity';\nimport { readSourceBytes } from 'lib/node/utils/read-source';\n\nconst createFsManifestProvider = (): ForProvidingManifest => {\n const formatError = (manifestUrl: string) => (err: unknown) => {\n if (err instanceof NFError) throw err;\n const msg = err instanceof Error ? err.message : String(err);\n throw new NFError(`Read of '${manifestUrl}' returned ${msg}`);\n };\n\n return {\n provide: async function (\n remotesOrManifestUrl: string | FederationManifest,\n opts: { integrity?: string } = {}\n ) {\n if (typeof remotesOrManifestUrl !== 'string') return remotesOrManifestUrl;\n\n try {\n const bytes = await readSourceBytes(remotesOrManifestUrl);\n if (opts.integrity) await verifyIntegrity(bytes, opts.integrity);\n return JSON.parse(new TextDecoder().decode(bytes)) as FederationManifest;\n } catch (err) {\n return formatError(remotesOrManifestUrl)(err);\n }\n },\n };\n};\n\nexport { createFsManifestProvider };\n", "import type { DenseSharedInfo, RemoteSharedInfo, SharedInfo } from './remote-entry.contract';\n\n// Runs on the raw `shared` array: normalizing wraps a flat entry into the dense shape, after which the two\n// can't be told apart.\nexport function markDense(\n shared: (SharedInfo | DenseSharedInfo)[]\n): (SharedInfo | RemoteSharedInfo)[] {\n return shared.map(entry => ('entries' in entry ? { ...entry, dense: true } : entry));\n}\n", "const CHUNK_PREFIX = \"@nf-internal\";\nconst SCRIPT_EXTENSION = /\\.(m|c)?js$/;\nfunction toChunkImport(fileName) {\n if (fileName.startsWith(\"./\")) {\n fileName = fileName.slice(2);\n }\n const packageName = fileName.replace(SCRIPT_EXTENSION, \"\");\n return CHUNK_PREFIX + \"/\" + packageName;\n}\nexport {\n CHUNK_PREFIX,\n SCRIPT_EXTENSION,\n toChunkImport\n};\n", "import { toPosix } from \"./path-patterns.js\";\nfunction normalize(path, trailingSlash) {\n let cand = toPosix(path);\n if (typeof trailingSlash === \"undefined\") {\n return cand;\n }\n while (cand.endsWith(\"/\")) {\n cand = cand.substring(0, cand.length - 1);\n }\n if (trailingSlash) {\n return cand + \"/\";\n }\n return cand;\n}\nfunction normalizePackageName(fileName) {\n const sanitized = fileName.replace(/[^A-Za-z0-9]/g, \"_\");\n return sanitized.startsWith(\"_\") ? sanitized.slice(1) : sanitized;\n}\nfunction inferPackageFromSecondary(secondary) {\n const parts = secondary.split(\"/\");\n if (secondary.startsWith(\"@\") && parts.length >= 2) {\n return parts[0] + \"/\" + parts[1];\n }\n return parts[0];\n}\nfunction sharedBundlePackage(key, build) {\n return build === \"separate\" ? key : inferPackageFromSecondary(key);\n}\nfunction sharedBundleName(platform, packageName) {\n return `${platform}-${normalizePackageName(packageName)}`;\n}\nexport {\n inferPackageFromSecondary,\n normalize,\n normalizePackageName,\n sharedBundleName,\n sharedBundlePackage\n};\n", "import { CHUNK_PREFIX } from \"../../domain/core/chunk.js\";\nimport { inferPackageFromSecondary } from \"../../utils/normalize.js\";\nfunction isDense(entry) {\n return \"entries\" in entry;\n}\nfunction isFlatChunk(entry) {\n return entry.packageName.startsWith(CHUNK_PREFIX);\n}\nfunction densifyExternals(shared, declaredPackages) {\n const result = [];\n const groupIndex = /* @__PURE__ */ new Map();\n for (const entry of shared) {\n if (isDense(entry)) {\n result.push(entry);\n continue;\n }\n if (isFlatChunk(entry)) {\n const { outFileName: outFileName2, ...rest } = entry;\n result.push({ ...rest, entries: { [entry.packageName]: outFileName2 } });\n continue;\n }\n const { outFileName, packageName, dev, ...meta } = entry;\n const parent = declaredPackages.get(packageName) ?? inferPackageFromSecondary(packageName);\n const sig = JSON.stringify(meta, Object.keys(meta).sort());\n const key = parent + \" \" + sig;\n const existing = groupIndex.get(key);\n if (existing === void 0) {\n const dense = {\n ...meta,\n packageName: parent,\n entries: { [packageName]: outFileName }\n };\n if (dev !== void 0) dense.dev = dev;\n groupIndex.set(key, result.length);\n result.push(dense);\n } else {\n result[existing].entries[packageName] = outFileName;\n }\n }\n return result;\n}\nfunction toDenseSharedInfoFormat(shared) {\n return shared.map((external) => {\n if (\"entries\" in external) return external;\n const { outFileName, ...baseSharedInfoProps } = external;\n return {\n ...baseSharedInfoProps,\n entries: { [external.packageName]: outFileName }\n };\n });\n}\nexport {\n densifyExternals,\n toDenseSharedInfoFormat\n};\n", "import type {\n RawRemoteEntry,\n RemoteEntry,\n} from 'lib/core/1.domain/remote-entry/remote-entry.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { markDense } from 'lib/core/1.domain/remote-entry/mark-dense';\nimport {\n densifyExternals,\n toDenseSharedInfoFormat,\n} from '@softarc/native-federation/internal/browser';\n\nconst normalizeRemoteEntry = (\n raw: RawRemoteEntry,\n remoteEntryUrl: string,\n config: ModeConfig\n): RemoteEntry => {\n const marked = markDense(raw.shared ?? []);\n // Flat entries carry no package declaration, so densifying groups them by npm name.\n const shared = config.feature.convertFlatSharedInfo\n ? densifyExternals(marked, new Map())\n : toDenseSharedInfoFormat(marked);\n const remoteEntry = { ...raw, shared } as RemoteEntry;\n if (!remoteEntry.exposes) remoteEntry.exposes = [];\n if (!remoteEntry.url) remoteEntry.url = remoteEntryUrl;\n return remoteEntry;\n};\n\nexport { normalizeRemoteEntry };\n", "import type { RawRemoteEntry } from 'lib/core/1.domain/remote-entry/remote-entry.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { normalizeRemoteEntry } from 'lib/core/3.adapters/remote-entry/normalize-remote-entry';\nimport type { ForProvidingRemoteEntries } from 'lib/core/2.app/driving-ports/for-providing-remote-entries.port';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { verifyIntegrity } from 'lib/utils/integrity';\nimport { readSourceBytes } from 'lib/node/utils/read-source';\n\nconst createFsRemoteEntryProvider = (config: ModeConfig): ForProvidingRemoteEntries => {\n const formatError = (remoteEntryUrl: string) => (err: unknown) => {\n if (err instanceof NFError) throw err;\n const msg = err instanceof Error ? err.message : String(err);\n throw new NFError(`Read of '${remoteEntryUrl}' returned ${msg}`);\n };\n\n return {\n provide: async function (remoteEntryUrl: string, opts: { integrity?: string } = {}) {\n try {\n const bytes = await readSourceBytes(remoteEntryUrl);\n if (opts.integrity) await verifyIntegrity(bytes, opts.integrity);\n const raw = JSON.parse(new TextDecoder().decode(bytes)) as RawRemoteEntry;\n return normalizeRemoteEntry(raw, remoteEntryUrl, config);\n } catch (err) {\n return formatError(remoteEntryUrl)(err);\n }\n },\n };\n};\n\nexport { createFsRemoteEntryProvider };\n", "import type { ForSSE } from 'lib/core/2.app/driving-ports/for-sse.port';\n\nconst createNoopSSE = (): ForSSE => ({\n watchRemoteBuilds: () => {\n /* no-op */\n },\n closeAll: () => {\n /* no-op */\n },\n});\n\nexport { createNoopSSE };\n", "// `set` stores a copy and `get` returns a fresh one: a repository's uncommitted edits must never reach storage.\ntype StorageEntry<TValue> = {\n set: (value: TValue) => StorageEntry<TValue>;\n get: () => TValue | undefined;\n clear: () => StorageEntry<TValue>;\n};\n\ntype StorageEntryKey = number | symbol | string;\n\ntype StorageType = 'globalThis' | 'localStorage' | 'sessionStorage' | 'custom';\n\n// `type` is only read to describe the storage on globalThis.__NF_ORCHESTRATOR__; untagged creators report 'custom'.\ntype StorageEntryCreator = {\n (namespace: string): StorageEntryHandler;\n type?: StorageType;\n};\n\nconst STORAGE_KEYS = {\n remotes: 'remotes',\n sharedExternals: 'shared-externals',\n scopedExternals: 'scoped-externals',\n sharedChunks: 'shared-chunks',\n cacheState: 'cache-state',\n} as const;\n\ntype StorageKey = (typeof STORAGE_KEYS)[keyof typeof STORAGE_KEYS];\n\n// The orchestrator version that wrote the cache, beside the records: a cache stamped with any other is dropped.\n// `undecidedScopes` are the share scopes a runtime load wrote since their serving builds were last decided.\ntype CacheState = { version: string; undecidedScopes: string[] };\n\ntype StorageEntryHandler = <TValue>(key: string, initialValue: TValue) => StorageEntry<TValue>;\n\ntype StorageConfig = {\n storage: StorageEntryHandler;\n clearStorage: boolean;\n};\n\ntype StorageOptions = {\n storage?: StorageEntryCreator;\n clearStorage?: boolean;\n storageNamespace?: string;\n exposeStorageGetter?: boolean;\n};\n\nexport {\n StorageEntry,\n StorageEntryKey,\n StorageEntryHandler,\n StorageConfig,\n StorageOptions,\n StorageEntryCreator,\n StorageType,\n StorageKey,\n STORAGE_KEYS,\n CacheState,\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", "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", "import type { RemoteInfo, RemoteName, Remotes } from 'lib/core/1.domain';\nimport {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForRemoteInfoStorage } from 'lib/core/2.app/driving-ports/for-remote-info-storage.port';\nimport * as _path from 'lib/utils/path';\nimport { Optional } from 'lib/utils/optional';\n\nconst createRemoteInfoRepository = (config: StorageConfig): ForRemoteInfoStorage => {\n const STORAGE: StorageEntry<Remotes> = config.storage(STORAGE_KEYS.remotes, {});\n if (config.clearStorage) STORAGE.clear();\n\n let _cache: Remotes = STORAGE.get() ?? {};\n\n let _dirty = false;\n\n return {\n contains: function (remoteName: RemoteName) {\n return !!_cache[remoteName];\n },\n remove: function (remoteName: RemoteName) {\n if (remoteName in _cache) {\n delete _cache[remoteName];\n _dirty = true;\n }\n return this;\n },\n addOrUpdate: function (remoteName: string, remote: RemoteInfo) {\n _cache[remoteName] = remote;\n _dirty = true;\n return this;\n },\n tryGet: function (remoteName: RemoteName) {\n return Optional.of(_cache[remoteName]);\n },\n tryGetModule: function (remoteName: RemoteName, exposedModule: string) {\n return Optional.of(_cache[remoteName]?.exposes.find(m => m.moduleName === exposedModule)).map(\n m => _path.join(_cache[remoteName]!.scopeUrl, m.file)\n );\n },\n getAll: function () {\n return _cache;\n },\n commit: function () {\n if (!_dirty) return this;\n STORAGE.set(_cache);\n _dirty = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? {};\n _dirty = false;\n return this;\n },\n };\n};\n\nexport { createRemoteInfoRepository };\n", "import type { ScopedExternals } from 'lib/core/1.domain/externals/external.contract';\nimport {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForScopedExternalsStorage } from 'lib/core/2.app/driving-ports/for-scoped-externals-storage.port';\nimport type { RemoteName, ScopedVersion } from 'lib/core/1.domain';\nimport { Optional } from 'lib/utils/optional';\n\nconst createScopedExternalsRepository = (config: StorageConfig): ForScopedExternalsStorage => {\n const STORAGE: StorageEntry<ScopedExternals> = config.storage(STORAGE_KEYS.scopedExternals, {});\n\n if (config.clearStorage) STORAGE.clear();\n\n let _cache: ScopedExternals = STORAGE.get() ?? {};\n\n let _dirty = false;\n\n return {\n addExternal: function (remoteName: RemoteName, external: string, version: ScopedVersion) {\n if (!_cache[remoteName]) _cache[remoteName] = {};\n _cache[remoteName][external] = version;\n _dirty = true;\n return this;\n },\n remove: function (remoteName: RemoteName) {\n if (remoteName in _cache) {\n delete _cache[remoteName];\n _dirty = true;\n }\n return this;\n },\n getAll: function () {\n return _cache;\n },\n tryGet: function (remoteName: string) {\n return Optional.of(_cache[remoteName]);\n },\n commit: function () {\n if (!_dirty) return this;\n STORAGE.set(_cache);\n _dirty = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? {};\n _dirty = false;\n return this;\n },\n };\n};\n\nexport { createScopedExternalsRepository };\n", "import type { RemoteName } from '../remote/remote-info.contract';\nimport 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 // The pool this external resolves in, as pooling last computed it; absent when it is in none.\n poolName?: string;\n // The build its pool's last election made global; a tied re-election keeps it.\n poolWinner?: RemoteName;\n // The build every specifier of this external's package is served from in this scope; the same on each of them.\n // A remote, not a tag: a host serves every tag it ships.\n servingBuild?: RemoteName;\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", "import {\n STORAGE_KEYS,\n type CacheState,\n type StorageEntryHandler,\n} from 'lib/core/2.app/config/storage.contract';\n\n// `cache-state` has two writers, the storage config (`version`) and the shared-externals repository\n// (`undecidedScopes`). Each write re-reads the stored object, so neither ever drops the other's field.\nexport const createCacheState = (storage: StorageEntryHandler) => {\n const entry = storage<unknown>(STORAGE_KEYS.cacheState, null);\n\n const read = (): Partial<CacheState> => {\n const stored = entry.get();\n if (typeof stored !== 'object' || stored === null) return {};\n const { version, undecidedScopes } = stored as Record<string, unknown>;\n return {\n ...(typeof version === 'string' ? { version } : {}),\n ...(Array.isArray(undecidedScopes)\n ? { undecidedScopes: undecidedScopes.filter(s => typeof s === 'string') }\n : {}),\n };\n };\n\n return {\n read,\n update: (fields: Partial<CacheState>): void => void entry.set({ ...read(), ...fields }),\n };\n};\n", "import {\n type SharedExternal,\n type SharedExternals,\n GLOBAL_SCOPE,\n STRICT_SCOPE,\n} from 'lib/core/1.domain/externals/external.contract';\nimport {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForSharedExternalsStorage } from 'lib/core/2.app/driving-ports/for-shared-externals-storage.port';\nimport { createCacheState } from './cache-state';\nimport { Optional } from 'lib/utils/optional';\n\nconst createSharedExternalsRepository = (config: StorageConfig): ForSharedExternalsStorage => {\n const STORAGE: StorageEntry<SharedExternals> = config.storage<SharedExternals>(\n STORAGE_KEYS.sharedExternals,\n { [GLOBAL_SCOPE]: {} }\n );\n\n const cacheState = createCacheState(config.storage);\n const storedUndecided = () => new Set(cacheState.read().undecidedScopes);\n\n if (config.clearStorage) {\n STORAGE.clear();\n cacheState.update({ undecidedScopes: [] });\n }\n\n let _cache: SharedExternals = STORAGE.get() ?? { [GLOBAL_SCOPE]: {} };\n\n const _uncommitted = new Set<string>();\n\n let _undecided = storedUndecided();\n let _undecidedChanged = false;\n\n return {\n getFromScope: function (shareScope?: string) {\n return { ..._cache[shareScope ?? GLOBAL_SCOPE] };\n },\n addOrUpdate: function (externalName: string, external: SharedExternal, shareScope?: string) {\n if (!_cache[shareScope ?? GLOBAL_SCOPE]) _cache[shareScope ?? GLOBAL_SCOPE] = {};\n _cache[shareScope ?? GLOBAL_SCOPE]![externalName] = external;\n _uncommitted.add(shareScope ?? GLOBAL_SCOPE);\n return this;\n },\n getScopes: function (o = { includeGlobal: true }) {\n if (o.includeGlobal) return Object.keys(_cache);\n return Object.keys(_cache).filter(s => s !== GLOBAL_SCOPE);\n },\n // Batched: one traversal of the graph per init instead of one per overridden remote.\n removeFromAllScopes: function (remoteNames: ReadonlySet<string>) {\n if (remoteNames.size === 0) return;\n\n Object.entries(_cache).forEach(([scopeName, scope]) => {\n const removeExternals: string[] = [];\n\n Object.entries(scope).forEach(([name, external]) => {\n let removedCopy = false;\n\n for (let i = external.versions.length - 1; i >= 0; i--) {\n const version = external.versions[i]!;\n const remotes = version.remotes;\n // The host is `remotes[0]` of a flagged version, and the filter below is about to move it.\n const host = version.host ? remotes[0]?.name : undefined;\n\n let keep = 0;\n for (let r = 0; r < remotes.length; r++) {\n if (remoteNames.has(remotes[r]!.name)) continue;\n remotes[keep++] = remotes[r]!;\n }\n if (keep !== remotes.length) {\n remotes.length = keep;\n removedCopy = true;\n _uncommitted.add(scopeName);\n // Or `determine` keeps granting host precedence to a tag the host has left.\n if (host !== undefined && remoteNames.has(host)) version.host = false;\n }\n\n if (remotes.length === 0) {\n external.versions.splice(i, 1);\n _uncommitted.add(scopeName);\n }\n }\n\n // Any lost copy re-elects the external, not only one that emptied a version: the copy may have\n // been the version's basis, or the build a surviving copy's `servedBy` names. A replacement entry\n // that no longer declares this external never marks it dirty itself, so the record would keep\n // pointing at a build that does not serve it any more.\n if (removedCopy) {\n external.dirty = true;\n if (external.versions.length === 0) removeExternals.push(name);\n }\n });\n\n const lostPools = new Set<string>();\n for (const name of removeExternals) {\n const poolName = scope[name]!.poolName;\n if (poolName !== undefined) lostPools.add(poolName);\n delete scope[name];\n }\n // Nothing dirty is left behind, so mark its pool's siblings dirty or the next init skips the scope.\n if (lostPools.size > 0)\n for (const external of Object.values(scope))\n if (external.poolName !== undefined && lostPools.has(external.poolName))\n external.dirty = true;\n });\n },\n scopeType: function (shareScope?: string) {\n switch (shareScope) {\n case GLOBAL_SCOPE:\n case null:\n case undefined:\n return 'global';\n case STRICT_SCOPE:\n return 'strict';\n default:\n return 'shareScope';\n }\n },\n tryGet: function (external: string, shareScope?: string) {\n return Optional.of(_cache[shareScope ?? GLOBAL_SCOPE]?.[external]);\n },\n uncommittedScopes: function () {\n return [..._uncommitted];\n },\n markUndecided: function (shareScope: string) {\n if (_undecided.has(shareScope)) return;\n _undecided.add(shareScope);\n _undecidedChanged = true;\n },\n isUndecided: function (shareScope: string) {\n return _undecided.has(shareScope);\n },\n markDecided: function (shareScope: string) {\n if (_undecided.delete(shareScope)) _undecidedChanged = true;\n },\n // Records before marks: should their write throw, the stored marks still send the next init to decide them. A\n // failed cache-state write after the records loses only this load's marks.\n commit: function () {\n if (_uncommitted.size > 0) {\n STORAGE.set(_cache);\n _uncommitted.clear();\n }\n if (_undecidedChanged) cacheState.update({ undecidedScopes: [..._undecided] });\n _undecidedChanged = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? { [GLOBAL_SCOPE]: {} };\n _uncommitted.clear();\n _undecided = storedUndecided();\n _undecidedChanged = false;\n return this;\n },\n };\n};\n\nexport { createSharedExternalsRepository };\n", "import {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForSharedChunksStorage } from 'lib/core/2.app/driving-ports/for-shared-chunks-storage.port';\nimport type { SharedChunks } from 'lib/core/1.domain/externals/chunks.contract';\nimport { Optional } from 'lib/utils/optional';\n\nconst createChunkRepository = (config: StorageConfig): ForSharedChunksStorage => {\n const STORAGE: StorageEntry<SharedChunks> = config.storage(STORAGE_KEYS.sharedChunks, {});\n\n if (config.clearStorage) STORAGE.clear();\n\n let _cache: SharedChunks = STORAGE.get() ?? {};\n\n let _dirty = false;\n\n return {\n addOrReplace: function (remoteName: string, bundleName: string, chunks: string[]) {\n if (!_cache[remoteName]) _cache[remoteName] = {};\n _cache[remoteName][bundleName] = chunks;\n _dirty = true;\n return this;\n },\n // Whole-remote: a build that stops chunking a bundle omits the key, so `addOrReplace` cannot clear it.\n remove: function (remoteName: string) {\n if (remoteName in _cache) {\n delete _cache[remoteName];\n _dirty = true;\n }\n return this;\n },\n tryGet: function (remoteName: string, bundleName: string) {\n return Optional.of(_cache[remoteName]?.[bundleName]);\n },\n commit: function () {\n if (!_dirty) return this;\n STORAGE.set(_cache);\n _dirty = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? {};\n _dirty = false;\n return this;\n },\n };\n};\n\nexport { createChunkRepository };\n", "type TTCreateScript = (input: string) => string;\ntype TTCreateScriptURL = (input: string) => string;\n\ntype TTPolicyRules = {\n createScript?: TTCreateScript;\n createScriptURL?: TTCreateScriptURL;\n};\n\ntype TrustedValue = { toString(): string };\n\ntype TTPolicy = {\n createScript: (input: string) => TrustedValue;\n createScriptURL: (input: string) => TrustedValue;\n};\n\ntype TTFactory = {\n createPolicy: (name: string, rules: TTPolicyRules) => TTPolicy;\n};\n\nexport type NFTrustedTypesPolicy = {\n // `script.text` is a TrustedScript sink, so this must stay the genuine object.\n createScript: (input: string) => TrustedValue;\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),\n createScriptURL: input => String(native.createScriptURL(input)),\n };\n return cachedPolicy;\n};\n\nexport const __resetTrustedTypesPolicyForTests = (): void => {\n cachedPolicy = null;\n};\n", "import type { ImportMap } from 'lib/core/1.domain';\nimport type { SetImportMap } from 'lib/core/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/core/2.app/config/import-map.contract';\nimport { replaceInDOM } from './replace-in-dom';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\nconst useDefaultImportMap = (trustedTypesPolicyName: string | false = 'nfo'): 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 {\n ImportMapConfig,\n ImportMapOptions,\n} from 'lib/core/2.app/config/import-map.contract';\nimport { useDefaultImportMap } from './use-default';\n\nexport const createImportMapConfig = (o: Partial<ImportMapOptions>): ImportMapConfig => {\n const fallback = useDefaultImportMap(o.trustedTypesPolicyName);\n return {\n setImportMapFn: o.setImportMapFn ?? fallback.setImportMapFn,\n loadModuleFn: o.loadModuleFn ?? fallback.loadModuleFn,\n reloadBrowserFn: o.reloadBrowserFn ?? fallback.reloadBrowserFn,\n };\n};\n", "import type { HostConfig, HostOptions } from 'lib/core/2.app/config/host.contract';\n\nexport const createHostConfig = (override: Partial<HostOptions>): HostConfig => {\n const extras = override?.manifestIntegrity\n ? { manifestIntegrity: override.manifestIntegrity }\n : {};\n\n if (!override?.hostRemoteEntry) {\n return { hostRemoteEntry: false, ...extras };\n }\n if (typeof override.hostRemoteEntry === 'string') {\n return {\n hostRemoteEntry: {\n name: '__NF-HOST__',\n url: override.hostRemoteEntry,\n },\n ...extras,\n };\n }\n return {\n hostRemoteEntry: {\n name: '__NF-HOST__',\n ...override.hostRemoteEntry,\n },\n ...extras,\n };\n};\n", "import type { Logger } from 'lib/core/2.app/config/log.contract';\n\nconst noopLogger: Logger = {\n debug: () => {},\n error: () => {},\n warn: () => {},\n};\n\nexport { noopLogger };\n", "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 {\n type LogType,\n type LogHandler,\n type Logger,\n LogLevel,\n} from 'lib/core/2.app/config/log.contract';\n\nconst createLogHandler = (logger: Logger, logLevel: LogType): LogHandler => {\n const logTypes = Object.keys(LogLevel).filter(key => isNaN(Number(key))) as LogType[];\n\n return logTypes.reduce(\n (acc, logMessageType) => {\n return {\n ...acc,\n [logMessageType]: (step: number, message: string, details: unknown) => {\n if (LogLevel[logMessageType] >= LogLevel[logLevel]) {\n logger[logMessageType](step, message, details);\n }\n },\n };\n },\n { level: logLevel } as LogHandler\n );\n};\n\nexport { createLogHandler };\n", "import type { LoggingConfig, LoggingOptions } from 'lib/core/2.app/config/log.contract';\nimport { noopLogger } from './noop.logger';\nimport { createLogHandler } from './log.handler';\n\nexport const createLogConfig = ({ logger, logLevel, sse }: LoggingOptions): LoggingConfig => ({\n log: createLogHandler(logger ?? noopLogger, logLevel ?? 'error'),\n sse: !!sse,\n});\n", "import type { StorageEntryKey } from 'lib/core/2.app/config/storage.contract';\nimport { NFError } from 'lib/core/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 'lib/utils/clone-entry';\nimport {\n type StorageEntryCreator,\n type StorageEntry,\n} from 'lib/core/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\n const entry: StorageEntry<TValue> = {\n get(): TValue {\n return cloneEntry(key, key in storage ? storage[key] : initialValue)!;\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\nglobalThisStorageEntry.type = 'globalThis';\nObject.freeze(globalThisStorageEntry);\n\nexport { globalThisStorageEntry };\n", "// Injected by build.js; bundles built without that define (e.g. the e2e harness) report 'dev'.\ndeclare const __NF_ORCHESTRATOR_VERSION__: string | undefined;\n\nexport const ORCHESTRATOR_VERSION =\n typeof __NF_ORCHESTRATOR_VERSION__ === 'string' ? __NF_ORCHESTRATOR_VERSION__ : 'dev';\n", "import type {\n NFOrchestratorGlobal,\n NFOrchestratorStorageInfo,\n} from 'lib/core/2.app/config/orchestrator-global.contract';\nimport {\n STORAGE_KEYS,\n type StorageEntryHandler,\n type StorageKey,\n type StorageType,\n} from 'lib/core/2.app/config/storage.contract';\nimport { cloneEntry } from 'lib/utils/clone-entry';\nimport { ORCHESTRATOR_VERSION } from 'lib/core/4.config/orchestrator-version';\n\nconst KEYS: readonly StorageKey[] = Object.freeze(Object.values(STORAGE_KEYS));\n\nconst isStorageKey = (key: string): key is StorageKey => (KEYS as readonly string[]).includes(key);\n\ntype StorageInfoOptions = {\n type: StorageType;\n namespace: string;\n storage: StorageEntryHandler;\n exposeGetter: boolean;\n};\n\nconst createStorageInfo = ({\n type,\n namespace,\n storage,\n exposeGetter,\n}: StorageInfoOptions): NFOrchestratorStorageInfo => {\n const info: NFOrchestratorStorageInfo = {\n version: ORCHESTRATOR_VERSION,\n type,\n namespace,\n keys: KEYS,\n };\n if (!exposeGetter) return Object.freeze(info);\n\n return Object.freeze({\n ...info,\n // Cloned again because custom storages may hand out live references.\n get: (key: string) =>\n isStorageKey(key) ? cloneEntry(key, storage(key, undefined).get()) : undefined,\n });\n};\n\n// Replaced (not mutated) so earlier namespaces survive while the published object stays frozen.\n// Diagnostic only: a locked-down or foreign global must never break init, so failures are swallowed.\nexport const publishStorageInfo = (options: StorageInfoOptions): void => {\n try {\n globalThis.__NF_ORCHESTRATOR__ = Object.freeze<NFOrchestratorGlobal>({\n storage: Object.freeze({\n ...globalThis.__NF_ORCHESTRATOR__?.storage,\n [options.namespace]: createStorageInfo(options),\n }),\n });\n } catch {\n /* the global is not writable */\n }\n};\n", "import {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n type StorageEntryHandler,\n type StorageOptions,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { LogHandler } from 'lib/core/2.app/config/log.contract';\nimport { cloneEntry } from 'lib/utils/clone-entry';\nimport { globalThisStorageEntry } from './global-this.storage';\nimport { publishStorageInfo } from './publish-storage-info';\nimport { ORCHESTRATOR_VERSION } from 'lib/core/4.config/orchestrator-version';\nimport { createCacheState } from 'lib/core/3.adapters/storage/cache-state';\n\n// Every entry goes, not only the outdated one: a warm init skips fetching any remote it still has\n// cached, so a dropped externals entry would never be refilled.\nconst isOutdatedCache = (storage: StorageEntryHandler): boolean => {\n const cacheState = createCacheState(storage);\n if (cacheState.read().version === ORCHESTRATOR_VERSION) return false;\n cacheState.update({ version: ORCHESTRATOR_VERSION, undecidedScopes: [] });\n return Object.values(STORAGE_KEYS)\n .filter(key => key !== STORAGE_KEYS.cacheState)\n .some(key => storage(key, null).get() !== null);\n};\n\n// After one failed write the page stops persisting and keeps every later write in memory: a cache-state update\n// would otherwise re-stamp the version, and a rollback would re-read the half-written records.\nconst guardWrites = (storage: StorageEntryHandler, log: LogHandler): StorageEntryHandler => {\n let failed = false;\n const memory = new Map<string, unknown>();\n\n const write = (key: string, value: unknown, persist: () => void): void => {\n if (!failed) {\n try {\n persist();\n return;\n } catch (error) {\n failed = true;\n try {\n // Replaces the stamp with the smallest value, so the next page clears the cache.\n storage(STORAGE_KEYS.cacheState, null).set(null);\n } catch {\n /* the next page may inherit the broken cache */\n }\n log.warn(\n 5,\n `Could not save '${key}' to storage; this page runs from memory and the next page starts without a cache.`,\n error\n );\n }\n }\n memory.set(key, cloneEntry(key, value));\n };\n\n return <TValue>(key: string, initialValue: TValue) => {\n const inner = storage(key, initialValue);\n const entry: StorageEntry<TValue> = {\n get: () => (memory.has(key) ? cloneEntry(key, memory.get(key) as TValue) : inner.get()),\n set: value => {\n write(key, value, () => void inner.set(value));\n return entry;\n },\n clear: () => {\n write(key, initialValue, () => void inner.clear());\n return entry;\n },\n };\n return entry;\n };\n};\n\nexport const createStorageConfig = (override: StorageOptions, log: LogHandler): StorageConfig => {\n const creator = override.storage ?? globalThisStorageEntry;\n const namespace = override.storageNamespace ?? '__NATIVE_FEDERATION__';\n const storage = guardWrites(creator(namespace), log);\n publishStorageInfo({\n type: creator.type ?? 'custom',\n namespace,\n storage,\n exposeGetter: override.exposeStorageGetter ?? true,\n });\n const outdated = isOutdatedCache(storage);\n\n return {\n storage,\n clearStorage: (override.clearStorage ?? false) || outdated,\n };\n};\n", "import type { ModeProfileConfig } from 'lib/core/2.app/config/mode.contract';\n\nexport const defaultProfile: ModeProfileConfig = {\n latestSharedExternal: false,\n skipInvalidExternalVersions: false,\n overrideCachedRemotes: 'init-only',\n overrideCachedRemotesIfURLMatches: false,\n mergeManifests: true,\n};\n", "import type { ModeConfig, ModeOptions } from 'lib/core/2.app/config/mode.contract';\nimport { defaultProfile } from './default.profile';\n\nexport const createModeConfig = (override: ModeOptions): ModeConfig => {\n const strictnessConfig =\n typeof override.strict === 'boolean'\n ? {\n strictRemoteEntry: override.strict,\n strictExternalCompatibility: override.strict,\n strictExternalSameVersionCompatibility: override.strict,\n strictExternalVersion: override.strict,\n strictImportMap: override.strict,\n }\n : {\n strictRemoteEntry: override.strict?.strictRemoteEntry ?? false,\n strictExternalCompatibility: override.strict?.strictExternalCompatibility ?? false,\n strictExternalSameVersionCompatibility:\n override.strict?.strictExternalSameVersionCompatibility ?? false,\n strictExternalVersion: override.strict?.strictExternalVersion ?? false,\n strictImportMap: override.strict?.strictImportMap ?? false,\n };\n\n return {\n strict: strictnessConfig,\n profile: { ...defaultProfile, ...(override.profile ?? {}) },\n feature: {\n convertFlatSharedInfo: override.feature?.convertFlatSharedInfo ?? false,\n },\n };\n};\n", "import type { ConfigContract, NFOptions } from 'lib/core/2.app/config/config.contract';\nimport { createImportMapConfig } from 'lib/core/4.config/import-map/import-map.config';\nimport { createHostConfig } from 'lib/core/4.config/host/host.config';\nimport { createLogConfig } from 'lib/core/4.config/logging/log.config';\nimport { createStorageConfig } from 'lib/core/4.config/storage/storage.config';\nimport { createModeConfig } from 'lib/core/4.config/mode/mode.config';\n\nexport const createConfigHandlers = (overrides: NFOptions): ConfigContract => {\n const logConfig = createLogConfig(overrides);\n return {\n ...createImportMapConfig(overrides),\n ...createHostConfig(overrides),\n ...logConfig,\n ...createStorageConfig(overrides, logConfig.log),\n ...createModeConfig(overrides),\n };\n};\n", "import type { FLOW_FACTORY } from '../driver-ports/flow-factory.contract';\nimport type { InitDriversContract } from '../driver-ports/init/drivers.contract';\nimport type { InitFlow } from '../driver-ports/init/flow.contract';\n\nexport const createInitFlow = ({\n flow,\n adapters,\n config,\n}: FLOW_FACTORY<InitDriversContract>): InitFlow => {\n return remotesOrManifestUrl =>\n flow\n .getRemoteEntries(remotesOrManifestUrl)\n .then(flow.processRemoteEntries)\n .then(flow.poolSharedExternals)\n .then(flow.determineSharedExternals)\n .then(flow.decideServingBuilds)\n .then(flow.generateImportMap)\n .then(importMap => flow.commitChanges(importMap, { override: true }))\n .then(flow.exposeModuleLoader)\n .then(loadRemoteModule => ({\n config,\n adapters,\n loadRemoteModule,\n }));\n};\n", "import type { RemoteEntry } from 'lib/core/1.domain';\nimport type { FLOW_FACTORY } from '../driver-ports/flow-factory.contract';\nimport type { InitDriversContract } from '../driver-ports/init/drivers.contract';\nimport type { InitRemoteEntryFlow } from '../driver-ports/init/flow.contract';\n\nexport const createInitRemoteEntryFlow = ({\n flow,\n}: FLOW_FACTORY<InitDriversContract>): InitRemoteEntryFlow => {\n const processDynamicRemoteEntry = (remoteEntry: RemoteEntry) =>\n flow\n .updateCache(remoteEntry)\n .then(flow.poolDynamicExternals)\n .then(flow.convertToImportMap)\n .then(importMap => flow.commitChanges(importMap, { markUndecided: true }));\n\n return (remoteEntryUrl, remote) =>\n flow\n .getRemoteEntry(remoteEntryUrl, remote)\n .then(entry => entry.map(processDynamicRemoteEntry).orElse(Promise.resolve()))\n .then(() => undefined)\n .catch((error: unknown) => {\n const remoteName = typeof remote === 'string' ? remote : remote?.name;\n return flow\n .rollbackChanges(`[dynamic-init][${remoteName ?? remoteEntryUrl}]`)\n .then(() => Promise.reject(error));\n });\n};\n", "import {\n type RemoteEntry,\n type RemoteInfo,\n type RemoteName,\n type ScopedVersion,\n type SharedExternal,\n type DenseSharedInfo,\n type RemoteSharedInfo,\n type SharedVersion,\n type SharedVersionMeta,\n} from 'lib/core/1.domain';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport * as _path from 'lib/utils/path';\n\nexport type StoreRemoteEntry = (\n remoteEntry: RemoteEntry,\n onSharedExternal: SharedExternalHandler\n) => void;\n\nexport type RemoveCachedRemoteEntries = (remoteNames: ReadonlySet<RemoteName>) => void;\n\n/**\n * Evict stored remotes: overridden ones before their replacements are merged in, and ones the manifest\n * doesn't list. Kept out of `storeRemoteEntry` because `removeFromAllScopes` costs a full traversal of the\n * shared-externals graph, so each caller evicts its whole set at once.\n */\nexport function createRemoveCachedRemoteEntries(\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedExternalsRepo' | 'sharedChunksRepo'\n >\n): RemoveCachedRemoteEntries {\n return remoteNames => {\n if (remoteNames.size === 0) return;\n\n for (const remoteName of remoteNames) {\n ports.remoteInfoRepo.remove(remoteName);\n ports.scopedExternalsRepo.remove(remoteName);\n ports.sharedChunksRepo.remove(remoteName);\n }\n ports.sharedExternalsRepo.removeFromAllScopes(remoteNames);\n };\n}\n\nexport type SharedExternalHandler = (\n remoteEntry: RemoteEntry,\n external: DenseSharedInfo,\n ctx: SharedExternalContext\n) => void;\n\nexport type SharedExternalContext = {\n tag: string;\n remote: SharedVersionMeta;\n readRecord: () => SharedExternal;\n scopeType: 'global' | 'strict' | 'shareScope';\n assertSameVersionCompatibility: (matchingVersion: SharedVersion) => void;\n write: () => void;\n};\n\n/**\n * Not a pipeline step but the template both storage steps specialize: it owns the merge sequence\n * for a remoteEntry, and only the resolution of a singleton external differs between the init\n * pipeline (process-remote-entries, step 2) and the dynamic pipeline (update-cache, step 8),\n * injected per call. Evicting an overridden remote is the caller's job, see\n * `createRemoveCachedRemoteEntries` \u2014 every entry reaching here is merged additively. The\n * pipelines must not be merged, see docs/version-resolver.md \"Dynamic Init\". If a change ever\n * needs a flag or parameter here to serve only one caller, inline this back into the steps instead.\n */\nexport function createStoreRemoteEntry(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'scopedExternalsRepo'\n | 'sharedExternalsRepo'\n | 'sharedChunksRepo'\n | 'versionCheck'\n >,\n logStep: number\n): StoreRemoteEntry {\n return (remoteEntry, onSharedExternal) => {\n addRemoteInfoToStorage(remoteEntry);\n addExternalsToStorage(remoteEntry, onSharedExternal);\n addSharedChunksToStorage(remoteEntry);\n };\n\n function addRemoteInfoToStorage({ name, url, exposes, integrity }: RemoteEntry): void {\n ports.remoteInfoRepo.addOrUpdate(name, {\n scopeUrl: _path.getScope(url),\n exposes: Object.values(exposes ?? []).map(m => ({\n moduleName: m.key,\n file: m.outFileName,\n })),\n ...(integrity ? { integrity } : {}),\n } as RemoteInfo);\n }\n\n function addExternalsToStorage(\n remoteEntry: RemoteEntry,\n onSharedExternal: SharedExternalHandler\n ): void {\n remoteEntry.shared.forEach(external => {\n const tag = resolveVersion(remoteEntry, external);\n if (tag === null) return;\n\n if (external.singleton) {\n if (\n external.requiredVersion &&\n !ports.versionCheck.isCompatible(tag, external.requiredVersion)\n )\n config.log.warn(\n logStep,\n `[${remoteEntry.name}][${external.packageName}] requiredVersion '${external.requiredVersion}' excludes its own version '${tag}'; '${tag}' is still accepted for it.`\n );\n onSharedExternal(remoteEntry, external, sharedExternalContext(remoteEntry, external, tag));\n } else {\n addScopedExternal(remoteEntry, external, tag);\n }\n });\n }\n\n function addSharedChunksToStorage(remoteEntry: RemoteEntry): void {\n if (!remoteEntry.chunks) return;\n config.log.debug(\n logStep,\n `Adding chunks for remote \"${remoteEntry.name}\", bundles: [${Object.keys(remoteEntry.chunks).join(', ')}]`\n );\n Object.entries(remoteEntry.chunks).forEach(([bundleName, chunks]) => {\n ports.sharedChunksRepo.addOrReplace(remoteEntry.name, bundleName, chunks);\n });\n }\n\n function addScopedExternal(\n remoteEntry: RemoteEntry,\n sharedInfo: DenseSharedInfo,\n tag: string\n ): void {\n ports.scopedExternalsRepo.addExternal(remoteEntry.name, sharedInfo.packageName, {\n tag,\n bundle: sharedInfo.bundle,\n entries: sharedInfo.entries,\n } as ScopedVersion);\n }\n\n function resolveVersion(remoteEntry: RemoteEntry, external: DenseSharedInfo): string | null {\n if (external.version && ports.versionCheck.isValidSemver(external.version)) {\n return external.version;\n }\n\n const errorMsg = `[${remoteEntry.name}][${external.packageName}] Version '${external.version}' is not a valid version.`;\n if (config.strict.strictExternalVersion) {\n config.log.error(logStep, errorMsg);\n throw new NFError(`Could not process remote '${remoteEntry.name}'`);\n }\n if (config.profile.skipInvalidExternalVersions) {\n config.log.warn(logStep, `${errorMsg} Skipping external.`);\n return null;\n }\n config.log.warn(logStep, errorMsg);\n return ports.versionCheck.smallestVersion(external.requiredVersion);\n }\n\n function sharedExternalContext(\n remoteEntry: RemoteEntry,\n sharedInfo: RemoteSharedInfo,\n tag: string\n ): SharedExternalContext {\n const scopeType = ports.sharedExternalsRepo.scopeType(sharedInfo.shareScope);\n\n const remote: SharedVersionMeta = {\n name: remoteEntry.name,\n bundle: sharedInfo.bundle,\n strictVersion: sharedInfo.strictVersion,\n cached: false,\n requiredVersion: scopeType === 'strict' ? tag : sharedInfo.requiredVersion || tag,\n ...(sharedInfo.pool?.trim() ? { pool: sharedInfo.pool } : {}),\n ...(sharedInfo.dense ? { dense: true as const } : {}),\n entries: sharedInfo.entries,\n };\n\n // Read on first use: a runtime load stores its copies only after deciding them all, and an entry may list\n // one external twice (one row per tag).\n let stored: SharedExternal | undefined;\n const readRecord = (): SharedExternal =>\n (stored ??= ports.sharedExternalsRepo\n .tryGet(sharedInfo.packageName, sharedInfo.shareScope)\n .get() ?? { dirty: false, versions: [] });\n\n return {\n tag,\n remote,\n readRecord,\n scopeType,\n assertSameVersionCompatibility(matchingVersion: SharedVersion): void {\n if (!remote.strictVersion) return;\n if (matchingVersion.remotes[0]!.requiredVersion === remote.requiredVersion) return;\n\n const errorMsg = `[${remoteEntry.name}][${sharedInfo.packageName}@${\n sharedInfo.version\n }] Required version-range '${\n remote.requiredVersion\n }' does not match cached version-range '${matchingVersion.remotes[0]!.requiredVersion}'`;\n\n if (config.strict.strictExternalSameVersionCompatibility) {\n config.log.error(logStep, errorMsg);\n throw new NFError(`Could not process remote '${remoteEntry.name}'`);\n }\n config.log.warn(logStep, errorMsg);\n },\n write(): void {\n ports.sharedExternalsRepo.addOrUpdate(\n sharedInfo.packageName,\n {\n ...readRecord(),\n versions: readRecord().versions.sort((a, b) => ports.versionCheck.compare(b.tag, a.tag)),\n },\n sharedInfo.shareScope\n );\n },\n };\n }\n}\n", "import type { RemoteEntry } from 'lib/core/1.domain/remote-entry/remote-entry.contract';\nimport type {\n FederationManifest,\n RemoteEntryDescriptor,\n RemoteEntryUrl,\n} from 'lib/core/1.domain/remote-entry/manifest.contract';\nimport type { RemoteInfo, RemoteName } from 'lib/core/1.domain/remote/remote-info.contract';\nimport type { ForGettingRemoteEntries } from '../driver-ports/init/for-getting-remote-entries.port';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { ModeConfig } from '../config/mode.contract';\nimport type { HostConfig } from '../config/host.contract';\nimport * as _path from 'lib/utils/path';\nimport { createRemoveCachedRemoteEntries } from './store-remote-entry';\n\nexport function createGetRemoteEntries(\n config: LoggingConfig & ModeConfig & HostConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteEntryProvider'\n | 'manifestProvider'\n | 'remoteInfoRepo'\n | 'scopedExternalsRepo'\n | 'sharedExternalsRepo'\n | 'sharedChunksRepo'\n | 'sse'\n >\n): ForGettingRemoteEntries {\n const removeCachedRemoteEntries = createRemoveCachedRemoteEntries(ports);\n\n /**\n * Step 1: Fetch the remoteEntry JSON objects:\n *\n * A Manifest or URL to a Manifest is used as the input. Based on the defined remotes\n * in the manifest, the library will download the remoteEntry.json files which contain the\n * metadata of the defined remotes (name, exposed modules and required dependencies a.k.a. externals).\n * With `profile.mergeManifests: false`, stored remotes the manifest doesn't list are dropped first.\n *\n * @param config\n * @param adapters\n * @returns A list of the remoteEntry json objects\n */\n return (remotesOrManifestUrl = {}) => {\n const manifestPromise = config.manifestIntegrity\n ? ports.manifestProvider.provide(remotesOrManifestUrl, {\n integrity: config.manifestIntegrity,\n })\n : ports.manifestProvider.provide(remotesOrManifestUrl);\n\n return manifestPromise\n .catch(e => {\n config.log.error(1, 'Could not fetch manifest.', e);\n return Promise.reject(new NFError('Failed to fetch manifest'));\n })\n .then(addHostRemoteEntry)\n .then(dropUnlistedRemotes)\n .then(fetchRemoteEntries)\n .then(removeSkippedRemotes)\n .then(checkForSSE);\n };\n\n function addHostRemoteEntry(manifest: FederationManifest): FederationManifest {\n if (!config.hostRemoteEntry) return manifest;\n\n const { name, url, integrity } = config.hostRemoteEntry;\n\n return {\n ...manifest,\n [name]: integrity ? { url, integrity } : url,\n };\n }\n\n // Here rather than with the overrides in process-remote-entries: an unlisted remote has no fetched entry, and\n // only this step knows the manifest.\n function dropUnlistedRemotes(manifest: FederationManifest): FederationManifest {\n if (config.profile.mergeManifests !== false) return manifest;\n\n const listedUrls = new Set(\n Object.values(manifest).map(descriptor => normalizeEntry(descriptor).url)\n );\n // A remote fetched under another name than its manifest key is stored under the fetched one.\n const isListed = (remoteName: RemoteName, info: RemoteInfo) =>\n Object.hasOwn(manifest, remoteName) || listedUrls.has(storedEntryUrl(info));\n\n const unlisted = new Set(\n Object.entries(ports.remoteInfoRepo.getAll())\n .filter(([remoteName, info]) => !isListed(remoteName, info))\n .map(([remoteName]) => remoteName)\n );\n if (unlisted.size > 0)\n config.log.debug(\n 1,\n `Removing stored remotes the manifest doesn't list: ${[...unlisted].join(', ')}.`\n );\n removeCachedRemoteEntries(unlisted);\n return manifest;\n }\n\n function storedEntryUrl(info: RemoteInfo): RemoteEntryUrl {\n return _path.join(info.scopeUrl, 'remoteEntry.json');\n }\n\n function normalizeEntry(descriptor: RemoteEntryDescriptor): {\n url: RemoteEntryUrl;\n integrity?: string;\n } {\n return typeof descriptor === 'string' ? { url: descriptor } : descriptor;\n }\n\n function withCacheTag(url: string, cacheTag?: string): string {\n if (!cacheTag) return url;\n return `${url}${url.includes('?') ? '&' : '?'}cacheTag=${cacheTag}`;\n }\n\n function resolveCacheTag(remoteName: RemoteName): string | undefined {\n if (\n config.hostRemoteEntry &&\n remoteName === config.hostRemoteEntry.name &&\n config.hostRemoteEntry.cacheTag\n ) {\n return config.hostRemoteEntry.cacheTag;\n }\n return config.profile.cacheTag;\n }\n\n async function fetchRemoteEntries(\n manifest: FederationManifest\n ): Promise<(RemoteEntry | false)[]> {\n const fetchPromises = Object.entries(manifest).map(([remoteName, descriptor]) =>\n fetchRemoteEntry(remoteName, descriptor)\n );\n return Promise.all(fetchPromises);\n }\n\n async function fetchRemoteEntry(\n remoteName: RemoteName,\n descriptor: RemoteEntryDescriptor\n ): Promise<RemoteEntry | false> {\n const { url: remoteEntryUrl, integrity } = normalizeEntry(descriptor);\n let isOverride = false;\n let skip = false;\n\n ports.remoteInfoRepo.tryGet(remoteName).ifPresent(cachedRemoteInfo => {\n if (\n config.profile.overrideCachedRemotes !== 'never' &&\n (remoteEntryUrl !== storedEntryUrl(cachedRemoteInfo) ||\n config.profile.overrideCachedRemotesIfURLMatches)\n ) {\n config.log.debug(1, `Overriding existing remote '${remoteName}' with '${remoteEntryUrl}'.`);\n isOverride = true;\n } else {\n config.log.debug(1, `Found remote '${remoteName}' in storage, omitting fetch.`);\n skip = true;\n }\n });\n\n if (skip) return false;\n\n const fetchUrl = withCacheTag(remoteEntryUrl, resolveCacheTag(remoteName));\n\n try {\n const remoteEntry = integrity\n ? await ports.remoteEntryProvider.provide(fetchUrl, { integrity })\n : await ports.remoteEntryProvider.provide(fetchUrl);\n\n config.log.debug(\n 1,\n `Fetched '${remoteEntry.name}' from '${remoteEntry.url}', exposing: ${JSON.stringify(remoteEntry.exposes)}`\n );\n\n return prepareRemoteEntry(remoteEntry, remoteName, isOverride);\n } catch (error) {\n if (config.strict.strictRemoteEntry) {\n config.log.error(1, `Could not fetch remote '${remoteName}'.`, error);\n return Promise.reject(new NFError(`Could not fetch remote '${remoteName}'`));\n }\n config.log.warn(1, `Could not fetch remote '${remoteName}'. skipping init.`, error);\n\n return Promise.resolve(false);\n }\n }\n\n function prepareRemoteEntry(\n remoteEntry: RemoteEntry,\n expectedRemoteName: string,\n isOverride: boolean\n ): RemoteEntry {\n if (isOverride) remoteEntry.override = isOverride;\n\n if (!!config.hostRemoteEntry && expectedRemoteName === config.hostRemoteEntry.name) {\n remoteEntry.host = true;\n remoteEntry.name = config.hostRemoteEntry!.name;\n }\n\n if (remoteEntry.name !== expectedRemoteName) {\n const errorDetails = `Fetched remote '${remoteEntry.name}' does not match requested '${expectedRemoteName}'.`;\n if (config.strict.strictRemoteEntry) {\n throw new NFError(errorDetails);\n }\n config.log.warn(1, `${errorDetails} Omitting expected name.`);\n }\n\n return remoteEntry;\n }\n\n function removeSkippedRemotes(remoteEntries: (RemoteEntry | false)[]): RemoteEntry[] {\n return remoteEntries.filter((entry): entry is RemoteEntry => entry !== false);\n }\n\n function checkForSSE(remoteEntries: RemoteEntry[]): RemoteEntry[] {\n if (config.sse) {\n remoteEntries.forEach(entry => {\n if (entry.buildNotificationsEndpoint) {\n ports.sse.watchRemoteBuilds(\n _path.join(_path.getScope(entry.url), entry.buildNotificationsEndpoint)\n );\n config.log.debug(1, `Registered SSE endpoint of remote '${entry.name}' `);\n return;\n }\n config.log.debug(1, `Remote ${entry.name} has no defined 'buildNotificationsEndpoint'`);\n });\n }\n\n return remoteEntries;\n }\n}\n", "// Code-unit order: unlike `localeCompare`, the same in every browser and locale, so anything stored or elected\n// from a name comes out identical everywhere.\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nexport { compareStrings };\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport type { SharedVersion, SharedVersionMeta } from './version.contract';\n\nconst coverage = (remote: SharedVersionMeta): number => Object.keys(remote.entries).length;\n\n// `remotes[0]` is the basis: the copy every consumer of the version resolves to. Host and cached\n// outrank coverage because repointing them invalidates a committed import map. An exact tie goes to the\n// name, so the basis does not depend on the order remotes register in.\nexport function isBetterBasis(candidate: SharedVersionMeta, basis: SharedVersionMeta): boolean {\n if (basis.cached !== candidate.cached) return candidate.cached;\n const byCoverage = coverage(candidate) - coverage(basis);\n return byCoverage === 0 ? compareStrings(candidate.name, basis.name) < 0 : byCoverage > 0;\n}\n\nexport function addRemoteToVersion(\n version: SharedVersion,\n remote: SharedVersionMeta,\n isHost = false\n): void {\n if (isHost) {\n version.host = true;\n version.remotes.unshift(remote);\n return;\n }\n\n const basis = version.remotes[0];\n if (basis && !version.host && isBetterBasis(remote, basis)) {\n version.remotes.unshift(remote);\n return;\n }\n\n version.remotes.push(remote);\n}\n\n// `remotes[0]` answers \"who serves this version\", never \"what does this version demand\":\n// `requiredVersion`, `strictVersion` and `cached` are per-build settings, so remotes sharing a tag\n// can disagree on all three. Negotiation must therefore aggregate over every remote, or basis\n// precedence would decide compatibility. Deduped because those settings repeat across a version's\n// remotes, which keeps the resolver's O(versions\u00B2) selection from also scaling with remote count.\nexport function versionDemands(version: SharedVersion): SharedVersionMeta[] {\n if (version.remotes.length < 2) return version.remotes;\n\n const distinct = new Map<string, SharedVersionMeta>();\n for (const remote of version.remotes) {\n const key = `${remote.requiredVersion}|${remote.strictVersion}|${remote.cached}`;\n if (!distinct.has(key)) distinct.set(key, remote);\n }\n return Array.from(distinct.values());\n}\n\n// Which copies of a version may publish a specifier, in basis precedence; callers keep the first claim. The\n// copies build one tag, so this is what the version ships, not whose files a consumer runs; see\n// docs/version-resolver.md#copies-of-one-version.\n//\n// Only copies that publish their own files count. Pooling places a copy in a subpool running a foreign\n// build via `servedBy`, and the import map then names that build's files for it, per consumer \u2014 so what\n// such a copy bundles answers for nobody but itself, and counting it would promise a specifier no\n// consumer of this version can resolve. Pooling keeps a subpool copy out of the basis slot for exactly\n// this reason, so a `share` version's basis always survives the skip. `accepts` lets a caller discount a\n// copy without dropping its specifiers for the next copy to claim.\nexport function forEachVersionEntry(\n version: DeepReadonly<SharedVersion>,\n accepts: ((remote: SharedVersionMeta) => boolean) | undefined,\n visit: (entrypoint: string, remote: SharedVersionMeta) => void\n): void {\n for (const remote of version.remotes) {\n if (remote.servedBy) continue;\n if (accepts && !accepts(remote)) continue;\n for (const entrypoint in remote.entries) visit(entrypoint, remote);\n }\n}\n\ntype Covered = Pick<ReadonlySet<string>, 'has'>;\n\n// Counted rather than listed: the resolver's O(versions\u00B2) selection loop asks this once per remote per\n// candidate.\nexport function countUncoveredEntrypoints(remote: SharedVersionMeta, covered: Covered): number {\n let uncovered = 0;\n for (const entrypoint in remote.entries) {\n if (!covered.has(entrypoint)) uncovered++;\n }\n return uncovered;\n}\n", "import type { RemoteName } from '../remote/remote-info.contract';\nimport type { AcceptsTag } from './compatibility';\nimport type {\n SharedVersion,\n SharedVersionAction,\n SharedVersionMeta,\n VersionName,\n} from './version.contract';\n\n// Newest tag first, as `write()` orders a record. Leaves a tag's rows in their order (`sort` is stable).\nexport const byTag =\n (compare: (a: VersionName, b: VersionName) => number) =>\n (a: SharedVersion, b: SharedVersion): number =>\n compare(b.tag, a.tag);\n\nexport const rowAt = (\n versions: readonly SharedVersion[],\n tag: VersionName,\n action: SharedVersionAction\n): SharedVersion | undefined => versions.find(v => v.tag === tag && v.action === action);\n\n// One row per (tag, action): the first row of each absorbs the copies of the later ones, in place. `lead` is\n// that first row wherever it stands, so its copies stay in front.\nexport function mergeRows(versions: SharedVersion[], lead?: SharedVersion): SharedVersion[] {\n const merged = new Map<string, SharedVersion>();\n if (lead) merged.set(`${lead.tag}|${lead.action}`, lead);\n return versions.filter(v => {\n const key = `${v.tag}|${v.action}`;\n const first = merged.get(key);\n if (first === v) return true;\n if (!first) {\n merged.set(key, v);\n return true;\n }\n first.remotes.push(...v.remotes);\n return false;\n });\n}\n\n// `redirectRow` and `scopeRemote` can leave a `scope` row beside a shareable one at the same tag.\nexport function findVersionForTag(\n versions: SharedVersion[],\n tag: string\n): SharedVersion | undefined {\n let scoped: SharedVersion | undefined;\n for (const version of versions) {\n if (version.tag !== tag) continue;\n if (version.action !== 'scope') return version;\n scoped ??= version;\n }\n return scoped;\n}\n\n// Points a row at `tag`: its copies skip to it, and only the strict ones that reject it keep their own build,\n// split off into a `scope` row beside it. Returns the rows that replace `version`, in order; mutates it in place.\nexport function redirectRow(\n version: SharedVersion,\n tag: VersionName,\n acceptsTag: AcceptsTag\n): SharedVersion[] {\n const objecting = new Set(\n version.remotes.filter(r => r.strictVersion && !acceptsTag(tag, version.tag, r.requiredVersion))\n );\n\n if (objecting.size === 0) {\n version.action = 'skip';\n return [version];\n }\n if (objecting.size === version.remotes.length) {\n version.action = 'scope';\n return [version];\n }\n\n version.remotes = version.remotes.filter(r => !objecting.has(r));\n version.action = 'skip';\n // Beside its source rather than appended: the record stays newest-first, which `write()`\n // guarantees and a later election reads as \"the latest\".\n return [version, { tag: version.tag, host: false, action: 'scope', remotes: [...objecting] }];\n}\n\n// Moves each of `remotes`' copies out of every `share` and `skip` row into the `scope` row of their tag; a new scope\n// row goes right after its source, so the record stays newest-first. In one pass, yet ordered as if each remote\n// moved in turn: copies by remote then by row, a host's in front. Mutates the source rows, returns the new list.\nexport function scopeRemotes(\n versions: SharedVersion[],\n remotes: readonly RemoteName[]\n): SharedVersion[] {\n if (remotes.length === 0) return versions;\n const turn = new Map(remotes.map((remote, i) => [remote, i]));\n const moves = new Map<VersionName, Move[]>();\n versions.forEach((source, at) => {\n if (source.action === 'scope') return;\n const byTurn = new Map<number, SharedVersionMeta[]>();\n for (const copy of source.remotes) {\n const i = turn.get(copy.name);\n if (i === undefined) continue;\n const copies = byTurn.get(i);\n if (copies) copies.push(copy);\n else byTurn.set(i, [copy]);\n }\n if (byTurn.size === 0) return;\n // The host leads its row and a later election finds the host's tag by the flag, so both move with it.\n const hostTurn = source.host ? turn.get(source.remotes[0]!.name) : undefined;\n source.remotes = source.remotes.filter(r => !turn.has(r.name));\n if (hostTurn !== undefined) source.host = false;\n const tagMoves = moves.get(source.tag) ?? [];\n for (const [i, copies] of byTurn)\n tagMoves.push({ turn: i, at, source, copies, host: i === hostTurn });\n moves.set(source.tag, tagMoves);\n });\n\n const rows = [...versions];\n for (const [tag, tagMoves] of moves) {\n tagMoves.sort((a, b) => a.turn - b.turn || a.at - b.at);\n let scoped = rowAt(rows, tag, 'scope');\n if (!scoped) {\n scoped = { tag, host: false, action: 'scope', remotes: [] };\n rows.splice(rows.indexOf(tagMoves[0]!.source) + 1, 0, scoped);\n }\n for (const { copies, host } of tagMoves)\n if (host) {\n scoped.host = true;\n scoped.remotes.unshift(...copies);\n } else scoped.remotes.push(...copies);\n }\n return rows.filter(v => v.remotes.length > 0);\n}\n\ntype Move = {\n turn: number;\n at: number;\n source: SharedVersion;\n copies: SharedVersionMeta[];\n host: boolean;\n};\n", "import type { ForProcessingRemoteEntries } from '../driver-ports/init/for-processing-remote-entries.port';\nimport type { RemoteEntry, RemoteName, DenseSharedInfo } from 'lib/core/1.domain';\nimport { addRemoteToVersion } from 'lib/core/1.domain/externals/basis';\nimport { findVersionForTag } from 'lib/core/1.domain/externals/rows';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport {\n createRemoveCachedRemoteEntries,\n createStoreRemoteEntry,\n type SharedExternalContext,\n} from './store-remote-entry';\n\nexport function createProcessRemoteEntries(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'sharedExternalsRepo'\n | 'scopedExternalsRepo'\n | 'sharedChunksRepo'\n | 'versionCheck'\n >\n): ForProcessingRemoteEntries {\n const storeRemoteEntry = createStoreRemoteEntry(config, ports, 2);\n const removeCachedRemoteEntries = createRemoveCachedRemoteEntries(ports);\n\n /**\n * Step 2: Merge the remote-info, externals and chunks of the provided remoteEntry\n * objects into the cache. Shared externals are only registered here; resolution\n * happens later in determine-shared-externals, per scope, with global knowledge.\n */\n return remoteEntries => {\n try {\n const evictPerEntry = evictOverriddenRemotes(remoteEntries);\n remoteEntries.forEach(remoteEntry => {\n if (remoteEntry?.override && evictPerEntry.has(remoteEntry.name)) {\n removeCachedRemoteEntries(new Set([remoteEntry.name]));\n }\n storeRemoteEntry(remoteEntry, addSharedExternal);\n });\n return Promise.resolve(remoteEntries);\n } catch (e) {\n return Promise.reject(e);\n }\n };\n\n /**\n * Evict every overridden remote in one traversal of the shared-externals graph. Hoisting it ahead\n * of the merge is equivalent because removal only touches records carrying that remote's name \u2014\n * unless a name appears twice in the batch, which `get-remote-entries` permits when\n * `strictRemoteEntry` is off and a fetched entry disagrees with its manifest key.\n *\n * @returns the names that must still be evicted per entry, inside the merge loop.\n */\n function evictOverriddenRemotes(remoteEntries: RemoteEntry[]): Set<RemoteName> {\n const batched = new Set<RemoteName>();\n const repeated = new Set<RemoteName>();\n const seen = new Set<RemoteName>();\n\n for (const remoteEntry of remoteEntries) {\n if (!remoteEntry) continue;\n if (seen.has(remoteEntry.name)) repeated.add(remoteEntry.name);\n seen.add(remoteEntry.name);\n if (remoteEntry.override) batched.add(remoteEntry.name);\n }\n for (const remoteName of repeated) batched.delete(remoteName);\n\n removeCachedRemoteEntries(batched);\n return repeated;\n }\n\n function addSharedExternal(\n remoteEntry: RemoteEntry,\n _sharedInfo: DenseSharedInfo,\n {\n tag,\n remote,\n readRecord,\n scopeType,\n assertSameVersionCompatibility,\n write,\n }: SharedExternalContext\n ): void {\n const cached = readRecord();\n // Resolution is a function of the whole remote set, not of the tag list: a remote joining an\n // existing version can take the basis slot (changing what the version serves) and always adds\n // to `versionDemands` (changing what it accepts). Either way the cached actions are stale.\n if (scopeType !== 'strict') cached.dirty = true;\n\n const matchingVersion = findVersionForTag(cached.versions, tag);\n\n if (matchingVersion) {\n assertSameVersionCompatibility(matchingVersion);\n addRemoteToVersion(matchingVersion, remote, !matchingVersion.host && !!remoteEntry?.host);\n } else {\n cached.versions.push({\n tag,\n action: scopeType === 'strict' ? 'share' : 'skip',\n host: !!remoteEntry?.host,\n remotes: [remote],\n });\n }\n\n write();\n }\n}\n", "import type { SharedExternal } from './external.contract';\nimport type { SharedVersion, SharedVersionMeta } from './version.contract';\nimport { versionDemands } from './basis';\n\nexport type AcceptsTag = (offered: string, ownTag: string, requiredVersion: string) => boolean;\n\n// A copy runs the build it ships whatever its range says, so a range that excludes its own version (one\n// drifted from the lockfile) never rejects that version. Semver-equal, not string-equal: `v1.0.0` is `1.0.0`.\nexport function createAcceptsTag(\n isCompatible: (tag: string, requiredVersion: string) => boolean,\n compare: (a: string, b: string) => number\n): AcceptsTag {\n return (offered, ownTag, requiredVersion) =>\n isCompatible(offered, requiredVersion) || offered === ownTag || compare(offered, ownTag) === 0;\n}\n\nexport type VersionAcceptance = {\n // A version can only be redirected to `tag` if none of its remotes rejects that tag.\n accepts: (version: SharedVersion, tag: string) => boolean;\n // A representative copy that makes the redirect unsafe: it rejects `tag` while `strictVersion` is set,\n // so it keeps its own build instead of being deduped away. One is enough for the message and the\n // strict check; `redirectRow` enumerates the rest itself when it splits the version.\n objector: (version: SharedVersion, tag: string) => SharedVersionMeta | undefined;\n};\n\n// Every compatibility question is asked of the whole version, not of its basis: see `versionDemands`.\n// Computed once per external, since the selection loop is O(versions\u00B2).\nexport function versionAcceptance(\n external: SharedExternal,\n acceptsTag: AcceptsTag\n): VersionAcceptance {\n const demands = new Map<SharedVersion, SharedVersionMeta[]>(\n external.versions.map(v => [v, versionDemands(v)])\n );\n\n return {\n accepts: (version, tag) =>\n demands.get(version)!.every(d => acceptsTag(tag, version.tag, d.requiredVersion)),\n objector: (version, tag) =>\n demands\n .get(version)!\n .find(d => d.strictVersion && !acceptsTag(tag, version.tag, d.requiredVersion)),\n };\n}\n", "import type { SharedExternal, SharedVersion, SharedVersionMeta } from 'lib/core/1.domain';\nimport { mergeRows, redirectRow } from 'lib/core/1.domain/externals/rows';\nimport type { AcceptsTag, VersionAcceptance } from 'lib/core/1.domain/externals/compatibility';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\n\n// Fails init for a strict copy whose range rejects what is shared at `servedAt`; both are `name@tag`.\nexport function rejectIncompatible(\n config: LoggingConfig,\n copy: SharedVersionMeta,\n rejected: string,\n servedAt: string\n): never {\n config.log.error(\n 3,\n `[${copy.name}][${rejected}] Is not compatible with requiredRange '${copy.requiredVersion}' of shared ${servedAt}.`\n );\n throw new NFError(`External ${rejected} could not be shared.`);\n}\n\n/**\n * The tail of winner election: derive every other version's verdict from the chosen one, clear `dirty`.\n * `determine` is the only caller, and passes its `acceptsTag` plus the `acceptance` it already built for\n * the election.\n */\nexport function createApplyWinner(config: LoggingConfig & ModeConfig) {\n return function applyWinner(\n externalName: string,\n external: SharedExternal,\n winner: SharedVersion,\n acceptsTag: AcceptsTag,\n acceptance: VersionAcceptance\n ): SharedExternal {\n // Every copy accepts its own tag, so a lone version, like the winner, is never redirected or split.\n if (external.versions.length > 1) {\n const rebuilt: SharedVersion[] = [];\n\n for (const v of external.versions) {\n const objector =\n config.strict.strictExternalCompatibility && acceptance.objector(v, winner.tag);\n\n if (objector)\n rejectIncompatible(\n config,\n objector,\n `${externalName}@${v.tag}`,\n `${externalName}@${winner.tag}`\n );\n\n rebuilt.push(...redirectRow(v, winner.tag, acceptsTag));\n }\n\n // One row per (tag, action), which the record keeps: a warm record can already hold a `scope` row at\n // the tag a split produces. Merged after the loop, not during it: a row's verdict is not final until\n // the winner has been applied to it. The winner absorbs its tag's other rows, or the `share` below\n // would land on a row merged away.\n external.versions = mergeRows(rebuilt, winner);\n }\n\n winner.action = 'share';\n\n external.dirty = false;\n return external;\n };\n}\n", "import type { ForDeterminingSharedExternals } from '../driver-ports/init/for-determining-shared-externals.port';\nimport { GLOBAL_SCOPE, type SharedExternal, type SharedVersion } from 'lib/core/1.domain';\nimport { countUncoveredEntrypoints, forEachVersionEntry } from 'lib/core/1.domain/externals/basis';\nimport {\n type AcceptsTag,\n createAcceptsTag,\n versionAcceptance,\n} from 'lib/core/1.domain/externals/compatibility';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport { createApplyWinner } from './apply-winner';\n\nexport function createDetermineSharedExternals(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'versionCheck' | 'sharedExternalsRepo'>\n): ForDeterminingSharedExternals {\n const applyWinner = createApplyWinner(config);\n\n /**\n * Step 3: Determine which version is the optimal version to share.\n *\n * The shared external versions that were merged into the cache/storage caused the shared\n * external to be 'dirty', this step re-elects every dirty external by calculating the most optimal\n * version to share since only 1 version can be shared globally. Pooling runs first and writes every\n * member it elects with `dirty: false`, so determine never sees one. Every other copy\n * either skips onto the winner or, where its own range rejects it and `strictVersion` is set, is split\n * out into a scoped external of its own tag.\n *\n * Check the docs for a full explanation of the dependency resolver.\n *\n * Priority:\n * 1) Latest external defined in 'host' remoteEntry (if available).\n * 2) If defined in config, prioritize latest available version.\n * 3) Find most optimal version, by comparing potential extra downloads per version.\n *\n * @param config\n * @param adapters\n */\n return () => {\n const acceptsTag = createAcceptsTag(\n ports.versionCheck.isCompatible,\n ports.versionCheck.compare\n );\n\n for (const shareScope of ports.sharedExternalsRepo.getScopes()) {\n // The strict scope shares every tag side by side; an eviction still marks its externals dirty.\n if (ports.sharedExternalsRepo.scopeType(shareScope) === 'strict') continue;\n const sharedExternals = ports.sharedExternalsRepo.getFromScope(shareScope);\n\n try {\n Object.entries(sharedExternals)\n .filter(([_, e]) => e.dirty)\n .forEach(([name, external]) => {\n ports.sharedExternalsRepo.addOrUpdate(\n name,\n setVersionActions(name, external, acceptsTag),\n shareScope\n );\n });\n } catch (error) {\n config.log.error(\n 3,\n `[${shareScope ?? GLOBAL_SCOPE}] failed to determine shared externals.`,\n {\n sharedExternals,\n error,\n }\n );\n return Promise.reject(\n new NFError(\n `Could not determine shared externals in scope ${shareScope}.`,\n error as Error\n )\n );\n }\n }\n return Promise.resolve();\n };\n\n // Entrypoints declared by the versions `winner` would skip that none of its copies can serve. Every copy counts:\n // the serving build is decided later and may be any of them.\n function uncoveredTears(\n external: SharedExternal,\n winner: SharedVersion,\n accepts: (version: SharedVersion, tag: string) => boolean\n ): number {\n const covered = new Set<string>();\n forEachVersionEntry(winner, undefined, entrypoint => covered.add(entrypoint));\n return external.versions.reduce((sum, v) => {\n if (v === winner) return sum;\n if (!accepts(v, winner.tag)) return sum;\n return v.remotes.reduce((n, r) => n + countUncoveredEntrypoints(r, covered), sum);\n }, 0);\n }\n\n function setVersionActions(\n externalName: string,\n external: SharedExternal,\n acceptsTag: AcceptsTag\n ) {\n const acceptance = versionAcceptance(external, acceptsTag);\n\n if (external.versions.length === 1) {\n return applyWinner(externalName, external, external.versions[0]!, acceptsTag, acceptance);\n }\n\n const { accepts } = acceptance;\n\n let sharedVersion = external.versions.find(v => v.host);\n\n if (!sharedVersion && config.profile.latestSharedExternal) {\n sharedVersion = external.versions[0];\n }\n\n if (!sharedVersion) {\n // find version with least extra downloads, sorted by SEMVER version (O^2 complexity)\n let leastExtraDownloads = Number.MAX_VALUE;\n let leastTears = Number.MAX_VALUE;\n let leaderShared = false;\n // What a rejected version really costs: `applyWinner` splits it, so only the copies that themselves\n // reject the winner keep their own build. Cached copies are already downloaded and non-strict ones take\n // whatever is shared, so neither costs anything. Grouped by range so the O(versions\u00B2) selection loop\n // does not also scale with remote count.\n const selfServing = new Map<SharedVersion, { requiredVersion: string; copies: number }[]>(\n external.versions.map(v => {\n const groups = new Map<string, { requiredVersion: string; copies: number }>();\n for (const remote of v.remotes) {\n if (remote.cached || !remote.strictVersion) continue;\n const group = groups.get(remote.requiredVersion);\n if (group) group.copies++;\n else\n groups.set(remote.requiredVersion, {\n requiredVersion: remote.requiredVersion,\n copies: 1,\n });\n }\n return [v, [...groups.values()]];\n })\n );\n\n const costOf = (version: SharedVersion, tag: string) =>\n selfServing\n .get(version)!\n .reduce(\n (n, g) => (acceptsTag(tag, version.tag, g.requiredVersion) ? n : n + g.copies),\n 0\n );\n\n external.versions.forEach(vA => {\n const extraDownloads = external.versions.reduce((sum, vB) => sum + costOf(vB, vA.tag), 0);\n // A downloads tie goes to the version already shared, as keeping it saves a download, then to the one\n // that leaves fewest entrypoints uncovered across the versions it would skip (tears / scope-promotions).\n const alreadyShared = vA.action === 'share' && !!vA.remotes[0]?.cached;\n if (extraDownloads < leastExtraDownloads) {\n leastExtraDownloads = extraDownloads;\n leastTears = uncoveredTears(external, vA, accepts);\n leaderShared = alreadyShared;\n sharedVersion = vA;\n return;\n }\n if (extraDownloads > leastExtraDownloads || leaderShared) return;\n\n const tears = uncoveredTears(external, vA, accepts);\n if (alreadyShared || tears < leastTears) {\n leastTears = tears;\n leaderShared = alreadyShared;\n sharedVersion = vA;\n }\n });\n }\n\n if (!sharedVersion) {\n throw new NFError(`[${externalName}] Could not determine shared version!`);\n }\n\n // Determine action of other versions based on chosen sharedVersion\n return applyWinner(externalName, external, sharedVersion, acceptsTag, acceptance);\n }\n}\n", "// Iterative path halving: no stack growth in the browser.\nexport function unionFind() {\n const parent = new Map<string, string>();\n const find = (node: string): string => {\n for (let up = parent.get(node); up !== undefined; up = parent.get(node)) {\n const grand = parent.get(up);\n if (grand === undefined) return up;\n parent.set(node, grand);\n node = grand;\n }\n return node;\n };\n const union = (a: string, b: string): void => {\n const rootA = find(a);\n const rootB = find(b);\n if (rootA !== rootB) parent.set(rootB, rootA);\n };\n return { find, union };\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport { unionFind } from 'lib/utils/union-find';\nimport type { ExternalName, shareScope } from './external.contract';\nimport type { SharedVersionMeta, VersionName } from './version.contract';\n\n// An entrypoint as a consumer imports it; pooling keys by it, not by external name (see `pooling/builds.ts`).\nexport type Specifier = string;\n\n// An npm package name carries at most one `/` (after a leading `@scope`), so any deeper segment is a\n// subpath of the package above it: `@framework/core/testing` -> `@framework/core`, `rxjs/operators`\n// -> `rxjs`.\nexport function npmPackageOf(name: ExternalName): ExternalName {\n const depth = name.startsWith('@') ? 2 : 1;\n let cut = -1;\n for (let seen = 0; seen < depth; seen++) {\n cut = name.indexOf('/', cut + 1);\n if (cut === -1) return name;\n }\n return name.slice(0, cut);\n}\n\nexport type PackageOf = (specifier: Specifier) => ExternalName;\n\ntype StoredCopy = readonly [ExternalName, DeepReadonly<SharedVersionMeta>];\n\n// See docs/version-resolver.md \u00A7\"One build per package\".\nexport function packageOfIn(\n scope: DeepReadonly<shareScope>,\n loading: readonly StoredCopy[] = []\n): PackageOf {\n // A fast path, measured: without a declared library the records group by npm name anyway.\n if (!declaresLibrary(scope, loading)) return npmPackageOf;\n\n // Each component keeps its shortest name.\n const { find, union } = unionFind();\n const shortest = new Map<ExternalName, ExternalName>();\n for (const [name, copy] of copiesIn(scope, loading)) {\n const anchor = anchorOf(name, copy);\n for (const specifier in copy.entries) {\n const best = shorter(\n shortest.get(find(anchor)) ?? anchor,\n shortest.get(find(specifier)) ?? specifier\n );\n union(anchor, specifier);\n shortest.set(find(anchor), best);\n }\n }\n // An unlisted specifier joins whatever its npm name joined.\n return specifier => {\n const npm = npmPackageOf(specifier);\n return shortest.get(find(specifier)) ?? shortest.get(find(npm)) ?? npm;\n };\n}\n\nconst shorter = (a: ExternalName, b: ExternalName): ExternalName =>\n b.length < a.length || (b.length === a.length && compareStrings(b, a) < 0) ? b : a;\n\nfunction declaresLibrary(scope: DeepReadonly<shareScope>, loading: readonly StoredCopy[]): boolean {\n const isLibrary = (name: ExternalName, copies: readonly DeepReadonly<SharedVersionMeta>[]) =>\n npmPackageOf(name) !== name && copies.some(copy => copy.dense);\n return (\n loading.some(([name, copy]) => isLibrary(name, [copy])) ||\n Object.entries(scope).some(([name, external]) =>\n external.versions.some(version => isLibrary(name, version.remotes))\n )\n );\n}\n\n// A flat copy declares no package, so it is at least its npm package.\nconst anchorOf = (name: ExternalName, copy: DeepReadonly<SharedVersionMeta>): ExternalName =>\n copy.dense ? name : npmPackageOf(name);\n\nfunction* copiesIn(\n scope: DeepReadonly<shareScope>,\n loading: readonly StoredCopy[]\n): Generator<StoredCopy> {\n yield* loading;\n for (const [name, external] of Object.entries(scope))\n for (const version of external.versions) for (const copy of version.remotes) yield [name, copy];\n}\n\n// Tags per specifier that also pin the rest of their package: a package is one version, so its tag is the\n// root's, else the first entrypoint's \u2014 a package can ship entrypoints only (`material/table`, no root).\nexport class SpecifierTags extends Map<Specifier, VersionName> {\n private readonly packages = new Map<ExternalName, VersionName>();\n\n constructor(\n private readonly packageOf: PackageOf,\n entries: Iterable<readonly [Specifier, VersionName]> = []\n ) {\n super();\n for (const [specifier, tag] of entries) this.set(specifier, tag);\n }\n\n override set(specifier: Specifier, tag: VersionName): this {\n super.set(specifier, tag);\n const pkg = this.packageOf(specifier);\n if (pkg === specifier || !this.packages.has(pkg)) this.packages.set(pkg, tag);\n return this;\n }\n\n override clear(): void {\n super.clear();\n this.packages.clear();\n }\n\n pinnedTag(specifier: Specifier): VersionName | undefined {\n return this.get(specifier) ?? this.packages.get(this.packageOf(specifier));\n }\n}\n\nexport function groupByPackage<T>(\n items: Iterable<T>,\n nameOf: (item: T) => ExternalName,\n packageOf: PackageOf\n): Map<ExternalName, T[]> {\n const packages = new Map<ExternalName, T[]>();\n for (const item of items) {\n const pkg = packageOf(nameOf(item));\n const group = packages.get(pkg);\n if (group) group.push(item);\n else packages.set(pkg, [item]);\n }\n return packages;\n}\n", "import type { ExternalName, RemoteName, VersionName } from 'lib/core/1.domain';\nimport {\n type PackageOf,\n type Specifier,\n SpecifierTags,\n} from 'lib/core/1.domain/externals/specifier';\nimport type { PoolMember } from './membership';\n\n// Keyed by specifier so flat and dense builds of one package compare.\n\nexport type Copy = {\n member: ExternalName;\n tag: VersionName;\n requiredVersion: string;\n strict: boolean;\n // Basis precedence puts the host's own copy first on a `host: true` version.\n host: boolean;\n specifiers: Specifier[];\n};\n\nexport type Build = {\n owner: RemoteName;\n tags: SpecifierTags;\n tagByMember: Map<ExternalName, VersionName>;\n host: boolean;\n};\n\nexport function copiesByRemote(members: readonly PoolMember[]): Map<RemoteName, Copy[]> {\n const shipped = new Map<RemoteName, Copy[]>();\n for (const member of members) {\n const seen = new Set<RemoteName>();\n for (const version of member.external.versions)\n for (const meta of version.remotes) {\n // A remote ships one copy per member, so a second row is a record it cannot produce; the first row\n // wins whole, entries included, so a build never covers a specifier at a tag it does not ship.\n if (seen.has(meta.name)) continue;\n seen.add(meta.name);\n let copies = shipped.get(meta.name);\n if (!copies) shipped.set(meta.name, (copies = []));\n copies.push({\n member: member.name,\n tag: version.tag,\n requiredVersion: meta.requiredVersion,\n strict: meta.strictVersion,\n host: version.host && meta === version.remotes[0],\n specifiers: Object.keys(meta.entries),\n });\n }\n }\n return shipped;\n}\n\nexport const specifierCount = (copies: readonly Copy[]): number =>\n copies.reduce((n, copy) => n + copy.specifiers.length, 0);\n\nexport function buildOf(owner: RemoteName, copies: readonly Copy[], packageOf: PackageOf): Build {\n const tags = new SpecifierTags(packageOf);\n const tagByMember = new Map<ExternalName, VersionName>();\n for (const copy of copies) {\n for (const specifier of copy.specifiers)\n if (!tags.has(specifier)) tags.set(specifier, copy.tag);\n tagByMember.set(copy.member, copy.tag);\n }\n return { owner, tags, tagByMember, host: copies.some(c => c.host) };\n}\n", "import type { AcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport type { Specifier, SpecifierTags } from 'lib/core/1.domain/externals/specifier';\nimport type { Build, Copy } from './builds';\n\n// Plain loops: the election calls these per remote pair.\n// See docs/version-resolver.md \u00A7\"How pooling resolves\".\n\n// A specifier the tags do not list is still pinned by its package's tag: a flat `core/testing` at 22.0.6 next\n// to a build's `core` at 22.0.8 is two cores, whoever lists the entrypoint.\nexport function agrees(copies: readonly Copy[], tags: SpecifierTags): boolean {\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const tag = tags.pinnedTag(s);\n if (tag !== undefined && tag !== copy.tag) return false;\n }\n return true;\n}\n\nexport function serves(\n copies: readonly Copy[],\n tags: SpecifierTags,\n acceptsTag: AcceptsTag\n): boolean {\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const tag = tags.get(s);\n if (tag === undefined || !acceptsTag(tag, copy.tag, copy.requiredVersion)) return false;\n }\n return true;\n}\n\n// One build must have shipped the combination the copies would run at these tags; a build witnesses\n// its packages' other entrypoints at its tag. The gap is the first specifier no build ships next to\n// the ones before it.\nexport function unwitnessedGap(\n copies: readonly Copy[],\n tags: SpecifierTags,\n builds: Iterable<Build>\n): Specifier | undefined {\n const specifiers = copies.flatMap(c => c.specifiers);\n let gap = 0;\n for (const build of builds) {\n const miss = specifiers.findIndex(s => build.tags.pinnedTag(s) !== tags.get(s));\n if (miss === -1) return undefined;\n gap = Math.max(gap, miss);\n }\n return specifiers[gap];\n}\n", "import type { ExternalName, PoolCause, RemoteName, VersionName } from 'lib/core/1.domain';\nimport type { AcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport {\n type PackageOf,\n type Specifier,\n SpecifierTags,\n} from 'lib/core/1.domain/externals/specifier';\nimport { type Build, buildOf, type Copy, copiesByRemote } from './builds';\nimport type { PoolMember } from './membership';\nimport { agrees, serves, unwitnessedGap } from './rules';\nimport { compareStrings } from 'lib/utils/compare-strings';\n\n// See docs/version-resolver.md \u00A7\"How pooling resolves\".\n\ntype ElectionInput = {\n members: readonly PoolMember[];\n packageOf: PackageOf;\n acceptsTag: AcceptsTag;\n compare: (a: VersionName, b: VersionName) => number;\n // The stored record's winner, which breaks round-1 ties.\n previousWinner?: RemoteName;\n latestFirst: boolean;\n};\n\n// `unshipped`: the map serves every specifier, but no build shipped them together.\nexport type PoolMiss =\n | { cause: 'incompatible'; member: ExternalName; tag: VersionName; strict: boolean }\n | { cause: 'uncovered'; gap: Specifier; unshipped?: true };\n\n// A subpool's owner is placed in its own subpool.\nexport type Placement =\n { kind: 'global' } | { kind: 'subpool'; owner: RemoteName } | { kind: 'self'; cause: PoolCause };\n\nexport type Election = {\n winner: RemoteName;\n winnerIsHost: boolean;\n globalTags: SpecifierTags;\n placements: ReadonlyMap<RemoteName, Placement>;\n // In warning order: subpools in election order, then self. A strict range's rejection wins, as\n // `strictExternalCompatibility` refuses that. Undefined only for a subpool's owner the global map\n // would serve.\n misses: ReadonlyMap<RemoteName, PoolMiss | undefined>;\n};\n\ntype Subpool = { owner: RemoteName; remotes: RemoteName[] };\n\ntype Pool = ElectionInput & {\n shipped: Map<RemoteName, Copy[]>;\n builds: Map<RemoteName, Build>;\n packages: Map<RemoteName, Map<ExternalName, PackageCopy | null>>;\n // In record order: the order remotes first appear in the pool's versions.\n remotes: RemoteName[];\n servesAt: (remote: RemoteName, tags: SpecifierTags) => boolean;\n agreesAt: (remote: RemoteName, tags: SpecifierTags) => boolean;\n};\n\n// What each step hands the next.\ntype State = {\n readonly winner: RemoteName;\n globalTags: SpecifierTags;\n globalRemotes: Set<RemoteName>;\n // The packages the winner does not ship that the global tags publish.\n extensions: Set<ExternalName>;\n subpools: Subpool[];\n pending: RemoteName[];\n};\n\nexport function elect(input: ElectionInput): Election {\n const shipped = copiesByRemote(input.members);\n const builds = new Map<RemoteName, Build>();\n for (const [owner, copies] of shipped) builds.set(owner, buildOf(owner, copies, input.packageOf));\n const pool: Pool = {\n ...input,\n shipped,\n builds,\n packages: new Map(\n [...shipped].map(([owner, copies]) => [owner, packageCopies(owner, copies, input.packageOf)])\n ),\n remotes: [...shipped.keys()],\n servesAt: (remote, tags) => serves(shipped.get(remote)!, tags, input.acceptsTag),\n agreesAt: (remote, tags) => agrees(shipped.get(remote)!, tags),\n };\n\n // The host cannot be repointed, so its build is the global one whenever it ships any member.\n const hostRemote = pool.remotes.find(r => builds.get(r)!.host);\n const state = roundOne(pool, hostRemote);\n formSubpools(pool, state);\n // Last, so it only moves remotes no later round could place in a subpool.\n addExtensions(pool, state);\n promote(pool, state);\n while (settle(pool, state)) formSubpools(pool, state);\n\n const firstSeen = new Map(pool.remotes.map((r, i) => [r, i]));\n const self = state.pending.sort((a, b) => firstSeen.get(a)! - firstSeen.get(b)!);\n return {\n winner: state.winner,\n winnerIsHost: hostRemote !== undefined,\n globalTags: state.globalTags,\n ...placeRemotes(state.globalRemotes, state.subpools, self, r => missOf(pool, state, r)),\n };\n}\n\n// The first member both ship, in pool order, whose tags differ decides, so two unrelated version lines are\n// never compared.\nfunction newer(pool: Pool, a: Build, b: Build): number {\n for (const { name } of pool.members) {\n const tagA = a.tagByMember.get(name);\n const tagB = b.tagByMember.get(name);\n if (tagA === undefined || tagB === undefined) continue;\n const d = pool.compare(tagA, tagB);\n if (d !== 0) return d;\n }\n return 0;\n}\n\n// What the keys leave tied goes to the newer build, then to the name that sorts first. `newer` ties unrelated\n// builds, so three can still rank in a cycle; presorting by name keeps record order out of that too.\nfunction rank<C extends { build: Build }>(pool: Pool, candidates: C[], keys: ((c: C) => number)[]) {\n const scored = [...candidates]\n .sort((a, b) => compareStrings(a.build.owner, b.build.owner))\n .map(c => ({ c, k: keys.map(key => key(c)) }));\n scored.sort((a, b) => {\n for (let i = 0; i < keys.length; i++) {\n const d = b.k[i]! - a.k[i]!;\n if (d !== 0) return d;\n }\n return newer(pool, b.c.build, a.c.build) || compareStrings(a.c.build.owner, b.c.build.owner);\n });\n return scored[0]?.c;\n}\n\nfunction roundOne(pool: Pool, hostRemote: RemoteName | undefined): State {\n const { remotes } = pool;\n type Candidate = {\n build: Build;\n served: RemoteName[];\n // Remotes that agree without being served: when no build serves more than itself, they separate a build\n // its peers share from an outlier.\n agreeing: number;\n };\n const scored = new Map<string, Omit<Candidate, 'build'>>();\n const round1 = (hostRemote ? [hostRemote] : remotes).map<Candidate>(owner => {\n const build = pool.builds.get(owner)!;\n // Keyed in insertion order, which decides `pinnedTag`.\n const key = JSON.stringify([[...build.tags], [...build.tagByMember]]);\n let score = scored.get(key);\n if (!score) {\n const served = new Set(remotes.filter(r => pool.servesAt(r, build.tags)));\n const agreeing = remotes.filter(r => !served.has(r) && pool.agreesAt(r, build.tags)).length;\n scored.set(key, (score = { served: [...served], agreeing }));\n }\n return { build, ...score };\n });\n const newerThan = (c: Candidate) => round1.filter(o => newer(pool, c.build, o.build) > 0).length;\n const round1Winner = rank(pool, round1, [\n ...(pool.latestFirst ? [newerThan] : []),\n c => c.served.length,\n c => c.agreeing,\n c => (c.build.owner === pool.previousWinner ? 1 : 0),\n ])!;\n\n const winner = round1Winner.build.owner;\n const globalTags = new SpecifierTags(pool.packageOf, round1Winner.build.tags);\n const globalRemotes = new Set([winner, ...round1Winner.served]);\n\n const pending = remotes.filter(r => !globalRemotes.has(r));\n return { winner, globalTags, globalRemotes, extensions: new Set(), subpools: [], pending };\n}\n\nfunction formSubpools(pool: Pool, state: State): void {\n // The global tags hold still within a call and pending only shrinks, so who each build serves is found once.\n const servable = new Map(\n state.pending.map(owner => {\n const build = pool.builds.get(owner)!;\n const served = state.pending.filter(r => pool.servesAt(r, build.tags));\n return [owner, { build, served }];\n })\n );\n for (;;) {\n const stillPending = new Set(state.pending);\n const candidates = state.pending\n .map(owner => {\n const { build, served } = servable.get(owner)!;\n return { build, served: served.filter(r => stillPending.has(r)) };\n })\n .filter(c => c.served.includes(c.build.owner) && c.served.length >= 2);\n const best = rank(pool, candidates, [c => c.served.length]);\n if (!best) break;\n state.subpools.push({ owner: best.build.owner, remotes: best.served });\n state.pending = state.pending.filter(r => !best.served.includes(r));\n }\n}\n\nfunction promote(pool: Pool, state: State): void {\n const { globalTags, globalRemotes } = state;\n // Whoever the global tags now serve resolves globally, in a subpool or not \u2014 but a subpool's owner only once\n // no other member needs it. A subpool of one is none: its owner goes global when served, else serves itself.\n const takesGlobal = (remote: RemoteName) =>\n pool.servesAt(remote, globalTags) &&\n unwitnessedGap(pool.shipped.get(remote)!, globalTags, pool.builds.values()) === undefined;\n for (const remote of state.pending) if (takesGlobal(remote)) globalRemotes.add(remote);\n state.pending = state.pending.filter(r => !globalRemotes.has(r));\n for (const subpool of state.subpools) {\n const moved = subpool.remotes.filter(r => r !== subpool.owner && takesGlobal(r));\n for (const remote of moved) globalRemotes.add(remote);\n subpool.remotes = subpool.remotes.filter(r => !moved.includes(r));\n }\n state.subpools = state.subpools.filter(subpool => {\n if (subpool.remotes.length >= 2) return true;\n if (takesGlobal(subpool.owner)) globalRemotes.add(subpool.owner);\n else state.pending.push(subpool.owner);\n return false;\n });\n}\n\n// A package round 1 does not ship at all is published from one build that agrees with the global tags, so it\n// runs whole from that build: the copy that contains the most others. A subpool copy resolves globally only\n// when its subpool's owner agrees. Under a host, the agreeing members of subpools whose build disagrees with\n// the host then offer the packages still missing, so they can move onto the host's runtime.\nfunction addExtensions(pool: Pool, state: State): void {\n const { globalTags, globalRemotes } = state;\n const runsOn = (remote: RemoteName) =>\n state.subpools.find(p => p.remotes.includes(remote))?.owner ?? remote;\n const agreeing = pool.remotes.filter(r => !globalRemotes.has(r) && pool.agreesAt(r, globalTags));\n const runsGlobally = (remote: RemoteName) => pool.agreesAt(runsOn(remote), globalTags);\n const offered = offers(pool, globalTags, agreeing.filter(runsGlobally));\n const fill = pool.builds.get(state.winner)!.host ? agreeing.filter(r => !runsGlobally(r)) : [];\n for (const [pkg, offer] of offers(pool, globalTags, fill))\n if (!offered.has(pkg)) offered.set(pkg, offer);\n for (const [pkg, offer] of offered) {\n if (!offer) continue;\n state.extensions.add(pkg);\n for (const s of offer.specifiers) globalTags.set(s, offer.tag);\n }\n}\n\ntype PackageCopy = { owner: RemoteName; tag: VersionName; specifiers: Set<Specifier> };\n\n// A remote's copy of each package, or null where it ships the package at two tags.\nfunction packageCopies(\n owner: RemoteName,\n copies: readonly Copy[],\n packageOf: PackageOf\n): Map<ExternalName, PackageCopy | null> {\n const packages = new Map<ExternalName, PackageCopy | null>();\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const pkg = packageOf(s);\n const seen = packages.get(pkg);\n if (seen === undefined) packages.set(pkg, { owner, tag: copy.tag, specifiers: new Set([s]) });\n else if (seen && seen.tag !== copy.tag) packages.set(pkg, null);\n else seen?.specifiers.add(s);\n }\n return packages;\n}\n\n// Per package the remotes ship and the global tags do not pin: the copy chosen to publish it, or null when\n// they ship it at two tags.\nfunction offers(pool: Pool, globalTags: SpecifierTags, remotes: RemoteName[]) {\n const candidates = new Map<ExternalName, (PackageCopy | null)[]>();\n for (const owner of remotes)\n for (const [pkg, copy] of pool.packages.get(owner)!)\n if (globalTags.pinnedTag(pkg) === undefined)\n candidates.set(pkg, [...(candidates.get(pkg) ?? []), copy]);\n const offered = new Map<ExternalName, PackageCopy | null>();\n for (const [pkg, copies] of candidates)\n offered.set(pkg, oneTag(copies) ? coveringCopy(copies) : null);\n return offered;\n}\n\nconst oneTag = (copies: (PackageCopy | null)[]): copies is PackageCopy[] =>\n copies.every(c => c !== null && c.tag === copies[0]!.tag);\n\n// The copy that contains the most others, then the widest; ties go to the name that sorts first.\nfunction coveringCopy(candidates: PackageCopy[]): PackageCopy {\n const scored = candidates.map(c => ({\n c,\n covers: candidates.filter(o => contains(c.specifiers, o.specifiers)).length,\n }));\n scored.sort(\n (a, b) =>\n b.covers - a.covers ||\n b.c.specifiers.size - a.c.specifiers.size ||\n compareStrings(a.c.owner, b.c.owner)\n );\n return scored[0]!.c;\n}\n\nconst contains = (a: ReadonlySet<Specifier>, b: ReadonlySet<Specifier>) =>\n [...b].every(s => a.has(s));\n\n// The global map publishes a package the winner does not ship only while a global remote ships a copy of\n// exactly its tags: the chosen one or another, as the same files at one tag are the same code. Otherwise the\n// package's tags drop, whole; whoever that leaves unserved joins the first subpool whose owner serves it,\n// else goes back to the later rounds.\nfunction settle(pool: Pool, state: State): boolean {\n const { globalTags, globalRemotes, extensions } = state;\n let demoted = false;\n for (;;) {\n const dropped = new Set([...extensions].filter(pkg => !publishedWhole(pool, state, pkg)));\n if (dropped.size === 0) return demoted;\n for (const pkg of dropped) extensions.delete(pkg);\n const kept = [...globalTags].filter(([s]) => !dropped.has(pool.packageOf(s)));\n globalTags.clear();\n for (const [s, tag] of kept) globalTags.set(s, tag);\n for (const remote of globalRemotes)\n if (remote !== state.winner && !pool.servesAt(remote, globalTags)) {\n globalRemotes.delete(remote);\n const subpool = state.subpools.find(p =>\n pool.servesAt(remote, pool.builds.get(p.owner)!.tags)\n );\n if (subpool) subpool.remotes.push(remote);\n else state.pending.push(remote);\n demoted = true;\n }\n }\n}\n\nfunction publishedWhole(pool: Pool, state: State, pkg: string): boolean {\n const published = new Set([...state.globalTags.keys()].filter(s => pool.packageOf(s) === pkg));\n const tag = state.globalTags.pinnedTag(pkg);\n return [...state.globalRemotes].some(remote => {\n const copy = pool.packages.get(remote)!.get(pkg);\n return (\n !!copy &&\n copy.tag === tag &&\n copy.specifiers.size === published.size &&\n contains(copy.specifiers, published)\n );\n });\n}\n\nfunction missOf(pool: Pool, state: State, remote: RemoteName): PoolMiss | undefined {\n const { globalTags } = state;\n const copies = pool.shipped.get(remote)!;\n let rejected: PoolMiss | undefined;\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const tag = globalTags.get(s);\n if (tag === undefined || pool.acceptsTag(tag, copy.tag, copy.requiredVersion)) continue;\n if (copy.strict) return { cause: 'incompatible', member: copy.member, tag, strict: true };\n rejected ??= { cause: 'incompatible', member: copy.member, tag, strict: false };\n }\n if (rejected) return rejected;\n for (const copy of copies)\n for (const s of copy.specifiers) if (!globalTags.has(s)) return { cause: 'uncovered', gap: s };\n const gap = unwitnessedGap(copies, globalTags, pool.builds.values());\n if (gap) return { cause: 'uncovered', gap, unshipped: true };\n // Everyone else the final global tags serve is global, so only a subpool's owner can lack a reason.\n if (state.subpools.some(p => p.owner === remote)) return undefined;\n throw new Error(`'${remote}' missed the global map with nothing it rejects or lacks.`);\n}\n\n// A member that joined since carries no winner yet; only two stored winners that conflict void it.\nexport function previousWinner(members: PoolMember[]): RemoteName | undefined {\n const winners = new Set(members.flatMap(m => m.external.poolWinner ?? []));\n const [winner] = winners;\n if (winners.size !== 1) return undefined;\n const ships = members.some(m =>\n m.external.versions.some(v => v.remotes.some(r => r.name === winner))\n );\n return ships ? winner : undefined;\n}\n\nfunction placeRemotes(\n globalRemotes: ReadonlySet<RemoteName>,\n subpools: readonly Subpool[],\n self: readonly RemoteName[],\n missOf: (remote: RemoteName) => PoolMiss | undefined\n): Pick<Election, 'placements' | 'misses'> {\n const misses = new Map<RemoteName, PoolMiss | undefined>();\n for (const remote of [...subpools.flatMap(p => p.remotes), ...self])\n misses.set(remote, missOf(remote));\n const placements = new Map<RemoteName, Placement>();\n for (const remote of globalRemotes) placements.set(remote, { kind: 'global' });\n for (const { owner, remotes } of subpools)\n for (const remote of remotes) placements.set(remote, { kind: 'subpool', owner });\n for (const remote of self)\n placements.set(remote, { kind: 'self', cause: misses.get(remote)!.cause });\n return { placements, misses };\n}\n", "import type { ExternalName, SharedExternal, shareScope } from 'lib/core/1.domain';\nimport { type PackageOf, packageOfIn } from 'lib/core/1.domain/externals/specifier';\nimport type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport { unionFind } from 'lib/utils/union-find';\n\n// Unique per share scope: the most-declared of the labels merged into the pool.\nexport type PoolName = string;\n\nexport type PoolMember = {\n name: ExternalName;\n external: DeepReadonly<SharedExternal>;\n};\n\nexport type Membership = {\n pools: Map<PoolName, PoolMember[]>;\n // In scope order.\n labelledAlone: ExternalName[];\n packageOf: PackageOf;\n};\n\n// A copy the record doesn't hold yet: its external and its `pool` label.\nexport type LabelledCopy = { name: ExternalName; pool?: string };\n\n// A label is one node across every remote: the label is the pool's identity.\n// NUL-separated so a label can never alias an external.\nconst extNode = (name: ExternalName): string => `ext\\x00${name}`;\nconst labelNode = (label: string): string => `label\\x00${label}`;\n\nconst labelOf = (pool?: string): string | undefined => pool?.trim() || undefined;\n\n// One entry per declaring copy, which `mostDeclaredLabel` counts; in scope order.\nfunction labelsIn(sharedExternals: DeepReadonly<shareScope>): Map<ExternalName, string[]> {\n const labelsOf = new Map<ExternalName, string[]>();\n for (const [name, external] of Object.entries(sharedExternals))\n labelsOf.set(\n name,\n external.versions.flatMap(v => v.remotes.flatMap(r => labelOf(r.pool) ?? []))\n );\n return labelsOf;\n}\n\n// A pool is a connected component of `external -> label` and `entrypoint -> package` edges; see\n// docs/version-resolver.md \u00A7\"Enabling pooling\". Components in `labelsOf` order, each with a label.\nfunction labelledComponents(\n labelsOf: ReadonlyMap<ExternalName, readonly string[]>,\n packageOf: PackageOf\n): ExternalName[][] {\n const { find, union } = unionFind();\n for (const [name, labels] of labelsOf)\n for (const label of labels) union(extNode(name), labelNode(label));\n\n // An entrypoint follows its package into whatever pool the package joins, labelled or not: a flat build\n // that labels only the package would otherwise leave its entrypoints out \u2014 measured as a torn package.\n // The package's node needs no root external, so a package that ships only entrypoints stays one unit too.\n for (const name of labelsOf.keys()) {\n const owner = packageOf(name);\n if (owner !== name) union(extNode(name), extNode(owner));\n }\n\n const byComponent = new Map<string, ExternalName[]>();\n for (const name of labelsOf.keys()) {\n const root = find(extNode(name));\n const names = byComponent.get(root) ?? byComponent.set(root, []).get(root)!;\n names.push(name);\n }\n // A property of the component, not of one member: an entrypoint carries no label of its own yet pools\n // with the package that does.\n return [...byComponent.values()].filter(names => names.some(n => labelsOf.get(n)!.length > 0));\n}\n\nexport function buildPools(\n sharedExternals: DeepReadonly<shareScope>,\n packageOf: PackageOf = packageOfIn(sharedExternals)\n): Membership {\n const labelsOf = labelsIn(sharedExternals);\n // Unique without suffixing: a label belongs to exactly one component, so two pools never pick the same one.\n const pools = new Map<PoolName, PoolMember[]>();\n const labelledAlone: ExternalName[] = [];\n for (const names of labelledComponents(labelsOf, packageOf)) {\n if (names.length < 2) labelledAlone.push(names[0]!);\n else {\n const members = names.map(name => ({ name, external: sharedExternals[name]! }));\n pools.set(\n mostDeclaredLabel(members, labelsOf),\n members.sort((a, b) => compareStrings(a.name, b.name))\n );\n }\n }\n return { pools, labelledAlone, packageOf };\n}\n\n// The packages `buildPools` pools once `copies` are stored in the scope.\nexport function pooledPackagesWith(\n sharedExternals: DeepReadonly<shareScope>,\n copies: readonly LabelledCopy[],\n packageOf: PackageOf\n): Set<ExternalName> {\n const labelsOf = labelsIn(sharedExternals);\n for (const { name, pool } of copies) {\n const labels = labelsOf.get(name) ?? [];\n const label = labelOf(pool);\n labelsOf.set(name, label === undefined ? labels : [...labels, label]);\n }\n return new Set(\n labelledComponents(labelsOf, packageOf)\n .filter(names => names.length > 1)\n .flatMap(names => names.map(packageOf))\n );\n}\n\nfunction mostDeclaredLabel(\n members: readonly PoolMember[],\n labelsOf: ReadonlyMap<ExternalName, readonly string[]>\n): string {\n const counts = new Map<string, number>();\n for (const member of members)\n for (const label of labelsOf.get(member.name)!) counts.set(label, (counts.get(label) ?? 0) + 1);\n\n let best = '';\n let top = 0;\n for (const [label, count] of counts)\n if (count > top || (count === top && compareStrings(label, best) < 0))\n [best, top] = [label, count];\n return best;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type { SharedExternal, shareScope } from '../externals/external.contract';\n\n// Outside a pool, pool results are stale. The declared `pool` label is pooling's input, not a result, and\n// always stays.\nexport function hasPoolResults(external: DeepReadonly<SharedExternal>): boolean {\n if (external.poolName !== undefined || external.poolWinner !== undefined) return true;\n return external.versions.some(v =>\n v.remotes.some(r => r.servedBy !== undefined || r.poolCause !== undefined)\n );\n}\n\n// Stored results outlive the last label that left, so they count; read from the record, not this init.\nexport function scopeHasPoolState(scope: DeepReadonly<shareScope>): boolean {\n for (const name in scope) {\n const external = scope[name]!;\n if (hasPoolResults(external)) return true;\n for (const version of external.versions)\n for (const remote of version.remotes) if (remote.pool?.trim()) return true;\n }\n return false;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type {\n ExternalName,\n PoolCause,\n RemoteName,\n SharedExternal,\n SharedVersion,\n SharedVersionMeta,\n shareScope,\n VersionName,\n} from 'lib/core/1.domain';\nimport { addRemoteToVersion } from 'lib/core/1.domain/externals/basis';\nimport { byTag, mergeRows, rowAt } from 'lib/core/1.domain/externals/rows';\nimport type { Election } from './election';\nimport type { PoolMember, PoolName } from './membership';\n\nexport type PlacedPool = Election & { poolName: PoolName };\n\n// One row per (tag, action); see docs/version-resolver.md \u00A7\"How the verdicts land in the record and the map\".\nexport function memberRecord(\n member: PoolMember,\n pool: PlacedPool,\n compare: (a: VersionName, b: VersionName) => number\n): SharedExternal {\n const { globalTags, placements } = pool;\n // The external's own specifier fixes its shared tag; a package can ship only secondary entrypoints\n // (`material/table` without `material`), so failing that it is whatever round 1 serves any of them at.\n let sharedTag = globalTags.get(member.name);\n for (const version of member.external.versions)\n for (const meta of version.remotes)\n for (const s in meta.entries) sharedTag ??= globalTags.get(s);\n\n const claimsGlobally = (name: RemoteName) => placements.get(name)!.kind === 'global';\n\n const placed: SharedVersion[] = [];\n let winnerRow: SharedVersion | undefined;\n const place = (tag: VersionName, action: SharedVersion['action'], meta: SharedVersionMeta) => {\n const row = { tag, host: false, action, remotes: [meta] };\n placed.push(row);\n if (meta.name !== pool.winner) return;\n // The winner's copy leads its row: `remotes[0]` is the basis the global map publishes.\n winnerRow = row;\n row.host = pool.winnerIsHost;\n };\n\n for (const version of member.external.versions)\n for (const stored of version.remotes) {\n const { servedBy: _servedBy, poolCause: _poolCause, ...rest } = stored;\n // The import map is rebuilt from scratch, so it re-marks what it publishes.\n const meta = { ...rest, cached: false };\n const placement = placements.get(meta.name)!;\n if (placement.kind === 'global')\n place(version.tag, version.tag === sharedTag ? 'share' : 'skip', meta);\n else if (placement.kind === 'subpool')\n place(version.tag, 'skip', { ...meta, servedBy: placement.owner });\n else place(version.tag, 'scope', { ...meta, poolCause: placement.cause });\n }\n\n const rows = mergeRows(placed, winnerRow);\n // Stable, so the winner still leads; the import map publishes the first copy listing a specifier.\n for (const row of rows)\n row.remotes.sort((a, b) => Number(!claimsGlobally(a.name)) - Number(!claimsGlobally(b.name)));\n\n const order = { share: 0, skip: 1, scope: 2 };\n const newest = byTag(compare);\n const versions = rows.sort((a, b) => newest(a, b) || order[a.action] - order[b.action]);\n\n return { dirty: false, poolName: pool.poolName, versions };\n}\n\nexport type CopyMove = { cause: PoolCause } | { fromMap: true };\n\n// A fresh record, only the loaded remote's copy moved.\nexport function movedRecord(\n external: SharedExternal,\n remote: RemoteName,\n move: CopyMove,\n compare: (a: VersionName, b: VersionName) => number\n): SharedExternal {\n return withoutStaleServingBuild(moveCopy(external, remote, move, compare));\n}\n\n// The claim table trusts `servingBuild`, so a move that takes the named copy out of every share row drops it.\nfunction withoutStaleServingBuild(record: SharedExternal): SharedExternal {\n const { servingBuild, ...rest } = record;\n if (servingBuild === undefined) return record;\n const shares = record.versions.some(\n v => v.action === 'share' && v.remotes.some(r => r.name === servingBuild)\n );\n return shares ? record : rest;\n}\n\nfunction moveCopy(\n external: SharedExternal,\n remote: RemoteName,\n move: CopyMove,\n compare: (a: VersionName, b: VersionName) => number\n): SharedExternal {\n if ('fromMap' in move) return recordFromMap(external, remote);\n\n const moved: { tag: string; meta: SharedVersionMeta }[] = [];\n const versions = external.versions\n .map(v => {\n const copy = v.remotes.find(r => r.name === remote);\n if (!copy) return v;\n const { servedBy: _servedBy, ...rest } = copy;\n const meta = { ...rest, cached: true, poolCause: move.cause };\n if (v.action === 'scope')\n return { ...v, remotes: v.remotes.map(r => (r === copy ? meta : r)) };\n moved.push({ tag: v.tag, meta });\n return { ...v, remotes: v.remotes.filter(r => r !== copy) };\n })\n // A version only the loaded remote held \u2014 a `share` it introduced \u2014 leaves with it.\n .filter(v => v.remotes.length > 0);\n\n for (const { tag, meta } of moved) {\n const scoped = rowAt(versions, tag, 'scope');\n if (!scoped) versions.push({ tag, action: 'scope', host: false, remotes: [meta] });\n else versions[versions.indexOf(scoped)] = { ...scoped, remotes: [...scoped.remotes, meta] };\n }\n\n return { ...external, versions: versions.sort(byTag(compare)) };\n}\n\n// A copy that now runs the map's files moves into a skip row at its tag: it publishes nothing. A tag keeps one\n// row per action, so it joins a skip row already there.\nfunction recordFromMap(external: SharedExternal, remote: RemoteName): SharedExternal {\n // The copy sits alone in the share row it opened, among other islands in a scope row, or in a share row it\n // joined at the same tag, whose other copies stay.\n const opened = external.versions.find(\n v => v.action !== 'skip' && v.remotes.some(r => r.name === remote)\n )!;\n const meta = { ...opened.remotes.find(r => r.name === remote)!, cached: false };\n const joined = rowAt(external.versions, opened.tag, 'skip');\n const into = joined\n ? { ...joined, remotes: [...joined.remotes] }\n : { ...opened, action: 'skip' as const, remotes: [] };\n addRemoteToVersion(into, meta);\n\n const versions = external.versions.flatMap(v => {\n if (v === joined) return [into];\n if (v !== opened) return [v];\n const left = { ...v, remotes: v.remotes.filter(r => r.name !== remote) };\n return [...(left.remotes.length > 0 ? [left] : []), ...(joined ? [] : [into])];\n });\n return { ...external, versions };\n}\n\nexport function withoutPoolResults(external: DeepReadonly<SharedExternal>): SharedExternal {\n const { poolName: _poolName, poolWinner: _poolWinner, ...rest } = external;\n return {\n ...rest,\n versions: external.versions.map(v => ({\n ...v,\n remotes: v.remotes.map(({ servedBy: _servedBy, poolCause: _poolCause, ...meta }) => meta),\n })),\n };\n}\n\n// Pool results are kept: a pool nobody re-elected can still be renamed by another. An external in no pool\n// keeps its stored name until the next dirty init strips it.\nexport function renamedRecords(\n scope: shareScope,\n pools: ReadonlyMap<PoolName, readonly PoolMember[]>\n): [ExternalName, SharedExternal][] {\n const renamed: [ExternalName, SharedExternal][] = [];\n for (const [poolName, members] of pools)\n for (const { name } of members)\n if (scope[name]!.poolName !== poolName) renamed.push([name, { ...scope[name]!, poolName }]);\n return renamed;\n}\n", "import type { ExternalName, SharedExternal, shareScope } from '../externals/external.contract';\nimport { buildPools, type PoolMember, type PoolName } from './membership';\nimport { hasPoolResults, scopeHasPoolState } from './pool-state';\nimport { withoutPoolResults } from './records';\nimport type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { type PackageOf, npmPackageOf } from '../externals/specifier';\n\nexport type ElectionPlan = {\n pools: Map<PoolName, PoolMember[]>;\n // Dirty so determine re-elects them.\n stripped: Map<ExternalName, SharedExternal>;\n labelledAlone: ExternalName[];\n packageOf: PackageOf;\n};\n\n// Any dirty external re-elects every pool of its scope.\n// See docs/version-resolver.md \u00A7\"How the verdicts land in the record and the map\".\nexport function planElection(scope: DeepReadonly<shareScope>, poolable: boolean): ElectionPlan {\n // Skip before building the graph: measured, that was the whole pooling cost of a warm init.\n if (\n !poolable ||\n !Object.values(scope).some(external => external.dirty) ||\n !scopeHasPoolState(scope)\n )\n return { pools: new Map(), stripped: new Map(), labelledAlone: [], packageOf: npmPackageOf };\n\n const { pools, labelledAlone, packageOf } = buildPools(scope);\n const pooled = new Set([...pools.values()].flatMap(members => members.map(m => m.name)));\n const stripped = new Map<ExternalName, SharedExternal>();\n for (const [name, external] of Object.entries(scope))\n if (!pooled.has(name) && hasPoolResults(external))\n stripped.set(name, { ...withoutPoolResults(external), dirty: true });\n return { pools, stripped, labelledAlone, packageOf };\n}\n", "import type { ForPoolingSharedExternals } from '../../driver-ports/init/for-pooling-shared-externals.port';\nimport type { ExternalName, RemoteName, SharedExternal, shareScope } from 'lib/core/1.domain';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { DrivingContract } from '../../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../../config/log.contract';\nimport type { ModeConfig } from '../../config/mode.contract';\nimport { createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport type { PackageOf } from 'lib/core/1.domain/externals/specifier';\nimport { type Copy, copiesByRemote, specifierCount } from 'lib/core/1.domain/pooling/builds';\nimport { elect, type PoolMiss, previousWinner } from 'lib/core/1.domain/pooling/election';\nimport type { PoolMember, PoolName } from 'lib/core/1.domain/pooling/membership';\nimport { type ElectionPlan, planElection } from 'lib/core/1.domain/pooling/plan';\nimport { memberRecord, type PlacedPool } from 'lib/core/1.domain/pooling/records';\n\nexport function createPoolSharedExternals(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'sharedExternalsRepo' | 'versionCheck'>\n): ForPoolingSharedExternals {\n const { compare } = ports.versionCheck;\n\n // See docs/version-resolver.md \u00A7\"How pooling resolves\".\n return () => {\n const repo = ports.sharedExternalsRepo;\n for (const scope of repo.getScopes()) {\n const sharedExternals = repo.getFromScope(scope);\n try {\n const plan = planElection(sharedExternals, repo.scopeType(scope) !== 'strict');\n logPlan(plan, sharedExternals, scope);\n for (const [poolName, members] of plan.pools)\n for (const [name, record] of poolRecords(poolName, members, plan.packageOf, scope))\n repo.addOrUpdate(name, record, scope);\n for (const [name, external] of plan.stripped) repo.addOrUpdate(name, external, scope);\n } catch (error) {\n if (error instanceof NFError) return Promise.reject(error);\n config.log.error(3, `[${scope}] failed to pool shared externals.`, {\n sharedExternals,\n error,\n });\n return Promise.reject(\n new NFError(`Could not pool shared externals in scope ${scope}.`, error as Error)\n );\n }\n }\n return Promise.resolve();\n };\n\n function logPlan(plan: ElectionPlan, sharedExternals: shareScope, scope: string): void {\n if (plan.pools.size > 0) {\n const dirty = Object.values(sharedExternals).filter(external => external.dirty).length;\n config.log.debug(\n 3,\n `[${scope}] re-electing ${plan.pools.size} pool(s): ${dirty} dirty external(s).`\n );\n }\n if (plan.stripped.size > 0)\n config.log.debug(\n 3,\n `[${scope}] ${plan.stripped.size} external(s) left every pool; cleared their pool state for re-election.`\n );\n for (const name of plan.labelledAlone)\n config.log.debug(\n 3,\n `[${scope}] '${name}' has a 'pool' label that joins no other external; likely a typo or a missing sibling.`\n );\n }\n\n function poolRecords(\n poolName: PoolName,\n members: PoolMember[],\n packageOf: PackageOf,\n scope: string\n ): [ExternalName, SharedExternal][] {\n const election = elect({\n members,\n packageOf,\n acceptsTag: createAcceptsTag(ports.versionCheck.isCompatible, compare),\n compare,\n previousWinner: previousWinner(members),\n latestFirst: config.profile.latestSharedExternal,\n });\n const placed: PlacedPool = { ...election, poolName };\n report(poolName, members, placed, scope);\n return members.map(m => [\n m.name,\n { ...memberRecord(m, placed, compare), poolWinner: placed.winner },\n ]);\n }\n\n function report(\n poolName: PoolName,\n members: PoolMember[],\n placed: PlacedPool,\n scope: string\n ): void {\n const { misses } = placed;\n // A range rejecting the elected build is what this flag refuses; a coverage miss never is.\n const rejecting = [...misses]\n .filter(([, miss]) => miss?.cause === 'incompatible' && miss.strict)\n .map(([remote]) => remote);\n if (config.strict.strictExternalCompatibility && rejecting.length > 0) {\n config.log.error(\n 3,\n `[${scope}][pool:${poolName}] version-incompatible remotes cannot be pooled: {${rejecting.join(', ')}}.`\n );\n throw new NFError(`Could not pool '${poolName}' in scope ${scope}.`);\n }\n\n const subpoolSizes = new Map<RemoteName, number>();\n for (const placement of placed.placements.values())\n if (placement.kind === 'subpool')\n subpoolSizes.set(placement.owner, (subpoolSizes.get(placement.owner) ?? 0) + 1);\n let shipped: Map<RemoteName, Copy[]> | undefined;\n for (const [remote, miss] of misses) {\n if (miss === undefined) {\n config.log.warn(\n 3,\n `[${scope}][pool:${poolName}] '${remote}' keeps subpool '${remote}': the elected build would serve it, but ${subpoolSizes.get(remote)! - 1} other remote(s) in it need its build.`\n );\n continue;\n }\n shipped ??= copiesByRemote(members);\n const counts = {\n imports: specifierCount(shipped.get(remote)!),\n subpoolSize: subpoolSizes.get(remote) ?? 0,\n };\n config.log.warn(\n 3,\n `[${scope}][pool:${poolName}] ${missWarning(remote, miss, placed, counts)}`\n );\n }\n }\n}\n\nfunction missWarning(\n remote: RemoteName,\n miss: PoolMiss,\n placed: PlacedPool,\n counts: { imports: number; subpoolSize: number }\n): string {\n // Wording is pinned in `island-warnings.contract.spec.ts` alone; tools read islands from the record.\n const { imports, subpoolSize } = counts;\n const placement = placed.placements.get(remote)!;\n const where =\n placement.kind === 'subpool' && placement.owner !== remote\n ? `It runs in subpool '${placement.owner}' for all ${imports} of its entrypoints.`\n : subpoolSize > 1\n ? `Its build serves subpool '${remote}': its ${imports} entrypoints and ${subpoolSize - 1} other remote(s).`\n : `All ${imports} of its entrypoints are scoped for it.`;\n\n if (miss.cause === 'incompatible')\n return `'${remote}' is islanded: its range rejects '${miss.member}@${miss.tag}' of the elected build '${placed.winner}'. ${where}`;\n if (miss.unshipped)\n return `'${remote}' serves its own family: no build shipped its entrypoints together at the elected versions (gap '${miss.gap}', closest '${placed.winner}'). ${where}`;\n return `'${remote}' serves its own family: no elected build offers every entrypoint it imports at a version it accepts (gap '${miss.gap}', closest '${placed.winner}'). ${where}`;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport type { RemoteName } from '../remote/remote-info.contract';\nimport type { AcceptsTag } from './compatibility';\nimport type { ExternalName, SharedExternal, shareScope } from './external.contract';\nimport { mergeRows, redirectRow, rowAt, scopeRemotes } from './rows';\nimport { groupByPackage, packageOfIn, type Specifier } from './specifier';\nimport type { SharedVersion, SharedVersionMeta, VersionName } from './version.contract';\n\nexport type ServingBuild = { remote: RemoteName; tag: VersionName };\n\nexport type ServingCandidate = ServingBuild & {\n host: boolean;\n downloads: number;\n fallbacks: number;\n rootBasis: boolean;\n};\n\nexport type PackageExternals = readonly (readonly [ExternalName, DeepReadonly<SharedExternal>])[];\ntype Row = DeepReadonly<SharedVersion>;\ntype Placed = { row: Row; copy: DeepReadonly<SharedVersionMeta> };\n\nexport const byServingRank = (a: ServingCandidate, b: ServingCandidate): number =>\n Number(b.host) - Number(a.host) ||\n a.downloads - b.downloads ||\n a.fallbacks - b.fallbacks ||\n Number(b.rootBasis) - Number(a.rootBasis) ||\n compareStrings(a.remote, b.remote);\n\nexport const packagesOf = (scope: DeepReadonly<shareScope>): Map<ExternalName, ExternalName[]> =>\n groupByPackage(Object.keys(scope), name => name, packageOfIn(scope));\n\nexport const isPooled = (externals: PackageExternals): boolean =>\n externals.some(([, e]) => e.poolName !== undefined);\n\n// `externals` are package `pkg`'s, in record order. A share row of the root fixes the tag its secondaries follow.\nexport function servingBuildOf(\n pkg: ExternalName,\n externals: PackageExternals,\n accepts: AcceptsTag\n): ServingBuild | undefined {\n if (externals.length === 0) return undefined;\n // A dense build names the record of secondaries it does not declare by npm name, without shipping that root.\n const rootRows = shareRows(externals.find(([name]) => name === pkg)?.[1]).filter(row =>\n row.remotes.some(copy => pkg in copy.entries)\n );\n const rows = rootRows.length > 0 ? rootRows : externals.flatMap(([, e]) => shareRows(e));\n\n // The election already chose the global build; ranking again per package could split a pool.\n if (isPooled(externals)) return pooledBuild(externals, rows);\n\n const consumers = consumersOf(externals);\n const builds = buildsOf(rows, rootRows, consumers);\n // A host build outranks every other at any cost: only two or more of the builds left need pricing.\n const hosts = builds.filter(b => b.host);\n const field = hosts.length > 0 ? hosts : builds;\n if (field.length <= 1) return field[0] && { remote: field[0].remote, tag: field[0].tag };\n return cheapestBuild(field, costTable(consumers, accepts));\n}\n\nfunction cheapestBuild(\n field: UnpricedBuild[],\n costOf: (build: ServingBuild) => Cost\n): ServingBuild {\n let best: ServingCandidate | undefined;\n for (const b of field) {\n const { downloads, fallbacks } = costOf(b);\n const candidate: ServingCandidate = {\n remote: b.remote,\n tag: b.tag,\n host: b.host,\n rootBasis: b.rootBasis,\n downloads,\n fallbacks,\n };\n if (!best || byServingRank(candidate, best) < 0) best = candidate;\n }\n const { remote, tag } = best!;\n return { remote, tag };\n}\n\n// The serving build's copies publish even where that external's own election skipped them, so every specifier\n// the build ships stays in its surface. Mutates `external` in place.\nexport function shareServingCopies(external: SharedExternal, serving: ServingBuild): void {\n for (const row of external.versions) {\n const copy = row.remotes.find(c => c.name === serving.remote);\n if (row.action !== 'skip' || !copy || rowAt(external.versions, row.tag, 'share')) continue;\n row.action = 'share';\n // A host leading the row stops being its basis.\n if (row.remotes[0] !== copy) row.host = false;\n row.remotes = [copy, ...row.remotes.filter(c => c !== copy)];\n }\n}\n\nexport type ServingObjector = { copy: SharedVersionMeta; tag: VersionName };\n\n// Every share row at another tag follows the serving build the way a version follows its winner. Mutates\n// `external` in place; `objector` is the first strict copy that keeps its own build instead.\nexport function followServingBuild(\n external: SharedExternal,\n serving: ServingBuild,\n accepts: AcceptsTag\n): { external: SharedExternal; objector?: ServingObjector } {\n let objector: ServingObjector | undefined;\n const rebuilt = external.versions.flatMap(version => {\n if (\n version.action !== 'share' ||\n version.tag === serving.tag ||\n version.remotes[0]!.name === serving.remote\n )\n return [version];\n const rows = redirectRow(version, serving.tag, accepts);\n // A share row redirects into a `scope` row only of copies that reject the tag strictly.\n const scoped = rows.find(row => row.action === 'scope');\n if (scoped && !objector) objector = { copy: scoped.remotes[0]!, tag: scoped.tag };\n return rows;\n });\n external.versions = mergeRows(rebuilt);\n return { external, objector };\n}\n\n// A strict copy's range is its own tag, and a tag scope holds that tag only.\nconst sameTagOnly: AcceptsTag = (offered, ownTag) => offered === ownTag;\n\n// The strict scope shares every tag side by side, so each package at each tag is served on its own.\nexport const servedScopes = (scope: shareScope, strict: boolean): shareScope[] =>\n strict ? strictTagScopes(scope) : [scope];\n\n// See docs/version-resolver.md \u00A7\"Entrypoint coverage and tearing\". Rows are cloned, but each remote's copy in them is\n// the record's own, so the map's `cached` marks reach storage.\nfunction strictTagScopes(scope: shareScope): shareScope[] {\n const tagScopes: shareScope[] = [];\n for (const [pkg, names] of packagesOf(scope)) {\n const byTag = new Map<VersionName, shareScope>();\n for (const name of names)\n for (const row of scope[name]!.versions) {\n let tagScope = byTag.get(row.tag);\n if (!tagScope) byTag.set(row.tag, (tagScope = {}));\n const external = (tagScope[name] ??= { ...scope[name]!, versions: [] });\n external.versions.push({ ...row, remotes: [...row.remotes] });\n }\n for (const [tag, tagScope] of byTag) {\n // A record stored before determine skipped the strict scope can hold a skip row here, whose copy publishes\n // nothing.\n const lead = [tagScope[pkg], ...Object.values(tagScope)]\n .map(external => external && rowAt(external.versions, tag, 'share'))\n .find(row => row !== undefined);\n if (lead) {\n const serving = { remote: lead.remotes[0]!.name, tag };\n for (const external of Object.values(tagScope)) external.servingBuild = serving.remote;\n scopeFallbacks(Object.entries(tagScope), serving, sameTagOnly);\n }\n tagScopes.push(tagScope);\n }\n }\n return tagScopes;\n}\n\nfunction shareRows(external: DeepReadonly<SharedExternal> | undefined): Row[] {\n return external?.versions.filter(v => v.action === 'share') ?? [];\n}\n\n// Keyed by tag and remote rather than the first row per remote, so record order never decides.\nfunction buildsOf(\n rows: Row[],\n rootRows: Row[],\n consumers: Map<RemoteName, Placed[]>\n): UnpricedBuild[] {\n const candidates = new Map<string, UnpricedBuild>();\n for (const row of rows)\n for (const copy of row.remotes) {\n const key = `${row.tag}|${copy.name}`;\n if (copy.servedBy || candidates.has(key) || shipsTwoTags(consumers.get(copy.name)!)) continue;\n const basis = copy === row.remotes[0];\n candidates.set(key, {\n remote: copy.name,\n tag: row.tag,\n host: basis && row.host,\n rootBasis: basis && rootRows.includes(row),\n });\n }\n return [...candidates.values()];\n}\n\n// The pool's winner, where it ships the root (or, without one, any of the package); otherwise the widest copy:\n// every share-row copy lies within the one the election published, so the widest ships exactly it.\nfunction pooledBuild(externals: PackageExternals, rows: Row[]): ServingBuild | undefined {\n const winner = externals.find(([, e]) => e.poolWinner !== undefined)?.[1].poolWinner;\n const shipped = rows.flatMap(row =>\n row.remotes.filter(copy => !copy.servedBy).map(copy => ({ remote: copy.name, tag: row.tag }))\n );\n const own = shipped.find(c => c.remote === winner);\n if (own) return own;\n const width = ({ remote, tag }: ServingBuild) =>\n externals.reduce((n, [, e]) => {\n const copy = shareRows(e)\n .find(row => row.tag === tag)\n ?.remotes.find(c => c.name === remote);\n return n + Object.keys(copy?.entries ?? {}).length;\n }, 0);\n return shipped\n .map(c => ({ c, width: width(c) }))\n .sort((a, b) => b.width - a.width || compareStrings(a.c.remote, b.c.remote))[0]?.c;\n}\n\nexport function consumersOf(externals: PackageExternals): Map<RemoteName, Placed[]> {\n const consumers = new Map<RemoteName, Placed[]>();\n for (const [, external] of externals)\n for (const row of external.versions)\n for (const copy of row.remotes) {\n const placed = consumers.get(copy.name);\n if (placed) placed.push({ row, copy });\n else consumers.set(copy.name, [{ row, copy }]);\n }\n return consumers;\n}\n\ntype Cost = Pick<ServingCandidate, 'downloads' | 'fallbacks'>;\ntype UnpricedBuild = Omit<ServingCandidate, keyof Cost>;\n// The remotes that fall back and those that download their own build; a cached copy costs nothing.\ntype Toll = { fallbacks: Set<RemoteName>; downloads: Set<RemoteName> };\n\n// Builds at one tag that ship the same specifiers there cost the same but for their own remote, so each such\n// surface is tolled once.\nexport function costTable(\n consumers: Map<RemoteName, Placed[]>,\n accepts: AcceptsTag\n): (build: ServingBuild) => Cost {\n const scanned = new Map<VersionName, { surface: Surface; toll: Toll }[]>();\n const keyed = new Map<string, Toll>();\n const tollFor = (build: ServingBuild, surface: Surface): Toll => {\n let atTag = scanned.get(build.tag);\n if (!atTag) scanned.set(build.tag, (atTag = []));\n const known = atTag.find(t => sameSurface(t.surface, surface));\n if (known) return known.toll;\n if (atTag.length < SCANNED_SURFACES_PER_TAG) {\n const toll = tollOf(consumers, surface, build.tag, accepts);\n atTag.push({ surface, toll });\n return toll;\n }\n const key = [build.tag, ...[...surface].map(([s, tag]) => `${s}@${tag}`).sort()].join('\\n');\n let toll = keyed.get(key);\n if (!toll) keyed.set(key, (toll = tollOf(consumers, surface, build.tag, accepts)));\n return toll;\n };\n return build => {\n const surface = surfaceOf(consumers, build);\n const toll = tollFor(build, surface);\n const others = (remotes: Set<RemoteName>) => remotes.size - Number(remotes.has(build.remote));\n // The serving remote never falls back, and downloads its own build unless cached.\n return {\n downloads: others(toll.downloads) + Number(!allCached(consumers.get(build.remote) ?? [])),\n fallbacks: others(toll.fallbacks),\n };\n };\n}\n\nfunction tollOf(\n consumers: Map<RemoteName, Placed[]>,\n surface: Surface,\n tag: VersionName,\n accepts: AcceptsTag\n): Toll {\n const toll: Toll = { fallbacks: new Set(), downloads: new Set() };\n for (const [remote, placed] of consumers) {\n const fallback = fallsBack(placed, surface, tag, accepts);\n if (fallback) toll.fallbacks.add(remote);\n if (!allCached(placed) && (fallback || runsOffMap(placed, tag, accepts)))\n toll.downloads.add(remote);\n }\n return toll;\n}\n\nconst allCached = (placed: Placed[]): boolean => placed.every(({ copy }) => copy.cached);\n\n// The remotes that run part of the package off the map and part on it, ship a specifier outside the copies the\n// serving build publishes, or ship the package at two tags; without a serving build, every remote with a copy on\n// the map. Each serves the whole package from its own build instead, so none of its files imports another build's.\nexport function fallbacksOf(\n externals: PackageExternals,\n serving: ServingBuild | undefined,\n accepts: AcceptsTag\n): RemoteName[] {\n const consumers = consumersOf(externals);\n const surface: Surface = serving ? surfaceOf(consumers, serving) : new Map();\n return [...consumers]\n .filter(\n ([remote, placed]) =>\n remote !== serving?.remote && fallsBack(placed, surface, serving?.tag, accepts)\n )\n .map(([remote]) => remote);\n}\n\nexport function scopeFallbacks(\n externals: readonly (readonly [ExternalName, SharedExternal])[],\n serving: ServingBuild | undefined,\n accepts: AcceptsTag\n): void {\n const remotes = fallbacksOf(externals, serving, accepts);\n for (const [, external] of externals)\n external.versions = scopeRemotes(external.versions, remotes);\n}\n\n// The first copy, in record order, that `rejectsServingTag` while its remote's coverage alone (`splitsPackage`)\n// would keep it on the map: a remote its coverage already sends to its own build never refuses.\nexport function strictObjectorOf(\n externals: PackageExternals,\n serving: ServingBuild,\n accepts: AcceptsTag\n): (ServingObjector & { external: ExternalName }) | undefined {\n const consumers = consumersOf(externals);\n const surface = surfaceOf(consumers, serving);\n for (const [name, external] of externals)\n for (const row of external.versions)\n for (const copy of row.remotes)\n if (\n copy.name !== serving.remote &&\n rejectsServingTag({ row, copy }, surface, serving.tag, accepts) &&\n !splitsPackage(consumers.get(copy.name)!, surface, serving.tag, accepts)\n )\n return { external: name, copy, tag: row.tag };\n return undefined;\n}\n\n// Each specifier the serving build publishes, at the tag of the row it publishes it from.\ntype Surface = Map<Specifier, VersionName>;\n\n// Up to here a scan beats building the sorted key; a surface past it is looked up by that key after the scan.\nexport const SCANNED_SURFACES_PER_TAG = 8;\n\nfunction sameSurface(a: Surface, b: Surface): boolean {\n if (a.size !== b.size) return false;\n for (const [specifier, tag] of a) if (b.get(specifier) !== tag) return false;\n return true;\n}\n\nfunction surfaceOf(consumers: Map<RemoteName, Placed[]>, serving: ServingBuild): Surface {\n const surface: Surface = new Map();\n for (const p of consumers.get(serving.remote) ?? [])\n if ((p.row.tag === serving.tag && onMap(p)) || leadsShareRow(p))\n for (const s in p.copy.entries) if (!surface.has(s)) surface.set(s, p.row.tag);\n return surface;\n}\n\n// followServingBuild leaves these rows shared, so a host's copies at its other tags publish too.\nconst leadsShareRow = ({ row, copy }: Placed): boolean =>\n row.action === 'share' && row.remotes[0] === copy;\n\nconst onMap = ({ row }: Placed): boolean => row.action !== 'scope';\n\n// A remote with no copy on the map already runs the package wholly from its own build.\nfunction splitsPackage(\n placed: Placed[],\n surface: Surface,\n tag: VersionName | undefined,\n accepts: AcceptsTag\n): boolean {\n const uncovered = (p: Placed) =>\n Object.keys(p.copy.entries).some(s => {\n const servedAt = surface.get(s);\n // A strict copy takes a host's file at another tag only where its range accepts it; the serving tag is\n // `rejectsServingTag`'s to judge.\n return servedAt === undefined || (servedAt !== tag && rejectsTag(p, servedAt, accepts));\n });\n return (\n placed.some(onMap) && (shipsTwoTags(placed) || placed.some(p => !onMap(p) || uncovered(p)))\n );\n}\n\n// Whether a runtime load's copies split the package over the claims the committed map serves of it, as\n// `splitsPackage` judges a remote at init.\nexport function loadSplitsPackage(\n pkg: ExternalName,\n copies: readonly { tag: VersionName; copy: SharedVersionMeta }[],\n claims: readonly (readonly [Specifier, { tag: VersionName }])[],\n accepts: AcceptsTag\n): boolean {\n const root = claims.find(([specifier]) => specifier === pkg)?.[1];\n // Without a root claim the serving tag is unknown: every claim counts as at it, so only a gap or two tags\n // split.\n const servingTag = root?.tag ?? claims[0]![1].tag;\n const surface: Surface = new Map(\n claims.map(([specifier, { tag }]) => [specifier, root ? tag : servingTag])\n );\n // Each loaded copy as the share row it would join; a loader is never the host.\n const placed: Placed[] = copies.map(({ tag, copy }) => ({\n row: { tag, action: 'share', host: false, remotes: [copy] },\n copy,\n }));\n return splitsPackage(placed, surface, servingTag, accepts);\n}\n\nfunction fallsBack(\n placed: Placed[],\n surface: Surface,\n tag: VersionName | undefined,\n accepts: AcceptsTag\n): boolean {\n return (\n splitsPackage(placed, surface, tag, accepts) ||\n (tag !== undefined && placed.some(p => rejectsServingTag(p, surface, tag, accepts)))\n );\n}\n\n// A strict copy on the map whose range rejects the serving tag, where the serving build publishes one of its\n// files. A scoped copy already runs its own build, so it never objects.\nfunction rejectsServingTag(\n p: Placed,\n surface: Surface,\n tag: VersionName,\n accepts: AcceptsTag\n): boolean {\n return (\n onMap(p) &&\n rejectsTag(p, tag, accepts) &&\n Object.keys(p.copy.entries).some(s => surface.get(s) === tag)\n );\n}\n\nconst rejectsTag = ({ row, copy }: Placed, tag: VersionName, accepts: AcceptsTag): boolean =>\n copy.strictVersion && !accepts(tag, row.tag, copy.requiredVersion);\n\n// The host serves every tag it ships; any other remote shipping two tags has no one build to serve or follow.\nconst shipsTwoTags = (placed: Placed[]): boolean =>\n !placed.some(p => p.row.host && p.row.remotes[0] === p.copy) &&\n placed.some(p => p.row.tag !== placed[0]!.row.tag);\n\nfunction runsOffMap(placed: Placed[], tag: VersionName, accepts: AcceptsTag): boolean {\n return placed.some(p => !onMap(p) || rejectsTag(p, tag, accepts));\n}\n", "import type { ForDecidingServingBuilds } from '../driver-ports/init/for-deciding-serving-builds.port';\nimport type { ExternalName, RemoteName, SharedExternal, SharedVersion } from 'lib/core/1.domain';\nimport { type AcceptsTag, createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport {\n followServingBuild,\n isPooled,\n packagesOf,\n scopeFallbacks,\n servingBuildOf,\n shareServingCopies,\n strictObjectorOf,\n type ServingBuild,\n} from 'lib/core/1.domain/externals/serving';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport { rejectIncompatible } from './apply-winner';\n\ntype StoredPackage = (readonly [ExternalName, SharedExternal])[];\n\n// See docs/version-resolver.md \u00A7\"One build per package\".\nexport function createDecideServingBuilds(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'versionCheck' | 'sharedExternalsRepo'>\n): ForDecidingServingBuilds {\n return () => {\n const accepts = createAcceptsTag(ports.versionCheck.isCompatible, ports.versionCheck.compare);\n const repo = ports.sharedExternalsRepo;\n // Taken before deciding writes. A scope nothing wrote since its last decide would decide the same again.\n const written = new Set(repo.uncommittedScopes());\n const needsDeciding = (shareScope: string) =>\n written.has(shareScope) || repo.isUndecided(shareScope);\n\n try {\n for (const shareScope of repo.getScopes()) {\n if (repo.scopeType(shareScope) === 'strict' || !needsDeciding(shareScope)) continue;\n const sharedExternals = repo.getFromScope(shareScope);\n for (const [pkg, names] of packagesOf(sharedExternals)) {\n const externals = names.map(name => [name, sharedExternals[name]!] as const);\n decidePackage(shareScope, pkg, externals, accepts);\n }\n repo.markDecided(shareScope);\n }\n return Promise.resolve();\n } catch (e) {\n return Promise.reject(e);\n }\n };\n\n function decidePackage(\n shareScope: string,\n pkg: ExternalName,\n externals: StoredPackage,\n accepts: AcceptsTag\n ): void {\n const serving = servingBuildOf(pkg, externals, accepts);\n // Taken before falling back and following rewrite the stored externals in place.\n const before = externals.map(([, external]) => shapeOf(external));\n // The election already placed a pooled package's rows.\n const pooled = isPooled(externals);\n const toFollow = pooled ? undefined : serving;\n if (!pooled) fallBack(pkg, externals, accepts, serving);\n\n externals.forEach(([name, external], i) => {\n const decided = withServingBuild(\n toFollow ? follow(pkg, name, external, toFollow, accepts) : external,\n serving?.remote\n );\n if (!sameShape(before[i]!, decided))\n ports.sharedExternalsRepo.addOrUpdate(name, decided, shareScope);\n });\n }\n\n function follow(\n pkg: ExternalName,\n name: ExternalName,\n external: SharedExternal,\n serving: ServingBuild,\n accepts: AcceptsTag\n ): SharedExternal {\n const { external: followed, objector } = followServingBuild(external, serving, accepts);\n if (objector && config.strict.strictExternalCompatibility)\n rejectIncompatible(config, objector.copy, `${name}@${objector.tag}`, `${pkg}@${serving.tag}`);\n return followed;\n }\n\n // The serving copy publishes first, so a remote it covers stays; one it does not runs the package from its own\n // build.\n function fallBack(\n pkg: ExternalName,\n externals: StoredPackage,\n accepts: AcceptsTag,\n serving?: ServingBuild\n ): void {\n if (serving) {\n for (const [, external] of externals) shareServingCopies(external, serving);\n const objector =\n config.strict.strictExternalCompatibility && strictObjectorOf(externals, serving, accepts);\n if (objector)\n rejectIncompatible(\n config,\n objector.copy,\n `${objector.external}@${objector.tag}`,\n `${pkg}@${serving.tag}`\n );\n }\n scopeFallbacks(externals, serving, accepts);\n }\n}\n\nfunction withServingBuild(external: SharedExternal, servingBuild?: RemoteName): SharedExternal {\n if (external.servingBuild === servingBuild) return external;\n const { servingBuild: _, ...rest } = external;\n return servingBuild ? { ...rest, servingBuild } : rest;\n}\n\n// What deciding can change: the serving build, and every field of each row. The helpers reorder, move and merge\n// copies but never edit one, so copies compare by identity.\ntype Shape = { servingBuild?: RemoteName; rows: SharedVersion[] };\n\nconst shapeOf = (external: SharedExternal): Shape => ({\n servingBuild: external.servingBuild,\n rows: external.versions.map(\n ({ tag, action, host, remotes }) =>\n ({ tag, action, host, remotes: [...remotes] }) satisfies Required<SharedVersion>\n ),\n});\n\nconst sameRow = (was: SharedVersion, row: SharedVersion): boolean =>\n (Object.keys(was) as (keyof SharedVersion)[]).every(key =>\n key === 'remotes'\n ? was.remotes.length === row.remotes.length &&\n row.remotes.every((copy, j) => copy === was.remotes[j])\n : was[key] === row[key]\n );\n\nconst sameShape = (shape: Shape, external: SharedExternal): boolean =>\n shape.servingBuild === external.servingBuild &&\n shape.rows.length === external.versions.length &&\n external.versions.every((row, i) => sameRow(shape.rows[i]!, row));\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type { RemoteName } from '../remote/remote-info.contract';\nimport { type ExternalName, GLOBAL_SCOPE, type SharedExternal } from './external.contract';\nimport type { SharedVersion, SharedVersionMeta, VersionName } from './version.contract';\nimport type { Specifier } from './specifier';\nimport { forEachVersionEntry } from './basis';\n\nexport type Claim = {\n external: ExternalName;\n tag: VersionName;\n copy: SharedVersionMeta;\n};\n\nexport type ClaimTable = {\n // What `imports` serves: an external with a serving build claims that build's copy alone, one without claims its\n // share rows in record order; the first claim per specifier wins. A skip copy claims nothing.\n claims: Map<Specifier, Claim>;\n // Share rows reached after their external's name was claimed at another tag. A row whose name another row\n // claimed claims nothing, duplicate or not.\n duplicates: Set<DeepReadonly<SharedVersion>>;\n // What a named scope serves: the same rule over every share row, duplicates included.\n shareClaims: Map<Specifier, Claim>;\n};\n\nexport function claimTable(\n externals: Iterable<readonly [ExternalName, DeepReadonly<SharedExternal>]>,\n publishes?: (copy: SharedVersionMeta) => boolean\n): ClaimTable {\n const table: ClaimTable = { claims: new Map(), duplicates: new Set(), shareClaims: new Map() };\n const ordered = [...externals];\n\n const claim = (\n into: Map<Specifier, Claim>,\n external: ExternalName,\n version: DeepReadonly<SharedVersion>,\n accepts = publishes\n ) =>\n forEachVersionEntry(version, accepts, (specifier, copy) => {\n if (!into.has(specifier)) into.set(specifier, { external, tag: version.tag, copy });\n });\n\n const seedServingBuild = (name: ExternalName, external: DeepReadonly<SharedExternal>) => {\n const isServing = (copy: SharedVersionMeta) =>\n copy.name === external.servingBuild && (!publishes || publishes(copy));\n for (const version of external.versions) {\n if (version.action !== 'share') continue;\n claim(table.shareClaims, name, version, isServing);\n claim(table.claims, name, version, isServing);\n }\n };\n\n const claimShareRow = (\n name: ExternalName,\n external: DeepReadonly<SharedExternal>,\n version: DeepReadonly<SharedVersion>\n ) => {\n const prior = table.claims.get(name);\n const duplicate = prior !== undefined && prior.tag !== version.tag;\n // A row the serving host leads is never a duplicate: it ships that tag beside the one claimed first.\n if (duplicate && !(version.host && version.remotes[0]!.name === external.servingBuild))\n table.duplicates.add(version);\n // The seed already claimed an external with a serving build.\n if (external.servingBuild) return;\n claim(table.shareClaims, name, version);\n if (!duplicate && (!prior || prior.external === name)) claim(table.claims, name, version);\n };\n\n for (const [name, external] of ordered)\n if (external.servingBuild) seedServingBuild(name, external);\n for (const [name, external] of ordered)\n for (const version of external.versions)\n if (version.action === 'share') claimShareRow(name, external, version);\n\n return table;\n}\n\n// What a committed map serves in one scope, from externals in record order: `imports` holds only the copies\n// marked cached, a named scope's override may name any copy. `without` is a loaded remote whose copies the\n// record already holds but the committed map does not.\nexport function committedClaims(\n externals: Iterable<readonly [ExternalName, DeepReadonly<SharedExternal>]>,\n { shareScope, without }: { shareScope: string; without?: RemoteName }\n): Map<Specifier, Claim> {\n const publishes = (copy: SharedVersionMeta) =>\n copy.name !== without && (shareScope !== GLOBAL_SCOPE || copy.cached);\n return claimTable(externals, publishes).claims;\n}\n\n// One version's claims as `claimTable` makes them: the serving copy alone when there is one, else every copy in\n// record order.\nexport function versionClaims(\n version: DeepReadonly<SharedVersion>,\n servingBuild: RemoteName | undefined\n): Map<Specifier, SharedVersionMeta> {\n const claims = new Map<Specifier, SharedVersionMeta>();\n const claim = (specifier: Specifier, copy: SharedVersionMeta) => {\n if (!claims.has(specifier)) claims.set(specifier, copy);\n };\n const accepts = servingBuild\n ? (copy: SharedVersionMeta) => copy.name === servingBuild\n : undefined;\n forEachVersionEntry(version, accepts, claim);\n return claims;\n}\n", "import type { ForGeneratingImportMap } from '../driver-ports/init/for-generating-import-map';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ImportMap, Imports } from 'lib/core/1.domain/import-map/import-map.contract';\nimport {\n GLOBAL_SCOPE,\n type RemoteName,\n type ScopedExternal,\n type RemoteInfo,\n type SharedExternal,\n type SharedVersion,\n type SharedVersionMeta,\n} from 'lib/core/1.domain';\nimport { forEachVersionEntry } from 'lib/core/1.domain/externals/basis';\nimport { claimTable, versionClaims, type Claim } from 'lib/core/1.domain/externals/claims';\nimport { servedScopes } from 'lib/core/1.domain/externals/serving';\nimport type { Specifier } from 'lib/core/1.domain/externals/specifier';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport * as _path from 'lib/utils/path';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { toChunkImport } from '@softarc/native-federation/domain';\n\nexport function createGenerateImportMap(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedChunksRepo' | 'sharedExternalsRepo'\n >\n): ForGeneratingImportMap {\n /**\n * Step 4: Generate an importMap from the cached remoteEntries\n *\n * The processed externals in the storage/cache (step 2 & 3) are used\n * to generate an importMap. The step returns the generated importMap object.\n */\n return () => {\n const importMap: ImportMap = { imports: {} };\n const chunkBundles: Record<string, Set<string>> = {};\n try {\n addScopedExternals(importMap, chunkBundles);\n addNamedShareScopes(importMap, chunkBundles);\n addGlobalShareScope(importMap, chunkBundles);\n addRemoteInfos(importMap, chunkBundles);\n\n addChunkImports(importMap, chunkBundles);\n\n return Promise.resolve(importMap);\n } catch (e) {\n return Promise.reject(e);\n }\n };\n\n /**\n * Step 4.1: Begin with appending smallest scope of shared dependencies\n * @param importMap\n * @returns\n */\n function addScopedExternals(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>\n ): ImportMap {\n const scopedExternals = ports.scopedExternalsRepo.getAll();\n\n for (const [remoteName, externals] of Object.entries(scopedExternals)) {\n const remote = ports.remoteInfoRepo.tryGet(remoteName).orThrow(() => {\n config.log.error(4, `[scoped][${remoteName}] Remote name not found in cache.`);\n return new NFError('Could not create ImportMap.');\n });\n addToScope(importMap, remote.scopeUrl, createScopeModules(externals, remote.scopeUrl));\n\n for (const version of Object.values(externals)) {\n for (const file of Object.values(version.entries)) {\n addIntegrity(importMap, _path.join(remote.scopeUrl, file), remoteName, file);\n }\n }\n\n Object.values(externals)\n .filter(e => !!e.bundle)\n .forEach(e => registerBundleChunks(chunkBundles, remoteName, e.bundle));\n }\n\n return importMap;\n }\n\n function createScopeModules(externals: ScopedExternal, scope: string): Imports {\n const modules: Imports = {};\n\n for (const version of Object.values(externals)) {\n for (const [packageName, file] of Object.entries(version.entries)) {\n modules[packageName] = _path.join(scope, file);\n }\n }\n\n return modules;\n }\n\n // Runs after the scoped externals, so a remote's shared mappings overwrite its scoped ones in its scope.\n function addNamedShareScopes(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>\n ): ImportMap {\n const shareScopes = ports.sharedExternalsRepo.getScopes({ includeGlobal: false });\n\n for (const shareScope of shareScopes) {\n const sharedExternals = ports.sharedExternalsRepo.getFromScope(shareScope);\n const cachedBefore = new Map<string, string>();\n for (const [externalName, external] of Object.entries(sharedExternals))\n cachedBefore.set(externalName, cachedFingerprint(external));\n\n const strict = ports.sharedExternalsRepo.scopeType(shareScope) === 'strict';\n for (const served of servedScopes(sharedExternals, strict))\n addShareScope(importMap, shareScope, served, chunkBundles);\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n if (cachedFingerprint(external) !== cachedBefore.get(externalName)) {\n ports.sharedExternalsRepo.addOrUpdate(externalName, external, shareScope);\n }\n }\n }\n\n return importMap;\n }\n\n function addShareScope(\n importMap: ImportMap,\n shareScope: string,\n sharedExternals: Record<string, SharedExternal>,\n chunkBundles: Record<string, Set<string>>\n ): void {\n const index = buildServedIndex(sharedExternals);\n\n const claims = shareRowMappings(sharedExternals, shareScope);\n const claimedElsewhere = (externalName: string, specifier: string): Mapping | undefined => {\n const claim = claims.get(specifier);\n return claim?.external === externalName ? undefined : claim;\n };\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n let override: SharedVersion | undefined | 'NOT_AVAILABLE' = undefined;\n\n for (const version of external.versions) {\n if (version.action === 'scope') {\n addScopeRow(importMap, chunkBundles, shareScope, externalName, version);\n continue;\n }\n\n // Serve every entrypoint from one version: this one, or the override version when a\n // 'skip' is redirected elsewhere.\n let serving = version;\n\n if (version.action === 'skip') {\n if (!override) {\n override =\n findOverride(external, shareScope, externalName, s =>\n Boolean(claimedElsewhere(externalName, s))\n ) ?? 'NOT_AVAILABLE';\n }\n if (override !== 'NOT_AVAILABLE') {\n serving = override;\n version.remotes[0]!.cached = false;\n }\n }\n\n const provided = versionClaims(serving, external.servingBuild);\n const mappings: (Mapping & { packageName: string })[] = [];\n\n for (const [packageName, provider] of provided) {\n // The claiming external maps, marks and registers that copy; this one only points at it.\n const claim = claimedElsewhere(externalName, packageName);\n if (claim) {\n mappings.push({ packageName, ...claim });\n continue;\n }\n const file = provider.entries[packageName]!;\n mappings.push({\n packageName,\n url: _path.join(getScope(shareScope, provider.name, externalName), file),\n name: provider.name,\n file,\n });\n provider.cached = true;\n if (version.action === 'share') {\n registerBundleChunks(chunkBundles, provider.name, provider.bundle);\n }\n }\n\n version.remotes.forEach(consumer => {\n const consumerScope = getScope(shareScope, consumer.name, externalName);\n // Pooling placed this remote in a subpool, so its scope names that subpool's build's files for\n // everything it imports rather than the shared source's.\n if (index && consumer.servedBy) {\n const files = index.get(consumer.servedBy);\n const servedScope = getScope(shareScope, consumer.servedBy, externalName);\n for (const specifier of Object.keys(consumer.entries)) {\n const source = files?.get(specifier);\n if (!source) continue;\n const url = _path.join(servedScope, source.file);\n addToScope(importMap, consumerScope, { [specifier]: url });\n addIntegrity(importMap, url, consumer.servedBy, source.file);\n registerBundleChunks(chunkBundles, consumer.servedBy, source.bundle);\n source.meta.cached = true;\n }\n return;\n }\n for (const m of mappings) {\n addToScope(importMap, consumerScope, { [m.packageName]: m.url });\n }\n for (const packageName of Object.keys(consumer.entries)) {\n if (provided.has(packageName)) continue;\n const claim = claimedElsewhere(externalName, packageName);\n if (claim) addToScope(importMap, consumerScope, { [packageName]: claim.url });\n }\n });\n for (const m of mappings) {\n addIntegrity(importMap, m.url, m.name, m.file);\n }\n }\n }\n }\n\n function addScopeRow(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>,\n shareScope: string,\n externalName: string,\n version: SharedVersion\n ): void {\n for (const remote of version.remotes) {\n const remoteScope = getScope(shareScope, remote.name, externalName);\n for (const [packageName, file] of Object.entries(remote.entries)) {\n const url = _path.join(remoteScope, file);\n addToScope(importMap, remoteScope, { [packageName]: url });\n addIntegrity(importMap, url, remote.name, file);\n }\n registerBundleChunks(chunkBundles, remote.name, remote.bundle);\n remote.cached = true;\n }\n }\n\n function cachedFingerprint(external: SharedExternal): string {\n return external.versions.map(v => v.remotes.map(r => (r.cached ? 1 : 0)).join('')).join('|');\n }\n\n // A skip-only external whose specifiers another external's shared version maps is served all the same.\n function findOverride(\n external: SharedExternal,\n shareScope: string,\n externalName: string,\n servedElsewhere: (specifier: string) => boolean\n ): SharedVersion | undefined {\n const sharedVersions = external.versions.filter(v => v.action === 'share');\n const scopedExternalName = `${shareScope}.${externalName}`;\n\n if (sharedVersions.length > 1) {\n handleMultipleSharedVersions(scopedExternalName);\n }\n\n const servedByClaims = () =>\n external.versions.filter(v => v.action === 'skip').every(v => shipsOnly(v, servedElsewhere));\n\n if (sharedVersions.length < 1 && !servedByClaims()) {\n if (config.strict.strictImportMap) {\n config.log.error(4, `[${shareScope}][${externalName}] shareScope has no override version.`);\n throw new NFError('Could not create ImportMap.');\n }\n config.log.debug(\n 4,\n `[${shareScope}][${externalName}] shareScope has no override version, scoping override versions.`\n );\n }\n\n return sharedVersions[0];\n }\n\n function handleMultipleSharedVersions(scopedExternalName: string): void {\n if (config.strict.strictImportMap) {\n config.log.error(\n 4,\n `[${scopedExternalName}] ShareScope external has multiple shared versions.`\n );\n throw new NFError('Could not create ImportMap.');\n }\n\n config.log.warn(4, `ShareScope external ${scopedExternalName} has multiple shared versions.`);\n }\n\n /**\n * Where a build serves a specifier from, per remote \u2014 built only when some copy carries a `servedBy`,\n * so an unpooled portfolio allocates nothing. Pool-wide rather than per-external on purpose: the\n * specifier a subpool member runs may be an *entry* of a different external of the serving build,\n * which is the whole reason coverage is keyed by specifier (see docs/version-resolver.md \u00A7\"How pooling\n * resolves\", \"Coverage is keyed by specifier\").\n */\n type ServedSource = { file: string; bundle?: string; meta: SharedVersionMeta };\n\n function buildServedIndex(\n externals: Record<string, SharedExternal>\n ): Map<RemoteName, Map<string, ServedSource>> | undefined {\n let anyServed = false;\n for (const external of Object.values(externals)) {\n for (const version of external.versions) {\n if (version.remotes.some(r => r.servedBy)) anyServed = true;\n }\n }\n if (!anyServed) return undefined;\n\n const index = new Map<RemoteName, Map<string, ServedSource>>();\n for (const external of Object.values(externals)) {\n for (const version of external.versions) {\n for (const remote of version.remotes) {\n let own = index.get(remote.name);\n if (!own) index.set(remote.name, (own = new Map()));\n for (const [specifier, file] of Object.entries(remote.entries)) {\n if (!own.has(specifier))\n own.set(specifier, { file, bundle: remote.bundle, meta: remote });\n }\n }\n }\n }\n return index;\n }\n\n type Mapping = { url: string; name: RemoteName; file: string };\n\n // A specifier can be an entry of one external and a package of its own in another (flat vs dense), and the\n // first shared version listing it serves every remote of the scope.\n function shareRowMappings(\n externals: Record<string, SharedExternal>,\n shareScope: string\n ): Map<Specifier, Mapping & { external: string }> {\n const mappings = new Map<Specifier, Mapping & { external: string }>();\n for (const [specifier, { external, copy }] of claimTable(Object.entries(externals))\n .shareClaims) {\n const file = copy.entries[specifier]!;\n mappings.set(specifier, {\n url: _path.join(getScope(shareScope, copy.name, external), file),\n name: copy.name,\n file,\n external,\n });\n }\n return mappings;\n }\n\n // A cross-build scope entry, held back until every global mapping is in place so that a scope which\n // would merely repeat `imports` can be dropped.\n type ServedScope = { scope: string; specifier: string; source: ServedSource; from: RemoteName };\n\n function collectServed(\n into: ServedScope[],\n index: Map<RemoteName, Map<string, ServedSource>>,\n shareScope: string,\n externalName: string,\n version: SharedVersion\n ): void {\n for (const consumer of version.remotes) {\n if (!consumer.servedBy) continue;\n const files = index.get(consumer.servedBy);\n const scope = getScope(shareScope, consumer.name, externalName);\n for (const specifier of Object.keys(consumer.entries)) {\n const source = files?.get(specifier);\n if (!source) {\n config.log.warn(\n 4,\n `[${shareScope}][${externalName}][${consumer.name}] '${consumer.servedBy}' does not serve '${specifier}'.`\n );\n continue;\n }\n into.push({ scope, specifier, source, from: consumer.servedBy });\n }\n }\n }\n\n function flushServed(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>,\n served: ServedScope[]\n ): void {\n for (const { scope, specifier, source, from } of served) {\n const url = _path.join(getScope(GLOBAL_SCOPE, from), source.file);\n if (importMap.imports[specifier] === url) continue;\n addToScope(importMap, scope, { [specifier]: url });\n addIntegrity(importMap, url, from, source.file);\n registerBundleChunks(chunkBundles, from, source.bundle);\n source.meta.cached = true;\n }\n }\n\n function addGlobalShareScope(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>\n ): ImportMap {\n const sharedExternals = ports.sharedExternalsRepo.getFromScope();\n const index = buildServedIndex(sharedExternals);\n const { claims, duplicates } = claimTable(Object.entries(sharedExternals));\n const claimed = claimsByCopy(claims);\n const served: ServedScope[] = [];\n const cachedBefore = new Map<string, string>();\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n cachedBefore.set(externalName, cachedFingerprint(external));\n\n for (const version of external.versions) {\n if (index && version.action !== 'scope') {\n collectServed(served, index, GLOBAL_SCOPE, externalName, version);\n }\n if (version.action === 'skip') continue;\n if (version.action === 'scope') {\n addScopeRow(importMap, chunkBundles, GLOBAL_SCOPE, externalName, version);\n continue;\n }\n\n if (duplicates.has(version)) {\n notifyDuplicateGlobalExternal(externalName);\n continue;\n }\n\n publishClaims(importMap, chunkBundles, externalName, version, claimed);\n }\n }\n\n flushServed(importMap, chunkBundles, served);\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n if (cachedFingerprint(external) !== cachedBefore.get(externalName)) {\n ports.sharedExternalsRepo.addOrUpdate(externalName, external);\n }\n }\n\n return importMap;\n }\n\n function claimsByCopy(claims: Map<Specifier, Claim>): Map<SharedVersionMeta, Specifier[]> {\n const claimed = new Map<SharedVersionMeta, Specifier[]>();\n for (const [specifier, { copy }] of claims) {\n const specifiers = claimed.get(copy);\n if (specifiers) specifiers.push(specifier);\n else claimed.set(copy, [specifier]);\n }\n return claimed;\n }\n\n // Marks and registers each copy that claims a specifier, so `cached` names the copies this map really\n // publishes, which the dynamic path reads as what it may call covered.\n function publishClaims(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>,\n externalName: string,\n version: SharedVersion,\n claimed: Map<SharedVersionMeta, Specifier[]>\n ): void {\n for (const copy of version.remotes) {\n const specifiers = claimed.get(copy);\n if (!specifiers) continue;\n const scope = getScope(GLOBAL_SCOPE, copy.name, externalName);\n registerBundleChunks(chunkBundles, copy.name, copy.bundle);\n copy.cached = true;\n for (const specifier of specifiers) {\n const file = copy.entries[specifier]!;\n const url = _path.join(scope, file);\n addToGlobal(importMap, { [specifier]: url });\n addIntegrity(importMap, url, copy.name, file);\n }\n }\n }\n\n function notifyDuplicateGlobalExternal(externalName: string): void {\n if (config.strict.strictImportMap) {\n config.log.error(4, `[${externalName}] Shared external has multiple shared versions.`);\n throw new NFError('Could not create ImportMap.');\n }\n\n config.log.warn(4, `Singleton external ${externalName} has multiple shared versions.`);\n }\n\n function addToScope(importMap: ImportMap, scope: string, imports: Imports): void {\n if (!importMap.scopes) importMap.scopes = {};\n if (!importMap.scopes[scope]) importMap.scopes[scope] = {};\n importMap.scopes[scope] = Object.assign(importMap.scopes[scope], imports);\n }\n function addToGlobal(importMap: ImportMap, imports: Imports): void {\n importMap.imports = Object.assign(importMap.imports, imports);\n }\n\n /**\n * Step 4.4: Added the remote-modules (into the global scope).\n * @param importMap\n * @returns\n */\n function addRemoteInfos(importMap: ImportMap, chunkBundles: Record<string, Set<string>>): void {\n const remotes = ports.remoteInfoRepo.getAll();\n\n for (const [remoteName, remote] of Object.entries(remotes)) {\n addRemoteExposedModules(importMap, remoteName, remote);\n registerBundleChunks(chunkBundles, remoteName, 'mapping-or-exposed');\n }\n }\n\n function addRemoteExposedModules(\n importMap: ImportMap,\n remoteName: string,\n remote: RemoteInfo\n ): void {\n for (const exposed of remote.exposes) {\n const moduleName = _path.join(remoteName, exposed.moduleName);\n const moduleUrl = _path.join(remote.scopeUrl, exposed.file);\n importMap.imports[moduleName] = moduleUrl;\n addIntegrity(importMap, moduleUrl, remoteName, exposed.file);\n }\n }\n\n function registerBundleChunks(\n chunkBundles: Record<string, Set<string>>,\n remoteName: string,\n bundleName?: string\n ) {\n if (!bundleName) return chunkBundles;\n if (!chunkBundles[remoteName]) chunkBundles[remoteName] = new Set();\n chunkBundles[remoteName].add(bundleName);\n return chunkBundles;\n }\n\n function addChunkImports(importMap: ImportMap, chunkBundles: Record<string, Set<string>>) {\n Object.entries(chunkBundles).forEach(([remoteName, bundles]) => {\n const baseUrl = getScope('CHUNKS', remoteName);\n\n const imports = Array.from(bundles).reduce((_imports, bundleName) => {\n ports.sharedChunksRepo.tryGet(remoteName, bundleName).ifPresent(files => {\n files.forEach(file => {\n const url = _path.join(baseUrl, file);\n _imports[toChunkImport(file)] = url;\n addIntegrity(importMap, url, remoteName, file);\n });\n });\n return _imports;\n }, {} as Imports);\n\n if (Object.keys(imports).length > 0) addToScope(importMap, baseUrl, imports);\n });\n\n return importMap;\n }\n\n function addIntegrity(\n importMap: ImportMap,\n url: string,\n remoteName: RemoteName,\n file: string\n ): void {\n const hash = ports.remoteInfoRepo.tryGet(remoteName).get()?.integrity?.[file];\n if (!hash) return;\n if (!importMap.integrity) importMap.integrity = {};\n importMap.integrity[url] = hash;\n }\n\n function getScope(ctx: string, remoteName: RemoteName, externalName?: string) {\n return ports.remoteInfoRepo\n .tryGet(remoteName)\n .map(remote => remote.scopeUrl)\n .orThrow(() => {\n if (externalName) {\n config.log.error(\n 4,\n `[${ctx}][${externalName}][${remoteName}] Remote name not found in cache.`\n );\n } else {\n config.log.error(4, `[${ctx}][${remoteName}] Remote name not found in cache.`);\n }\n\n return new NFError('Could not create ImportMap.');\n });\n }\n}\n\nfunction shipsOnly(version: SharedVersion, served: (specifier: Specifier) => boolean): boolean {\n let only = true;\n forEachVersionEntry(version, undefined, specifier => {\n only &&= served(specifier);\n });\n return only;\n}\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type {\n CommitOptions,\n ForCommittingChanges,\n} from '../driver-ports/init/for-committing-changes.port';\nimport type { ImportMap } from 'lib/core/1.domain/import-map/import-map.contract';\nimport type { LoggingConfig } from 'lib/core/2.app/config';\n\nexport function createCommitChanges(\n config: LoggingConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'scopedExternalsRepo'\n | 'sharedExternalsRepo'\n | 'sharedChunksRepo'\n | 'browser'\n >\n): ForCommittingChanges {\n /**\n * Step 5: Commit all changes\n *\n * The changes made to the storage/cache are persisted to storage, and the importmap is\n * inserted into the HTML DOM.\n *\n * This step only runs if all previous steps were successful to prevent the persistence of\n * erroneous changes into storage which can corrupt other pages/routes of the host. A failed\n * dynamic load is undone by `rollbackChanges` instead.\n */\n return (importMap: ImportMap, { markUndecided = false, ...browserOpts }: CommitOptions = {}) =>\n Promise.resolve(importMap)\n .then(map => addToBrowser(map, browserOpts))\n .then(() => {\n if (markUndecided) markUndecidedScopes();\n persistRepositoryChanges();\n });\n\n function addToBrowser(importMap: ImportMap, opts: Pick<CommitOptions, 'override'>) {\n ports.browser.setImportMapFn(importMap, opts);\n config.log.debug(5, 'Added import map to browser.', importMap);\n return importMap;\n }\n\n // A runtime load decides no serving build, so the next init decides one in each non-strict scope it wrote.\n function markUndecidedScopes() {\n const repo = ports.sharedExternalsRepo;\n for (const shareScope of repo.uncommittedScopes())\n if (repo.scopeType(shareScope) !== 'strict') repo.markUndecided(shareScope);\n }\n\n function persistRepositoryChanges() {\n ports.remoteInfoRepo.commit();\n ports.scopedExternalsRepo.commit();\n ports.sharedExternalsRepo.commit();\n ports.sharedChunksRepo.commit();\n return;\n }\n}\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ForRollingBackChanges } from '../driver-ports/init/for-rolling-back-changes.port';\nimport type { LoggingConfig } from '../config/log.contract';\n\nexport const createStateDump =\n (\n config: LoggingConfig,\n ports: Pick<DrivingContract, 'remoteInfoRepo' | 'sharedExternalsRepo' | 'scopedExternalsRepo'>\n ) =>\n (msg: string): void =>\n config.log.debug(0, msg, {\n remotes: { ...ports.remoteInfoRepo.getAll() },\n 'shared-externals': ports.sharedExternalsRepo\n .getScopes({ includeGlobal: true })\n .reduce(\n (acc, scope) => ({ ...acc, [scope]: ports.sharedExternalsRepo.getFromScope(scope) }),\n {}\n ),\n 'scoped-externals': ports.scopedExternalsRepo.getAll(),\n });\n\nexport function createRollbackChanges(\n config: LoggingConfig,\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedExternalsRepo' | 'sharedChunksRepo'\n >\n): ForRollingBackChanges {\n const stateDump = createStateDump(config, ports);\n\n // The repositories outlive a failed load, so its half-written records would otherwise reach the next commit.\n return label =>\n Promise.resolve().then(() => {\n // The logger is user-supplied: if it throws, the rollback must still run.\n try {\n stateDump(`${label} STATE DUMP`);\n } finally {\n ports.remoteInfoRepo.rollback();\n ports.scopedExternalsRepo.rollback();\n ports.sharedExternalsRepo.rollback();\n ports.sharedChunksRepo.rollback();\n }\n });\n}\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ForExposingModuleLoader } from '../driver-ports/init/for-exposing-module-loader.port';\nimport type { LoadRemoteModule } from 'lib/core/init-federation.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { LoggingConfig } from '../config/log.contract';\nimport * as _path from 'lib/utils/path';\n\nexport function createExposeModuleLoader(\n config: LoggingConfig,\n ports: Pick<DrivingContract, 'remoteInfoRepo' | 'browser'>\n): ForExposingModuleLoader {\n const loadRemoteModule: LoadRemoteModule = <TModule = unknown>(\n remoteName: string,\n exposedModule: string\n ): Promise<TModule> => {\n try {\n if (!ports.remoteInfoRepo.contains(remoteName)) {\n throw new NFError(`Remote '${remoteName}' is not initialized.`);\n }\n\n const remoteModuleUrl = ports.remoteInfoRepo\n .tryGetModule(remoteName, exposedModule)\n .orThrow(\n new NFError(\n `Exposed module '${exposedModule}' from remote '${remoteName}' not found in storage.`\n )\n );\n\n config.log.debug(6, `Loading initialized module '${remoteModuleUrl}'`);\n\n return ports.browser.importModule(remoteModuleUrl) as Promise<TModule>;\n } catch (error) {\n config.log.error(6, `Failed to load module ${_path.join(remoteName, exposedModule)}: `, {\n error,\n });\n\n return Promise.reject(\n new NFError(`Failed to load module ${_path.join(remoteName, exposedModule)}`)\n );\n }\n };\n\n /**\n * Step 6: expose module loader\n *\n * The module loader can only be used after the importmap was generated and added to\n * the DOM, hence the module loader fn is exposed to the host after the final commit\n * step.\n *\n * The loadRemoteModule is also a callback that is returned as a promise by the initFederation\n * function. This way the loadRemoteModule can be shared througout the host application using\n * CustomEvents or by adding it to the global Window object for easy access.\n *\n * @param adapters\n */\n return () => Promise.resolve(loadRemoteModule);\n}\n", "import type { RemoteEntryUrl } from 'lib/core/1.domain/remote-entry/manifest.contract';\nimport type { RemoteName } from 'lib/core/1.domain/remote/remote-info.contract';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { ModeConfig } from '../config/mode.contract';\nimport type { ForGettingRemoteEntry } from '../driver-ports/init/for-getting-remote-entry.port';\nimport type { RemoteRef } from '../driver-ports/init/flow.contract';\nimport { Optional } from 'lib/utils/optional';\nimport type { RemoteEntry } from 'lib/core/1.domain';\nimport * as _path from 'lib/utils/path';\n\nconst normalizeRemoteRef = (remote?: RemoteRef): { name?: RemoteName; integrity?: string } => {\n if (!remote) return {};\n if (typeof remote === 'string') return { name: remote };\n return remote;\n};\n\nexport function createGetRemoteEntry(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'remoteEntryProvider' | 'remoteInfoRepo' | 'sse'>\n): ForGettingRemoteEntry {\n return async (remoteEntryUrl: RemoteEntryUrl, remote?: RemoteRef) => {\n const { name: remoteName, integrity } = normalizeRemoteRef(remote);\n\n // The committed import map cannot drop a remote's imports, so a dynamic init never replaces a known remote.\n const knownAtUrl = findCachedRemoteAt(remoteEntryUrl);\n if (knownAtUrl) {\n config.log.debug(\n 7,\n `Found remote '${knownAtUrl}' at '${remoteEntryUrl}' in storage, omitting fetch.`\n );\n return Optional.empty<RemoteEntry>();\n }\n if (!!remoteName && ports.remoteInfoRepo.contains(remoteName))\n return warnInitialized(remoteName, remoteEntryUrl);\n\n try {\n const remoteEntry = integrity\n ? await ports.remoteEntryProvider.provide(remoteEntryUrl, { integrity })\n : await ports.remoteEntryProvider.provide(remoteEntryUrl);\n\n config.log.debug(\n 7,\n `[${remoteEntry.name}] Fetched from '${remoteEntry.url}', exposing: ${JSON.stringify(remoteEntry.exposes)}`\n );\n\n if (!!remoteName && remoteEntry.name !== remoteName) {\n const errorMsg = `Fetched remote '${remoteEntry.name}' does not match requested '${remoteName}'.`;\n if (config.strict.strictRemoteEntry) {\n config.log.error(7, errorMsg);\n throw new NFError('Could not fetch remote entry');\n }\n config.log.warn(7, errorMsg + ' Omitting expected name.');\n }\n\n if (ports.remoteInfoRepo.contains(remoteEntry.name))\n return warnInitialized(remoteEntry.name, remoteEntryUrl);\n return Optional.of(checkForSSE(remoteEntry));\n } catch (error) {\n config.log.error(\n 7,\n `[${remoteName ?? 'unknown'}] Could not fetch remoteEntry from ${remoteEntryUrl}.`,\n error\n );\n return Promise.reject(\n new NFError(`[${remoteName ?? remoteEntryUrl}] Could not fetch remoteEntry.`)\n );\n }\n };\n\n function warnInitialized(name: RemoteName, remoteEntryUrl: string): Optional<RemoteEntry> {\n const initializedFrom = ports.remoteInfoRepo\n .tryGet(name)\n .map(info => _path.join(info.scopeUrl, 'remoteEntry.json'))\n .get();\n config.log.warn(\n 7,\n `[${name}] Already initialized from '${initializedFrom}', ignoring '${remoteEntryUrl}'.`\n );\n return Optional.empty<RemoteEntry>();\n }\n\n function findCachedRemoteAt(remoteEntryUrl: string): RemoteName | undefined {\n return Object.entries(ports.remoteInfoRepo.getAll()).find(\n ([, info]) => _path.join(info.scopeUrl, 'remoteEntry.json') === remoteEntryUrl\n )?.[0];\n }\n\n function checkForSSE(entry: RemoteEntry): RemoteEntry {\n if (config.sse) {\n if (entry.buildNotificationsEndpoint) {\n ports.sse.watchRemoteBuilds(\n _path.join(_path.getScope(entry.url), entry.buildNotificationsEndpoint)\n );\n config.log.debug(7, `Registered SSE endpoint of remote '${entry.name}' `);\n } else {\n config.log.debug(7, `Remote ${entry.name} has no defined 'buildNotificationsEndpoint'`);\n }\n }\n return entry;\n }\n}\n", "import type { ForUpdatingCache } from '../driver-ports/init/for-updating-cache';\nimport {\n type RemoteEntry,\n type DenseSharedInfo,\n type ExternalName,\n type RemoteName,\n type SharedVersionAction,\n type SharedVersionMeta,\n GLOBAL_SCOPE,\n} from 'lib/core/1.domain';\nimport type { LoadActions } from 'lib/core/1.domain/remote-entry/load-actions.contract';\nimport { createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport { addRemoteToVersion } from 'lib/core/1.domain/externals/basis';\nimport { loadSplitsPackage } from 'lib/core/1.domain/externals/serving';\nimport { type Claim, committedClaims } from 'lib/core/1.domain/externals/claims';\nimport {\n groupByPackage,\n type PackageOf,\n packageOfIn,\n type Specifier,\n} from 'lib/core/1.domain/externals/specifier';\nimport { type LabelledCopy, pooledPackagesWith } from 'lib/core/1.domain/pooling/membership';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport * as _path from 'lib/utils/path';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { createStoreRemoteEntry, type SharedExternalContext } from './store-remote-entry';\n\ntype Pending = { external: DenseSharedInfo; ctx: SharedExternalContext };\n\ntype CommittedClaims = Map<Specifier, Claim>;\n\ntype PackageClaims = readonly [Specifier, Claim][];\n\n// Indexes the record as decidePackages reads it, so it must not outlive it: applyDecision writes that record.\ntype LoadView = {\n packageOf: PackageOf;\n claims: CommittedClaims;\n claimsOf(pkg: ExternalName): PackageClaims;\n inPool(pkg: ExternalName): boolean;\n};\n\ntype Rejection = { item: Pending; specifier: Specifier; claim: Claim };\n\n// share: the remote's build opens the package; skip: it runs the build the map serves it from; scope: its own\n// build beside the map (partlyServed: the map serves some of it, or all of it from two builds).\ntype Decision =\n | { action: 'share' }\n | { action: 'scope'; partlyServed: boolean }\n | { action: 'skip'; files: Map<Specifier, SharedVersionMeta> };\n\nexport function createUpdateCache(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'sharedExternalsRepo'\n | 'scopedExternalsRepo'\n | 'sharedChunksRepo'\n | 'versionCheck'\n >\n): ForUpdatingCache {\n const storeRemoteEntry = createStoreRemoteEntry(config, ports, 8);\n // Read per call so a port swapped after wiring is honoured.\n const accepts = createAcceptsTag(\n (tag, range) => ports.versionCheck.isCompatible(tag, range),\n (a, b) => ports.versionCheck.compare(a, b)\n );\n\n // The import map is committed, so each package the remote shares runs wholly from one build; see\n // docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n return remoteEntry => {\n try {\n // Collected before any copy is stored, so every decision reads the record the committed map came from.\n const pending: Pending[] = [];\n storeRemoteEntry(remoteEntry, (_, external, ctx) => pending.push({ external, ctx }));\n const decisions = decidePackages(remoteEntry, pending);\n\n const actions: LoadActions = {};\n for (const item of pending)\n actions[item.external.packageName] = applyDecision(remoteEntry, item, decisions.get(item)!);\n\n return Promise.resolve({ entry: remoteEntry, actions });\n } catch (error) {\n return Promise.reject(error);\n }\n };\n\n function decidePackages(remoteEntry: RemoteEntry, pending: Pending[]): Map<Pending, Decision> {\n const decisions = new Map<Pending, Decision>();\n const viewOf = loadViewOf(remoteEntry, pending);\n for (const group of pendingPerPackage(pending, viewOf)) {\n // The strict scope shares every version side by side.\n const decision =\n group[0]!.ctx.scopeType === 'strict'\n ? ({ action: 'share' } as const)\n : decidePackage(remoteEntry, group, viewOf(group[0]!.external.shareScope));\n for (const item of group) decisions.set(item, decision);\n }\n scopeOpenedPackages(decisions);\n return decisions;\n }\n\n function pendingPerPackage(\n pending: Pending[],\n viewOf: (shareScope: string | undefined) => LoadView\n ): Pending[][] {\n const packages = new Map<string, Pending[]>();\n for (const item of pending) {\n const { shareScope, packageName } = item.external;\n // The strict scope shares each external whatever its package, so it needs no view.\n const pkg =\n item.ctx.scopeType === 'strict' ? packageName : viewOf(shareScope).packageOf(packageName);\n const key = `${shareScope ?? GLOBAL_SCOPE}\\0${pkg}`;\n const group = packages.get(key);\n if (group) group.push(item);\n else packages.set(key, [item]);\n }\n return [...packages.values()];\n }\n\n function loadViewOf(\n remoteEntry: RemoteEntry,\n pending: Pending[]\n ): (shareScope: string | undefined) => LoadView {\n const views = new Map<string, LoadView>();\n return shareScope => {\n const scope = shareScope ?? GLOBAL_SCOPE;\n let view = views.get(scope);\n if (!view) {\n const record = ports.sharedExternalsRepo.getFromScope(shareScope);\n const claims = committedClaims(Object.entries(record), {\n shareScope: scope,\n without: remoteEntry.name,\n });\n // The load's copies count as stored: they can only merge packages the committed map serves apart.\n const packageOf = packageOfIn(record, loadingIn(pending, scope));\n const claimsIn = groupByPackage(claims, ([specifier]) => specifier, packageOf);\n let pooled: Set<ExternalName> | undefined;\n view = {\n packageOf,\n claims,\n claimsOf: pkg => claimsIn.get(pkg) ?? [],\n inPool: pkg => {\n pooled ??= pooledPackagesWith(record, labelledCopiesIn(pending, scope), packageOf);\n return pooled.has(pkg);\n },\n };\n views.set(scope, view);\n }\n return view;\n };\n }\n\n function inScope(pending: Pending[], scope: string): Pending[] {\n return pending.filter(({ external }) => (external.shareScope ?? GLOBAL_SCOPE) === scope);\n }\n\n function loadingIn(pending: Pending[], scope: string): [ExternalName, SharedVersionMeta][] {\n return inScope(pending, scope).map(({ external, ctx }) => [external.packageName, ctx.remote]);\n }\n\n // The load's copies count as stored, so a pool only their labels form is judged as the gate will see it.\n function labelledCopiesIn(pending: Pending[], scope: string): LabelledCopy[] {\n return inScope(pending, scope).map(({ external, ctx }) => ({\n name: external.packageName,\n pool: ctx.remote.pool,\n }));\n }\n\n function scopeOpenedPackages(decisions: Map<Pending, Decision>): void {\n // An opened package's files resolve through the loader's scope, so its consumers would reach that build.\n if (![...decisions.values()].some(d => d.action === 'scope' && d.partlyServed)) return;\n for (const [item, decision] of decisions)\n if (decision.action === 'share' && item.ctx.scopeType !== 'strict')\n decisions.set(item, { action: 'scope', partlyServed: false });\n }\n\n function decidePackage(remoteEntry: RemoteEntry, group: Pending[], view: LoadView): Decision {\n const pkg = view.packageOf(group[0]!.external.packageName);\n const claims = view.claimsOf(pkg);\n if (claims.length === 0) return { action: 'share' };\n\n const specifiers = group.flatMap(({ external }) => Object.keys(external.entries));\n const builds = specifiers.every(specifier => view.claims.has(specifier))\n ? new Set(specifiers.map(specifier => view.claims.get(specifier)!.copy.name))\n : undefined;\n\n const rejections = group.flatMap(item => rejectionsOf(item, view.claims));\n if (rejections.length > 0) {\n const copies = group.map(({ ctx }) => ({ tag: ctx.tag, copy: ctx.remote }));\n const splits =\n (builds !== undefined && builds.size > 1) ||\n loadSplitsPackage(pkg, copies, claims, accepts);\n for (const rejection of refused(rejections, splits, view.inPool(pkg)))\n reportIncompatible(remoteEntry, rejection);\n return { action: 'scope', partlyServed: false };\n }\n\n if (!builds || builds.size > 1) return { action: 'scope', partlyServed: true };\n return { action: 'skip', files: servingFiles(claims, builds) };\n }\n\n // What the map serves of the package from the build the remote follows; a named scope maps all of it, as init\n // maps a skip copy's serving version.\n function servingFiles(\n claims: PackageClaims,\n builds: ReadonlySet<RemoteName>\n ): Map<Specifier, SharedVersionMeta> {\n const files = new Map<Specifier, SharedVersionMeta>();\n for (const [specifier, { copy }] of claims)\n if (builds.has(copy.name)) files.set(specifier, copy);\n return files;\n }\n\n // A non-strict range follows the map's tag all the same, as at init.\n function rejectionsOf(item: Pending, claims: CommittedClaims): Rejection[] {\n const { external, ctx } = item;\n if (!ctx.remote.strictVersion) return [];\n return Object.keys(external.entries).flatMap(specifier => {\n const claim = claims.get(specifier);\n return claim && !accepts(claim.tag, ctx.tag, ctx.remote.requiredVersion)\n ? [{ item, specifier, claim }]\n : [];\n });\n }\n\n // The first rejection of each copy that a cold init keeping the committed builds refuses too; see\n // docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n function refused(rejections: Rejection[], splits: boolean, pooled: boolean): Rejection[] {\n const first = new Map<Pending, Rejection>();\n for (const rejection of rejections)\n if (!first.has(rejection.item) && (pooled || !splits || electionKeeps(rejection)))\n first.set(rejection.item, rejection);\n return [...first.values()];\n }\n\n // A cold election with the loader refuses the claimed tag where no tag pleases every strict copy, and otherwise\n // keeps it only on a host row, or the newest with latestSharedExternal.\n function electionKeeps({ item: { external, ctx }, claim }: Rejection): boolean {\n if (claim.external !== external.packageName) return false;\n const versions =\n ports.sharedExternalsRepo.tryGet(claim.external, external.shareScope).get()?.versions ?? [];\n const strict = [\n { tag: ctx.tag, copy: ctx.remote },\n ...versions.flatMap(v =>\n v.remotes.filter(r => r.strictVersion).map(copy => ({ tag: v.tag, copy }))\n ),\n ];\n const tags = [ctx.tag, ...versions.map(v => v.tag)];\n if (!tags.some(tag => strict.every(s => accepts(tag, s.tag, s.copy.requiredVersion))))\n return true;\n const host = versions.find(v => v.host);\n if (host) return host.tag === claim.tag;\n if (!config.profile.latestSharedExternal) return false;\n return tags.every(tag => ports.versionCheck.compare(claim.tag, tag) >= 0);\n }\n\n function reportIncompatible(\n remoteEntry: RemoteEntry,\n { item: { external, ctx }, specifier, claim }: Rejection\n ) {\n const errorMsg = `[${external.shareScope ?? GLOBAL_SCOPE}][${remoteEntry.name}] ${specifier}@${\n ctx.tag\n } Is not compatible with existing ${specifier}@${claim.tag} requiredRange '${\n ctx.remote.requiredVersion\n }'`;\n\n if (config.strict.strictExternalCompatibility) {\n config.log.error(8, errorMsg);\n throw new NFError(`Could not process remote '${remoteEntry.name}'`);\n }\n config.log.warn(8, errorMsg);\n }\n\n function applyDecision(\n remoteEntry: RemoteEntry,\n { external, ctx }: Pending,\n decision: Decision\n ): LoadActions[string] {\n storeCopy(ctx, decision.action);\n if (decision.action !== 'skip') return { action: decision.action };\n\n const covered = Object.keys(external.entries);\n if (!external.shareScope) return { action: 'skip', covered };\n return {\n action: 'skip',\n covered,\n override: overrideFrom(remoteEntry, external, decision.files),\n };\n }\n\n // A skip copy keeps out of the share row, where it would claim on the next page what the map serves from the\n // build it follows. A scoped one stays inside a shareable version, where a later import-map build would\n // redirect it to the basis.\n function storeCopy(ctx: SharedExternalContext, action: SharedVersionAction): void {\n const { tag, remote } = ctx;\n const cached = ctx.readRecord();\n const shared = cached.versions.find(v => v.tag === tag && v.action === 'share');\n if (shared && action !== 'scope') ctx.assertSameVersionCompatibility(shared);\n\n remote.cached = action !== 'skip';\n const row =\n action === 'share' ? shared : cached.versions.find(v => v.tag === tag && v.action === action);\n // Only a package the map doesn't serve is shared, so the loader serves it. The strict scope serves every version\n // side by side: a strict row keeps the basis the committed map and getShared serve it from.\n const loaderServes = action === 'share' && ctx.scopeType !== 'strict';\n if (!row) cached.versions.push({ tag, action, host: false, remotes: [remote] });\n else if (loaderServes) addRemoteToVersion(row, remote);\n else row.remotes.push(remote);\n if (loaderServes) cached.servingBuild = remote.name;\n ctx.write();\n }\n\n // A named scope has no `imports` to inherit: each entrypoint maps to the file the committed map serves it from.\n function overrideFrom(\n remoteEntry: RemoteEntry,\n external: DenseSharedInfo,\n files: Map<Specifier, SharedVersionMeta>\n ): Record<string, string> {\n return Object.fromEntries(\n Array.from(files, ([specifier, copy]) => [\n specifier,\n _path.join(providerScopeUrl(remoteEntry, external, copy.name), copy.entries[specifier]!),\n ])\n );\n }\n\n function providerScopeUrl(\n remoteEntry: RemoteEntry,\n external: DenseSharedInfo,\n providerName: string\n ): string {\n return ports.remoteInfoRepo\n .tryGet(providerName)\n .map(remote => remote.scopeUrl)\n .orThrow(() => {\n config.log.error(\n 8,\n `[${external.shareScope ?? GLOBAL_SCOPE}][${remoteEntry.name}][${\n external.packageName\n }@${external.version}][override] Remote name not found in cache.`\n );\n return new NFError(`Could not find override url from remote ${providerName}`);\n });\n }\n}\n", "import {\n type ExternalName,\n GLOBAL_SCOPE,\n type RemoteName,\n type SharedVersionMeta,\n type VersionName,\n} from 'lib/core/1.domain';\nimport type { LoadActions } from 'lib/core/1.domain/remote-entry/load-actions.contract';\nimport { committedClaims } from 'lib/core/1.domain/externals/claims';\nimport type { AcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport {\n type PackageOf,\n type Specifier,\n SpecifierTags,\n} from 'lib/core/1.domain/externals/specifier';\nimport * as _path from 'lib/utils/path';\nimport { type Build, buildOf, type Copy } from './builds';\nimport type { PoolMember } from './membership';\nimport { agrees, unwitnessedGap } from './rules';\n\n// See docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n\n// One file: the remote whose scope URL it lives under, and its name there.\ntype Served = { tag: VersionName; remote: RemoteName; file: string };\n\ntype CommittedView = {\n packageOf: PackageOf;\n builds: Map<RemoteName, Build>;\n // What the committed global map serves per specifier: `imports`, or the shareScope's scopes.\n global: Map<Specifier, Served>;\n // Per build, the specifiers it runs from its own or a subpool's files, at the tag it runs.\n runsOffMap: Map<RemoteName, Map<Specifier, Served>>;\n};\n\nexport type GateMiss =\n | { cause: 'incompatible'; specifier: Specifier; tag: VersionName }\n | { cause: 'uncovered'; specifier: Specifier }\n | { cause: 'uncovered'; unshipped: true }\n | { cause: 'uncovered'; owner: RemoteName; specifier: Specifier; tag: VersionName };\n\n// `toSkip`: the copy moves out of a share row (opened or joined) or a resolver scope into a skip row.\ntype MapCover = {\n name: ExternalName;\n toSkip: boolean;\n override: Record<Specifier, string>;\n};\n\ntype MappedFiles = { covered: Set<Specifier>; override: Record<Specifier, string> };\n\n// One of the remote's copies the map may cover, with its action and what the map would serve of it.\ntype Coverable = MappedFiles & {\n member: PoolMember;\n action: LoadActions[string];\n copy: SharedVersionMeta;\n};\n\n// Where the remote resolves a specifier it ships: the map's file, or its own.\ntype Reach = { remote: RemoteName; file: string };\n\ntype MapPolicy = {\n shareScope: string;\n scopeUrlOf: (remote: RemoteName) => string | undefined;\n};\n\n// A `scope` copy counts as served by its build: its files are already in the map under its own scope.\n// `without`'s build is left out of `builds` too.\nexport function committedView(\n members: PoolMember[],\n shipped: ReadonlyMap<RemoteName, readonly Copy[]>,\n recordOrder: ExternalName[],\n {\n shareScope,\n without,\n packageOf,\n }: { shareScope: string; without?: RemoteName; packageOf: PackageOf }\n): CommittedView {\n const global: CommittedView['global'] = new Map();\n\n // Mirrors what `generate-import-map` emitted, so `global` is what the committed map really serves.\n const claims = committedClaims(inRecordOrder(members, recordOrder), { shareScope, without });\n for (const [specifier, { tag, copy }] of claims)\n global.set(specifier, { tag, remote: copy.name, file: copy.entries[specifier]! });\n\n const builds = new Map<RemoteName, Build>();\n for (const [owner, copies] of shipped)\n if (owner !== without) builds.set(owner, buildOf(owner, copies, packageOf));\n\n const fileOf = subpoolFilesOf(members);\n return {\n packageOf,\n builds,\n global,\n runsOffMap: runsOffMapOf(members, global, builds, fileOf),\n };\n}\n\nfunction subpoolFilesOf(members: PoolMember[]): Map<RemoteName, Map<Specifier, string>> {\n const subpoolOwners = new Set<RemoteName>();\n for (const member of members)\n for (const version of member.external.versions)\n for (const { servedBy } of version.remotes) if (servedBy) subpoolOwners.add(servedBy);\n const fileOf = new Map<RemoteName, Map<Specifier, string>>();\n for (const member of members)\n for (const version of member.external.versions)\n for (const { name, entries } of version.remotes) {\n if (!subpoolOwners.has(name)) continue;\n let files = fileOf.get(name);\n if (!files) fileOf.set(name, (files = new Map()));\n // Per specifier, earlier rows first.\n for (const specifier in entries)\n if (!files.has(specifier)) files.set(specifier, entries[specifier]!);\n }\n return fileOf;\n}\n\nfunction runsOffMapOf(\n members: PoolMember[],\n global: CommittedView['global'],\n builds: CommittedView['builds'],\n fileOf: ReadonlyMap<RemoteName, ReadonlyMap<Specifier, string>>\n): CommittedView['runsOffMap'] {\n const runsOffMap: CommittedView['runsOffMap'] = new Map();\n for (const member of members)\n for (const version of member.external.versions)\n for (const meta of version.remotes) {\n const { servedBy } = meta;\n // A share copy runs the map's files; only the loader's may ship more, and no reader looks it up.\n if (version.action === 'share' && !servedBy) continue;\n let runs = runsOffMap.get(meta.name);\n if (!runs) runsOffMap.set(meta.name, (runs = new Map()));\n for (const specifier in meta.entries) {\n // A skip copy runs its own file only for an entrypoint the map lacks.\n if (version.action === 'skip' && !servedBy && global.has(specifier)) continue;\n // A subpool member's copy keeps its own tag in the record but runs its build's files.\n const tag =\n (servedBy ? builds.get(servedBy)?.tags.pinnedTag(specifier) : undefined) ?? version.tag;\n const file = servedBy && fileOf.get(servedBy)?.get(specifier);\n runs.set(\n specifier,\n file\n ? { tag, remote: servedBy, file }\n : { tag, remote: meta.name, file: meta.entries[specifier]! }\n );\n }\n }\n return runsOffMap;\n}\n\n// See docs/version-resolver.md \u00A7\"Scope and dynamic init\", step 1. A resolver scope needs no rule of its own:\n// a range that rejects the map's tag is a miss here too.\nexport function judgeRemote(\n copies: readonly Copy[],\n view: CommittedView,\n accepts: AcceptsTag\n): 'global' | GateMiss {\n const { rejected, missing } = scan(copies, view, accepts);\n if (rejected) return { cause: 'incompatible', ...rejected };\n const globalTags = new SpecifierTags(\n view.packageOf,\n [...view.global].map(([s, { tag }]) => [s, tag] as const)\n );\n const binding = offMapBinding(copies, view, globalTags);\n if (binding) return { cause: 'uncovered', ...binding };\n // A package the map serves from two builds is a combination no build shipped, whatever the tags say: the\n // load's own copies can merge libraries the committed builds keep apart.\n if (servedSplit(copies, view)) return { cause: 'uncovered', unshipped: true };\n // The map's tags must be a combination one build shipped: agreeing is its own witness, otherwise one\n // committed build must be.\n if (agrees(copies, globalTags)) return 'global';\n if (missing !== undefined) return { cause: 'uncovered', specifier: missing };\n if (unwitnessedGap(copies, globalTags, view.builds.values()) === undefined) return 'global';\n return { cause: 'uncovered', unshipped: true };\n}\n\nfunction servedSplit(copies: readonly Copy[], view: CommittedView): boolean {\n const loaded = new Set(copies.flatMap(copy => copy.specifiers.map(view.packageOf)));\n const servedBy = new Map<ExternalName, RemoteName>();\n for (const [specifier, { remote }] of view.global) {\n const pkg = view.packageOf(specifier);\n if (!loaded.has(pkg)) continue;\n const first = servedBy.get(pkg);\n if (first === undefined) servedBy.set(pkg, remote);\n else if (first !== remote) return true;\n }\n return false;\n}\n\ntype Binding = { owner: RemoteName; specifier: Specifier; tag: VersionName };\n\nexport type CoverResult =\n { covers: MapCover[] } | { unmapped: RemoteName } | { gap: Specifier } | { bound: Binding };\n\n// `covered` is per external, but the map serves by specifier: an entrypoint another member ships as a package\n// of its own (flat vs dense) is served all the same. A named scope has no `imports` to inherit, so the remote's\n// own scope maps each such specifier to the file the committed map serves it from, replacing the resolver's\n// override. Covering fails, and the remote serves the pool itself, when it would reach one specifier at two\n// files (`bound`) or take a copy whose package the map serves only in part (`gap`).\nexport function coverFromMap(\n remote: RemoteName,\n mine: readonly PoolMember[],\n view: CommittedView,\n actions: Readonly<LoadActions>,\n policy: MapPolicy\n): CoverResult {\n const files: Coverable[] = [];\n for (const member of mine) {\n const action = actions[member.name]!;\n const copy = member.external.versions.flatMap(v => v.remotes).find(r => r.name === remote);\n if (!copy) continue;\n\n const mapped = mapFiles(copy, view, policy, action);\n if ('unmapped' in mapped) return mapped;\n files.push({ member, action, copy, ...mapped });\n }\n\n const reaches = reachesOf(remote, files, view);\n const bound = boundByFile(reaches, view);\n if (bound !== undefined) return { bound };\n const servedPackages = new Set([...view.global.keys()].map(view.packageOf));\n const gap = files\n .map(file => gapOf(file, servedPackages, view.packageOf))\n .find(specifier => specifier !== undefined);\n if (gap !== undefined) return { gap };\n return { covers: files.filter(covering).map(coverOf) };\n}\n\n// The first entrypoint a copy ships that the map lacks, when the map serves another entrypoint of its package.\nfunction gapOf(\n { copy, covered }: Coverable,\n servedPackages: ReadonlySet<string>,\n packageOf: PackageOf\n): Specifier | undefined {\n const entrypoints = Object.keys(copy.entries);\n const missing = entrypoints.filter(specifier => !covered.has(specifier));\n if (missing.length < entrypoints.length) return missing[0];\n return missing.find(specifier => servedPackages.has(packageOf(specifier)));\n}\n\nfunction covering({ action, copy, covered }: Coverable): boolean {\n if (action.action === 'skip') return true;\n const entrypoints = Object.keys(copy.entries);\n return entrypoints.length > 0 && entrypoints.every(specifier => covered.has(specifier));\n}\n\nfunction coverOf({ member, action, copy, covered, override }: Coverable): MapCover {\n // A copy that joined a share row would claim, on the next page, what the map serves from another member.\n const toSkip =\n action.action !== 'skip' ||\n (covered.size > action.covered!.length &&\n member.external.versions.some(v => v.action === 'share' && v.remotes.includes(copy)));\n return { name: member.name, toSkip, override };\n}\n\n// Where the remote resolves each specifier it ships once the covers apply: the map's file, else its own.\nfunction reachesOf(\n remote: RemoteName,\n files: readonly Coverable[],\n view: CommittedView\n): Map<Specifier, Reach> {\n const reaches = new Map<Specifier, Reach>();\n const fromMap = (specifier: Specifier): Reach | undefined => {\n const served = view.global.get(specifier);\n return served && { remote: served.remote, file: served.file };\n };\n for (const file of files) {\n const takesMap = covering(file);\n for (const [specifier, own] of Object.entries(file.copy.entries)) {\n if (!takesMap || !file.covered.has(specifier)) reaches.set(specifier, { remote, file: own });\n else {\n const reach = fromMap(specifier);\n if (reach) reaches.set(specifier, reach);\n }\n }\n }\n return reaches;\n}\n\n// `offMapBinding` by file rather than tag: a committed file binds its pool-mates where its build resolves them\n// (off the map where it runs them so, else the map), so every build whose file the remote reaches, directly or\n// through another such file, must resolve each specifier it ships to the file the remote does, or the one the\n// first such build does.\nfunction boundByFile(\n reaches: ReadonlyMap<Specifier, Reach>,\n view: CommittedView\n): Binding | undefined {\n const servers = new Set<RemoteName>();\n for (const { remote } of reaches.values()) if (view.builds.has(remote)) servers.add(remote);\n\n const firstRun = new Map<Specifier, { remote: RemoteName; file: string }>();\n // A Set iterates what is added during the loop, so a build first reached through another's file is judged too.\n for (const build of servers)\n for (const specifier of view.builds.get(build)!.tags.keys()) {\n const served = view.runsOffMap.get(build)?.get(specifier) ?? view.global.get(specifier);\n if (served === undefined) continue;\n const reached = reaches.get(specifier) ?? firstRun.get(specifier);\n if (reached === undefined) {\n firstRun.set(specifier, served);\n if (view.builds.has(served.remote)) servers.add(served.remote);\n } else if (reached.remote !== served.remote || reached.file !== served.file)\n return { owner: build, specifier, tag: served.tag };\n }\n return undefined;\n}\n\nfunction mapFiles(\n copy: SharedVersionMeta,\n view: CommittedView,\n policy: MapPolicy,\n action: LoadActions[string]\n): MappedFiles | { unmapped: RemoteName } {\n const covered = new Set(action.covered);\n const override = { ...action.override };\n for (const specifier in copy.entries) {\n const source = view.global.get(specifier);\n if (!source) continue;\n if (policy.shareScope !== GLOBAL_SCOPE) {\n const scopeUrl = policy.scopeUrlOf(source.remote);\n if (!scopeUrl) return { unmapped: source.remote };\n override[specifier] = _path.join(scopeUrl, source.file);\n }\n covered.add(specifier);\n }\n return { covered, override };\n}\n\nfunction scan(copies: readonly Copy[], view: CommittedView, accepts: AcceptsTag) {\n let rejected: { specifier: Specifier; tag: VersionName } | undefined;\n let missing: Specifier | undefined;\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const global = view.global.get(s);\n if (global === undefined) missing ??= s;\n else if (!accepts(global.tag, copy.tag, copy.requiredVersion))\n rejected ??= { specifier: s, tag: global.tag };\n }\n return { rejected, missing };\n}\n\n// A committed file binds its pool-mates where its build runs them, so a build serving the remote that runs one\n// off the map at another tag than the remote reaches elsewhere would split it. That tag is the map's, else the\n// remote's own, else the first serving build's.\nfunction offMapBinding(copies: readonly Copy[], view: CommittedView, globalTags: SpecifierTags) {\n const own = new SpecifierTags(\n view.packageOf,\n copies.flatMap(c => c.specifiers.map(s => [s, c.tag] as const))\n );\n const servers = new Set<RemoteName>();\n for (const copy of copies)\n for (const specifier of copy.specifiers) {\n const build = view.global.get(specifier)?.remote;\n if (build !== undefined) servers.add(build);\n }\n\n const firstRun = new SpecifierTags(view.packageOf);\n for (const build of servers)\n for (const [specifier, { tag }] of view.runsOffMap.get(build) ?? []) {\n const reached =\n globalTags.pinnedTag(specifier) ??\n own.pinnedTag(specifier) ??\n firstRun.pinnedTag(specifier);\n if (reached === undefined) firstRun.set(specifier, tag);\n else if (reached !== tag) return { owner: build, specifier, tag };\n }\n return undefined;\n}\n\nfunction inRecordOrder(members: PoolMember[], recordOrder: ExternalName[]) {\n const rank = new Map(recordOrder.map((name, i) => [name, i]));\n return [...members]\n .sort((a, b) => rank.get(a.name)! - rank.get(b.name)!)\n .map(m => [m.name, m.external] as const);\n}\n", "import type { ForPoolingDynamicExternals } from '../../driver-ports/init/for-pooling-dynamic-externals.port';\nimport type { ModeConfig } from '../../config/mode.contract';\nimport type { LoggingConfig } from '../../config/log.contract';\nimport type { DrivingContract } from '../../driving-ports/driving.contract';\nimport {\n type ExternalName,\n GLOBAL_SCOPE,\n type PoolCause,\n type RemoteEntry,\n type RemoteName,\n STRICT_SCOPE,\n type SharedExternal,\n type SharedInfoActions,\n type shareScope,\n} from 'lib/core/1.domain';\nimport type { LoadActions } from 'lib/core/1.domain/remote-entry/load-actions.contract';\nimport { copiesByRemote, specifierCount } from 'lib/core/1.domain/pooling/builds';\nimport { buildPools, type PoolMember, type PoolName } from 'lib/core/1.domain/pooling/membership';\nimport { scopeHasPoolState } from 'lib/core/1.domain/pooling/pool-state';\nimport {\n committedView,\n coverFromMap,\n type CoverResult,\n type GateMiss,\n judgeRemote,\n} from 'lib/core/1.domain/pooling/gate';\nimport { type CopyMove, movedRecord, renamedRecords } from 'lib/core/1.domain/pooling/records';\nimport { createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport type { PackageOf } from 'lib/core/1.domain/externals/specifier';\n\nexport function createPoolDynamicExternals(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'sharedExternalsRepo' | 'remoteInfoRepo' | 'versionCheck'>\n): ForPoolingDynamicExternals {\n // Read per call so a port swapped after wiring is honoured.\n const accepts = createAcceptsTag(\n (tag, range) => ports.versionCheck.isCompatible(tag, range),\n (a, b) => ports.versionCheck.compare(a, b)\n );\n const scopeUrlOf = (remote: RemoteName) => ports.remoteInfoRepo.tryGet(remote).get()?.scopeUrl;\n\n // The committed map is immutable, so this only rewrites the loaded remote's own actions and copies, never\n // another remote's. See docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n return ({ entry, actions }) => {\n for (const [scope, names] of poolableNames(entry, actions)) {\n // A label anywhere in the committed scope forms pools this entry is subject to \u2014 its own label is not\n // required, and the pool covers the whole external, this entry's copies included.\n const committed = ports.sharedExternalsRepo.getFromScope(scope);\n if (!scopeHasPoolState(committed)) continue;\n\n const { pools, packageOf } = buildPools(committed);\n const moves = judgeScope(\n entry.name,\n names,\n actions,\n pools,\n packageOf,\n Object.keys(committed),\n scope\n );\n writeMoves(entry.name, names, moves, committed, pools, scope);\n }\n\n return Promise.resolve({ entry, actions: publicActions(actions) });\n };\n\n function judgeScope(\n remote: RemoteName,\n names: ReadonlySet<ExternalName>,\n actions: LoadActions,\n pools: ReadonlyMap<PoolName, PoolMember[]>,\n packageOf: PackageOf,\n recordOrder: ExternalName[],\n scope: string\n ): Map<ExternalName, CopyMove> {\n const policy = { shareScope: scope, scopeUrlOf };\n const moves = new Map<ExternalName, CopyMove>();\n const selfServe = (members: PoolMember[], cause: PoolCause) => {\n for (const { name } of members) {\n actions[name]!.action = 'scope';\n delete actions[name]!.override;\n moves.set(name, { cause });\n }\n };\n\n for (const pool of pools.values()) {\n // Only the members this entry declares have an action to rewrite; the rest of the pool is context:\n // its committed tags are what the gate reads.\n const mine = pool.filter(member => names.has(member.name));\n if (mine.length === 0) continue;\n\n const shipped = copiesByRemote(pool);\n const view = committedView(pool, shipped, recordOrder, {\n shareScope: scope,\n without: remote,\n packageOf,\n });\n const own = shipped.get(remote) ?? [];\n const verdict = judgeRemote(own, view, accepts);\n if (verdict !== 'global') {\n config.log.warn(8, `[${scope}] ${selfServeWarning(remote, verdict, specifierCount(own))}`);\n selfServe(mine, verdict.cause);\n continue;\n }\n\n const cover = coverFromMap(remote, mine, view, actions, policy);\n if (!('covers' in cover)) {\n if ('unmapped' in cover) warnUnmapped(scope, remote, cover.unmapped);\n else\n config.log.warn(\n 8,\n `[${scope}] ${selfServeWarning(remote, coverMiss(cover), specifierCount(own))}`\n );\n // Half its family on the map's files and half on its own build would tear it.\n selfServe(mine, 'uncovered');\n continue;\n }\n for (const { name, toSkip, override } of cover.covers) {\n const action = actions[name]!;\n if (toSkip) {\n action.action = 'skip';\n moves.set(name, { fromMap: true });\n }\n if (Object.keys(override).length > 0) action.override = override;\n }\n }\n\n return moves;\n }\n\n // Writes the moves back so a reload rebuilds the map this delta publishes, not the one `update-cache`\n // recorded. The loaded remote's members are left dirty: the gate judged it against a map it could not\n // change, so the next init re-elects the scope with it, as a cold init of this record would.\n function writeMoves(\n remote: RemoteName,\n names: ReadonlySet<ExternalName>,\n moves: ReadonlyMap<ExternalName, CopyMove>,\n committed: shareScope,\n pools: ReadonlyMap<PoolName, PoolMember[]>,\n scope: string\n ): void {\n const written: Record<string, SharedExternal> = {};\n for (const [name, move] of moves)\n written[name] = movedRecord(committed[name]!, remote, move, ports.versionCheck.compare);\n for (const [name, record] of renamedRecords({ ...committed, ...written }, pools))\n written[name] = record;\n // A strict re-election throws on a pool the config refuses, so a strict page keeps the gate's verdicts.\n if (!config.strict.strictExternalCompatibility)\n for (const { name } of [...pools.values()].flat().filter(m => names.has(m.name)))\n written[name] = { ...(written[name] ?? committed[name]!), dirty: true };\n for (const [name, record] of Object.entries(written))\n ports.sharedExternalsRepo.addOrUpdate(name, record, scope);\n }\n\n function warnUnmapped(scope: string, remote: RemoteName, build: RemoteName): void {\n config.log.warn(\n 8,\n `[${scope}][${remote}] '${build}' is not in the cache, so its files cannot be mapped.`\n );\n }\n}\n\n// `covered` only carries a skip from the cache update into the gate.\nfunction publicActions(actions: LoadActions): SharedInfoActions {\n for (const action of Object.values(actions)) delete action.covered;\n return actions;\n}\n\nfunction poolableNames(entry: RemoteEntry, actions: LoadActions): Map<string, Set<ExternalName>> {\n const declared = new Map<string, Set<ExternalName>>();\n for (const external of entry.shared ?? []) {\n const name = external.packageName;\n if (!external.singleton || !actions[name]) continue;\n if (external.shareScope === STRICT_SCOPE) continue;\n\n const scope = external.shareScope ?? GLOBAL_SCOPE;\n let names = declared.get(scope);\n if (!names) declared.set(scope, (names = new Set()));\n names.add(name);\n }\n return declared;\n}\n\nfunction coverMiss(\n cover: Exclude<CoverResult, { covers: unknown } | { unmapped: unknown }>\n): GateMiss {\n if ('gap' in cover) return { cause: 'uncovered', specifier: cover.gap };\n return { cause: 'uncovered', ...cover.bound };\n}\n\n// Wording is pinned in `island-warnings.contract.spec.ts` alone; tools read islands from the record.\nfunction selfServeWarning(remote: RemoteName, miss: GateMiss, imports: number): string {\n const where = `All ${imports} of its entrypoints are scoped for it.`;\n if (miss.cause === 'incompatible')\n return `'${remote}' is islanded: its range rejects '${miss.specifier}@${miss.tag}' of the committed map. ${where}`;\n if ('owner' in miss)\n return `'${remote}' serves its own family: committed build '${miss.owner}', whose files it would reach, resolves '${miss.specifier}' to another file than it would. ${where}`;\n if ('unshipped' in miss)\n return `'${remote}' serves its own family: no committed build shipped the map's combination for it. ${where}`;\n return `'${remote}' serves its own family: no committed build offers every entrypoint it imports at a version it accepts (gap '${miss.specifier}'). ${where}`;\n}\n", "import type { ImportMap } from 'lib/core/1.domain/import-map/import-map.contract';\nimport { type RemoteEntry, type SharedInfoActions } from 'lib/core/1.domain';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport * as _path from 'lib/utils/path';\nimport type { ForConvertingToImportMap } from 'lib/core/2.app/driver-ports/init/for-converting-to-import-map';\nimport type { DrivingContract } from 'lib/core/2.app/driving-ports/driving.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { toChunkImport } from '@softarc/native-federation/domain';\n\nexport function createConvertToImportMap(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'sharedChunksRepo'>\n): ForConvertingToImportMap {\n const { log } = config;\n return async ({ entry, actions }) => {\n const importMap: ImportMap = { imports: {} };\n\n addExternals(entry, actions, importMap);\n addRemoteInfos(entry, importMap);\n log.debug(9, `[${entry.name}] Processed actions:`, actions);\n return importMap;\n };\n\n function addExternals(\n remoteEntry: RemoteEntry,\n actions: SharedInfoActions,\n importMap: ImportMap\n ): void {\n if (!remoteEntry.shared) {\n return;\n }\n\n const remoteEntryScope = _path.getScope(remoteEntry.url);\n const integrityMap = remoteEntry.integrity;\n\n const chunkBundles = new Set<string>(['mapping-or-exposed']);\n remoteEntry.shared.forEach(external => {\n // Scoped externals\n if (!external.singleton) {\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n\n if (external?.bundle) chunkBundles.add(external?.bundle);\n return;\n }\n\n if (!actions[external.packageName]) {\n log.warn(\n 9,\n `[${remoteEntry.name}] No action defined for shared external '${external.packageName}', skipping.`\n );\n return;\n }\n\n // Skipped externals are provided by another remote. An override \u2014 from a shareScope skip, or from\n // pooling having placed this remote in a committed build's subpool \u2014 names whose files, per\n // consumer. A global skip without one inherits the committed global mapping and needs no entry of\n // its own.\n if (actions[external.packageName]!.action === 'skip') {\n const { override } = actions[external.packageName]!;\n if (override) {\n Object.entries(override).forEach(([packageName, url]) => {\n addToScopes(remoteEntryScope, packageName, url, importMap);\n });\n return;\n }\n if (!external.shareScope) return;\n // Reaching here means the resolver failed to produce the expected override.\n log.error(\n 9,\n `[${remoteEntry.name}][${external.packageName}] shareScope skip has no override.`\n );\n if (config.strict.strictImportMap) throw new NFError('Could not create ImportMap.');\n // Non-strict fallback: serve from the remote's own scope (matches init).\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n return;\n }\n\n // Chunks for shared externals\n if (external?.bundle) chunkBundles.add(external?.bundle);\n\n // Scoped shared externals\n if (actions[external.packageName]!.action === 'scope') {\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n return;\n }\n\n // Shared externals with shareScope\n if (external.shareScope) {\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n return;\n }\n\n // Default case: shared globally\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n importMap.imports[packageName] = url;\n\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n });\n\n addChunkImports(importMap, remoteEntry, remoteEntryScope, chunkBundles);\n }\n\n function addToScopes(\n scope: string,\n packageName: string,\n url: string,\n importMap: ImportMap\n ): void {\n if (!importMap.scopes) importMap.scopes = {};\n if (!importMap.scopes[scope]) importMap.scopes[scope] = {};\n importMap.scopes[scope][packageName] = url;\n }\n\n function addRemoteInfos(remoteEntry: RemoteEntry, importMap: ImportMap): void {\n if (!remoteEntry.exposes) return;\n const scope = _path.getScope(remoteEntry.url);\n\n remoteEntry.exposes.forEach(exposed => {\n const moduleName = _path.join(remoteEntry.name, exposed.key);\n const moduleUrl = _path.join(scope, exposed.outFileName);\n importMap.imports[moduleName] = moduleUrl;\n addIntegrity(importMap, moduleUrl, remoteEntry.integrity, exposed.outFileName);\n });\n }\n\n function addChunkImports(\n importMap: ImportMap,\n remoteEntry: RemoteEntry,\n remoteEntryScope: string,\n chunkBundles: Set<string>\n ) {\n Array.from(chunkBundles).forEach(bundleName => {\n ports.sharedChunksRepo.tryGet(remoteEntry.name, bundleName).ifPresent(files => {\n files.forEach(file => {\n const url = _path.join(remoteEntryScope, file);\n addToScopes(remoteEntryScope, toChunkImport(file), url, importMap);\n addIntegrity(importMap, url, remoteEntry.integrity, file);\n });\n });\n });\n return importMap;\n }\n\n function addIntegrity(\n importMap: ImportMap,\n url: string,\n integrityMap: Record<string, string> | undefined,\n file: string\n ): void {\n const hash = integrityMap?.[file];\n if (!hash) return;\n if (!importMap.integrity) importMap.integrity = {};\n importMap.integrity[url] = hash;\n }\n}\n", "import type { FLOW_FACTORY } from 'lib/core/2.app/driver-ports/flow-factory.contract';\nimport type { InitDriversContract } from 'lib/core/2.app/driver-ports/init/drivers.contract';\nimport { createGetRemoteEntries } from '../2.app/steps/get-remote-entries';\nimport { createProcessRemoteEntries } from '../2.app/steps/process-remote-entries';\nimport { createDetermineSharedExternals } from '../2.app/steps/determine-shared-externals';\nimport { createPoolSharedExternals } from '../2.app/steps/pooling/pool-shared-externals';\nimport { createDecideServingBuilds } from '../2.app/steps/decide-serving-builds';\nimport { createGenerateImportMap } from '../2.app/steps/generate-import-map';\nimport { createCommitChanges } from '../2.app/steps/commit-changes';\nimport { createRollbackChanges } from '../2.app/steps/rollback-changes';\nimport { createExposeModuleLoader } from '../2.app/steps/expose-module-loader';\nimport { createGetRemoteEntry } from '../2.app/steps/get-remote-entry';\nimport { createUpdateCache } from '../2.app/steps/update-cache';\nimport { createPoolDynamicExternals } from '../2.app/steps/pooling/pool-dynamic-externals';\nimport { createConvertToImportMap } from '../2.app/steps/convert-to-import-map';\nimport type { DrivingContract } from '../2.app/driving-ports/driving.contract';\nimport type { ConfigContract } from '../2.app/config/config.contract';\n\nexport const createInitDrivers = ({\n config,\n adapters,\n}: {\n config: ConfigContract;\n adapters: DrivingContract;\n}): InitDriversContract => ({\n getRemoteEntries: createGetRemoteEntries(config, adapters),\n processRemoteEntries: createProcessRemoteEntries(config, adapters),\n determineSharedExternals: createDetermineSharedExternals(config, adapters),\n poolSharedExternals: createPoolSharedExternals(config, adapters),\n decideServingBuilds: createDecideServingBuilds(config, adapters),\n generateImportMap: createGenerateImportMap(config, adapters),\n commitChanges: createCommitChanges(config, adapters),\n rollbackChanges: createRollbackChanges(config, adapters),\n exposeModuleLoader: createExposeModuleLoader(config, adapters),\n getRemoteEntry: createGetRemoteEntry(config, adapters),\n updateCache: createUpdateCache(config, adapters),\n poolDynamicExternals: createPoolDynamicExternals(config, adapters),\n convertToImportMap: createConvertToImportMap(config, adapters),\n});\n\nexport const INIT_FLOW_FACTORY = ({\n config,\n adapters,\n}: {\n config: ConfigContract;\n adapters: DrivingContract;\n}): FLOW_FACTORY<InitDriversContract> => {\n const flow = createInitDrivers({ config, adapters });\n\n return {\n flow,\n adapters,\n config,\n };\n};\n", "import type { ConfigContract } from '../2.app/config/config.contract';\nimport type { DrivingContract } from '../2.app/driving-ports/driving.contract';\nimport type { InitRemoteEntryFlow, RemoteRef } from '../2.app/driver-ports/init/flow.contract';\nimport type {\n LoadRemoteModule,\n LoadRemoteModuleOf,\n NativeFederationResult,\n} from '../init-federation.contract';\n\nexport { createStateDump } from '../2.app/steps/rollback-changes';\n\nexport const createFederationResult = ({\n config,\n adapters,\n loadRemoteModule,\n initRemoteEntryFlow,\n afterInitRemoteEntry,\n}: {\n config: ConfigContract;\n adapters: DrivingContract;\n loadRemoteModule: LoadRemoteModule;\n initRemoteEntryFlow: InitRemoteEntryFlow;\n afterInitRemoteEntry?: () => Promise<unknown>;\n}): NativeFederationResult => {\n const initRemoteEntry = async (\n remoteEntryUrl: string,\n remote?: RemoteRef\n ): Promise<NativeFederationResult> => {\n return initRemoteEntryFlow(remoteEntryUrl, remote)\n .catch(e => {\n if (config.strict.strictRemoteEntry) return Promise.reject(e);\n else console.warn('Failed to initialize remote entry, continuing anyway.');\n return Promise.resolve();\n })\n .then(() => afterInitRemoteEntry?.())\n .then(() => result);\n };\n\n const result: NativeFederationResult = {\n config,\n adapters,\n loadRemoteModule,\n load: loadRemoteModule,\n as: <TModule = unknown>() => ({\n loadRemoteModule: loadRemoteModule as LoadRemoteModuleOf<TModule>,\n load: loadRemoteModule as LoadRemoteModuleOf<TModule>,\n }),\n initRemoteEntry,\n };\n\n return result;\n};\n", "import { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\nimport type { ImportMap } from 'lib/core/1.domain';\nimport { getLoaderUrl } from './loader-url';\n\n/** Per-specifier list of export names to bridge from the host's instances. */\nexport type HostInstanceKeys = Record<string, string[]>;\n\ntype IncomingMessage = { type: 'import-map-applied' } | { type: 'host-instances-applied' };\ntype OutgoingMessage =\n | { type: 'set-import-map'; map: ImportMap }\n | { type: 'set-host-instances'; keys: HostInstanceKeys };\n\nexport type NodeLoaderClient = {\n setMap: (map: ImportMap) => Promise<void>;\n setHostInstances: (keys: HostInstanceKeys) => Promise<void>;\n ready: () => Promise<void>;\n};\n\nexport const NODE_LOADER_CLIENT_ACK_TIMEOUT_MS = 10_000;\n\nlet cached: NodeLoaderClient | null = null;\n\nconst createClient = (): NodeLoaderClient => {\n const { port1, port2 } = new MessageChannel();\n register(getLoaderUrl(), {\n data: { port: port2 },\n transferList: [port2],\n });\n\n // Don't let the client keep the process alive on its own.\n port1.unref();\n\n let pending: Promise<void> = Promise.resolve();\n\n // Specifiers bridged to host instances. The loader resolves these ahead of\n // the import map, so we strip them from the map we post \u2014 no dead entries.\n const bridged = new Set<string>();\n const omitBridged = (map: ImportMap): ImportMap => {\n if (bridged.size === 0) return map;\n const drop = (imports: ImportMap['imports']): ImportMap['imports'] =>\n Object.fromEntries(Object.entries(imports).filter(([specifier]) => !bridged.has(specifier)));\n const scopes = map.scopes\n ? Object.fromEntries(\n Object.entries(map.scopes).map(([scope, imports]) => [scope, drop(imports)])\n )\n : map.scopes;\n return { ...map, imports: drop(map.imports), ...(scopes ? { scopes } : {}) };\n };\n\n const postAndAwaitAck = (\n message: OutgoingMessage,\n ackType: IncomingMessage['type']\n ): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n const cleanup = (): void => {\n port1.off('message', onMessage);\n if (timer !== null) clearTimeout(timer);\n };\n const onMessage = (msg: IncomingMessage): void => {\n if (msg?.type === ackType) {\n cleanup();\n resolve();\n }\n };\n port1.on('message', onMessage);\n timer = setTimeout(() => {\n cleanup();\n reject(\n new Error(\n `node-loader.client: loader did not acknowledge ${message.type} within ${NODE_LOADER_CLIENT_ACK_TIMEOUT_MS}ms`\n )\n );\n }, NODE_LOADER_CLIENT_ACK_TIMEOUT_MS);\n (timer as { unref?: () => void }).unref?.();\n try {\n port1.postMessage(message);\n } catch (err) {\n cleanup();\n reject(err);\n }\n });\n\n // Serialize every post on a single chain so set-import-map and\n // set-host-instances can never race each other on the loader thread.\n const enqueue = (message: OutgoingMessage, ackType: IncomingMessage['type']): Promise<void> => {\n const next = pending.catch(() => undefined).then(() => postAndAwaitAck(message, ackType));\n pending = next;\n return next;\n };\n\n const setMap = (map: ImportMap): Promise<void> =>\n enqueue({ type: 'set-import-map', map: omitBridged(map) }, 'import-map-applied');\n\n const setHostInstances = (keys: HostInstanceKeys): Promise<void> => {\n Object.keys(keys).forEach(specifier => bridged.add(specifier));\n return enqueue({ type: 'set-host-instances', keys }, 'host-instances-applied');\n };\n\n return {\n setMap,\n setHostInstances,\n ready: () => pending,\n };\n};\n\nexport const getNodeLoaderClient = (): NodeLoaderClient => {\n if (!cached) cached = createClient();\n return cached;\n};\n\n/** Only used by tests. */\nexport const _resetNodeLoaderClient = (): void => {\n cached = null;\n};\n", "import { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport { NFError } from 'lib/core/native-federation.error';\n\n/**\n * Resolves the bundled Node loader (`dist/node-loader/loader.mjs`) via the\n * package's own `exports` map. Self-resolving by name (rather than a relative\n * URL from `import.meta.url`) keeps this working under bundlers, pnpm, Yarn\n * PnP, and monorepo symlinks where the on-disk layout of the installed package\n * is not predictable.\n */\nexport const getLoaderUrl = () => {\n try {\n const require = createRequire(import.meta.url);\n return pathToFileURL(\n require.resolve('@softarc/native-federation-orchestrator/node-loader/loader.mjs')\n );\n } catch (err) {\n const cause = err instanceof Error ? err : new Error(String(err));\n throw new NFError(\n `Could not locate the bundled node-loader at '@softarc/native-federation-orchestrator/node-loader/loader.mjs'. Ensure it is installed, and that its 'exports' map exposes this subpath: ${cause.message}`,\n cause\n );\n }\n};\n", "import type { ImportMap } from 'lib/core/1.domain';\nimport type { ImportMapConfig } from 'lib/core/2.app/config/import-map.contract';\nimport {\n getNodeLoaderClient,\n type NodeLoaderClient,\n type HostInstanceKeys,\n} from 'lib/node/adapters/node-loader.client';\n\ntype NodeImportMapConfig = ImportMapConfig & {\n nodeLoader: NodeLoaderClient;\n setHostInstancesFn: (keys: HostInstanceKeys) => Promise<HostInstanceKeys>;\n};\n\nconst useNodeImportMap = (): NodeImportMapConfig => {\n const nodeLoader = getNodeLoaderClient();\n return {\n nodeLoader,\n loadModuleFn: (url: string) => import(/* @vite-ignore */ url),\n setImportMapFn: (importMap: ImportMap) => nodeLoader.setMap(importMap).then(() => importMap),\n setHostInstancesFn: (keys: HostInstanceKeys) =>\n nodeLoader.setHostInstances(keys).then(() => keys),\n reloadBrowserFn: () => {\n /* no-op */\n },\n };\n};\n\nexport { useNodeImportMap };\n", "import type { HostOptions } from 'lib/core/2.app/config/host.contract';\nimport type { LogHandler } from 'lib/core/2.app/config/log.contract';\nimport type { ForProvidingRemoteEntries } from 'lib/core/2.app/driving-ports/for-providing-remote-entries.port';\n\n/** Specifier \u2192 module namespace object to bridge into remotes (the host's own instances). */\nexport type HostInstanceMap = Record<string, object>;\n\n/**\n * Auto-derive the bridged specifiers from the host remoteEntry's shared\n * singletons instead of listing them by hand. Each derived specifier is loaded\n * in the host realm (so the captured instance is the host's) and published.\n */\nexport type HostInstancesAuto = {\n /** Only bridge specifiers matching one of these (exact or prefix, e.g. `'@angular/'`). */\n include?: string[];\n /** Never bridge specifiers matching one of these (exact or prefix). */\n exclude?: string[];\n /**\n * How to load each instance. Default: `(s) => import(s)`.\n *\n * The default resolves wherever this library runs. Under a bundler-driven dev\n * server (e.g. Vite SSR) that may NOT be the realm holding the host's running\n * instance \u2014 pass a `load` defined in your own host entry so the import\n * resolves through the host's module graph and captures the real instance.\n */\n load?: (specifier: string) => Promise<object>;\n};\n\nexport type HostInstancesOption =\n /** Explicit map of specifier \u2192 already-loaded namespace. */\n | HostInstanceMap\n /** Auto-derive every shared singleton from the host remoteEntry. */\n | 'all'\n /** Auto-derive, filtered. */\n | HostInstancesAuto;\n\ntype Deps = {\n remoteEntryProvider: ForProvidingRemoteEntries;\n hostRemoteEntry: HostOptions['hostRemoteEntry'];\n log: LogHandler;\n};\n\n/** A pattern matches a specifier on exact equality or as a prefix. */\nconst matches = (specifier: string, patterns: string[]): boolean =>\n patterns.some(p => specifier === p || specifier.startsWith(p));\n\n/** Distinguish the auto forms (`'all'` / filter object) from an explicit map. */\nconst isAuto = (option: HostInstancesOption): option is 'all' | HostInstancesAuto =>\n option === 'all' ||\n (typeof option === 'object' &&\n option !== null &&\n ('include' in option || 'exclude' in option || 'load' in option));\n\n/**\n * Turn the `hostInstances` option into a concrete `{ specifier: namespace }` map.\n *\n * - Explicit map \u2192 returned as-is.\n * - `'all'` / `{ include, exclude }` \u2192 read the host remoteEntry's shared\n * singletons, apply the filter, and import each in the host realm.\n *\n * A specifier that fails to load is skipped with a warning rather than aborting\n * init \u2014 the remote falls back to import-map resolution for it (which is the\n * pre-bridge behaviour).\n */\nexport const resolveHostInstances = async (\n option: HostInstancesOption | undefined,\n deps: Deps\n): Promise<HostInstanceMap | undefined> => {\n if (!option) return undefined;\n if (!isAuto(option)) return option;\n\n const auto: HostInstancesAuto = option === 'all' ? {} : option;\n\n const { hostRemoteEntry } = deps;\n if (!hostRemoteEntry) {\n deps.log.warn(\n 0,\n '[native-federation] hostInstances auto mode needs a hostRemoteEntry to derive shared singletons from; skipping.'\n );\n return undefined;\n }\n\n const url = typeof hostRemoteEntry === 'string' ? hostRemoteEntry : hostRemoteEntry.url;\n const integrity = typeof hostRemoteEntry === 'string' ? undefined : hostRemoteEntry.integrity;\n const entry = await deps.remoteEntryProvider.provide(url, { integrity });\n\n const load = auto.load ?? ((specifier: string) => import(specifier));\n\n const specifiers = [\n ...new Set(\n (entry.shared ?? []).filter(s => s.singleton).flatMap(s => Object.keys(s.entries))\n ),\n ]\n .filter(s => (auto.include ? matches(s, auto.include) : true))\n .filter(s => (auto.exclude ? !matches(s, auto.exclude) : true));\n\n const map: HostInstanceMap = {};\n for (const specifier of specifiers) {\n try {\n map[specifier] = (await load(specifier)) as object;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n deps.log.warn(\n 0,\n `[native-federation] hostInstances: could not load '${specifier}' from the host realm; skipping (${msg})`\n );\n }\n }\n\n deps.log.debug(\n 0,\n `[native-federation] hostInstances bridged: ${Object.keys(map).join(', ') || '(none)'}`\n );\n return map;\n};\n", "import { pathToFileURL } from 'node:url';\nimport type { HostOptions } from 'lib/core/2.app/config/host.contract';\n\n/**\n * Coerce a Node-side string into a URL string. Anything that already starts\n * with a scheme (`http:`, `https:`, `file:`, `node:`, \u2026) passes through; a bare\n * filesystem path is converted to a `file://` URL via `pathToFileURL`.\n */\nconst URL_SCHEME = /^[a-z][a-z0-9+\\-.]*:/i;\n\nexport const toUrl = (pathOrUrl: string): string =>\n URL_SCHEME.test(pathOrUrl) ? pathOrUrl : pathToFileURL(pathOrUrl).href;\n\nexport const normalizeHostRemoteEntry = (\n hostRemoteEntry: HostOptions['hostRemoteEntry']\n): HostOptions['hostRemoteEntry'] => {\n if (!hostRemoteEntry) return hostRemoteEntry;\n if (typeof hostRemoteEntry === 'string') return toUrl(hostRemoteEntry);\n return { ...hostRemoteEntry, url: toUrl(hostRemoteEntry.url) };\n};\n", "import type { FederationManifest } from 'lib/core/1.domain';\nimport type { NFOptions, ConfigContract } from 'lib/core/2.app/config/config.contract';\nimport type { DrivingContract } from 'lib/core/2.app/driving-ports/driving.contract';\nimport type { NativeFederationResult } from 'lib/core/init-federation.contract';\n\nimport { createBrowser } from 'lib/core/3.adapters/browser/browser';\nimport { createVersionCheck } from 'lib/core/3.adapters/checks/version.check';\nimport { createFsManifestProvider } from './adapters/fs-manifest-provider';\nimport { createFsRemoteEntryProvider } from './adapters/fs-remote-entry-provider';\nimport { createNoopSSE } from './adapters/noop-sse';\nimport { createRemoteInfoRepository } from 'lib/core/3.adapters/storage/remote-info.repository';\nimport { createScopedExternalsRepository } from 'lib/core/3.adapters/storage/scoped-externals.repository';\nimport { createSharedExternalsRepository } from 'lib/core/3.adapters/storage/shared-externals.repository';\nimport { createChunkRepository } from 'lib/core/3.adapters/storage/chunk.repository';\n\nimport { createConfigHandlers } from 'lib/core/5.di/config.factory';\nimport { createInitFlow } from 'lib/core/2.app/flows/init.flow';\nimport { createInitRemoteEntryFlow } from 'lib/core/2.app/flows/init-remote-entry.flow';\nimport { INIT_FLOW_FACTORY } from 'lib/core/5.di/init.factory';\nimport {\n createFederationResult,\n createStateDump,\n} from 'lib/core/5.di/federation-result.factory';\nimport { useNodeImportMap } from './use-node';\nimport { resolveHostInstances, type HostInstancesOption } from './resolve-host-instances';\nimport { normalizeHostRemoteEntry } from './utils/to-url';\n\nexport type { HostInstancesOption, HostInstancesAuto } from './resolve-host-instances';\n\nexport type InitNodeFederationOptions = NFOptions & {\n /**\n * Bridge specifiers to instances already loaded in the host process (dev).\n *\n * The host's instances are published on `globalThis.__NF_HOST_INSTANCES__`\n * and the node loader synthesizes a re-export module for each specifier\n * instead of resolving it through the import map, so remotes share the host's\n * singletons. Three forms:\n *\n * - **Explicit map** \u2014 `{ '@angular/core': await import('@angular/core') }`.\n * - **`'all'`** \u2014 auto-derive every shared singleton from the host remoteEntry\n * and import each in the host realm. Needs `hostRemoteEntry`.\n * - **`{ include, exclude }`** \u2014 auto-derive, filtered by exact/prefix match,\n * e.g. `{ include: ['@angular/', 'rxjs', 'zone.js'] }`.\n *\n * This is an escape hatch that bypasses the version resolver, the import map,\n * and integrity checks entirely. Exports are value snapshots, not live\n * bindings \u2014 fine for packages whose exports are stable refs (Angular's\n * classes/functions), not for packages that reassign their exports after init.\n *\n * Omit in production: with no `hostInstances`, nothing is published and the\n * loader never routes to the bridge \u2014 resolution is import-map only.\n */\n hostInstances?: HostInstancesOption;\n};\n\n/** Global key the node loader reads at module-eval time on the main thread. */\nconst HOST_INSTANCES_GLOBAL = '__NF_HOST_INSTANCES__';\n\nconst buildNodeAdapters = (config: ConfigContract): DrivingContract => ({\n versionCheck: createVersionCheck(),\n manifestProvider: createFsManifestProvider(),\n remoteEntryProvider: createFsRemoteEntryProvider(config),\n remoteInfoRepo: createRemoteInfoRepository(config),\n scopedExternalsRepo: createScopedExternalsRepository(config),\n sharedExternalsRepo: createSharedExternalsRepository(config),\n sharedChunksRepo: createChunkRepository(config),\n browser: createBrowser(config),\n sse: createNoopSSE(),\n});\n\nconst initNodeFederation = (\n remotesOrManifestUrl: string | FederationManifest,\n options: InitNodeFederationOptions = {}\n): Promise<NativeFederationResult> => {\n const nodeConfig = useNodeImportMap();\n\n const hostRemoteEntry = normalizeHostRemoteEntry(options.hostRemoteEntry);\n\n const config = createConfigHandlers({\n ...options,\n hostRemoteEntry,\n loadModuleFn: options.loadModuleFn ?? nodeConfig.loadModuleFn,\n setImportMapFn: options.setImportMapFn ?? nodeConfig.setImportMapFn,\n reloadBrowserFn: options.reloadBrowserFn ?? nodeConfig.reloadBrowserFn,\n sse: false,\n });\n\n const adapters = buildNodeAdapters(config);\n\n // Host-instance bridge (dev): resolve the instance map (explicit, or\n // auto-derived from the host remoteEntry's shared singletons), publish it on\n // the global the loader reads, ship the export-key lists to the loader thread,\n // and wait for its ack before the init flow resolves any remote import. With\n // no hostInstances this is a no-op and resolution stays import-map only.\n const hostInstancesReady = (async () => {\n const instances = await resolveHostInstances(options.hostInstances, {\n remoteEntryProvider: adapters.remoteEntryProvider,\n hostRemoteEntry,\n log: config.log,\n });\n if (!instances || Object.keys(instances).length === 0) return;\n\n const globals = globalThis as Record<string, unknown>;\n globals[HOST_INSTANCES_GLOBAL] = {\n ...((globals[HOST_INSTANCES_GLOBAL] as Record<string, object> | undefined) ?? {}),\n ...instances,\n };\n const keys = Object.fromEntries(\n Object.entries(instances).map(([specifier, ns]) => [specifier, Object.keys(ns)])\n );\n await nodeConfig.setHostInstancesFn(keys);\n })();\n\n const factory = INIT_FLOW_FACTORY({ adapters, config });\n const initFlow = createInitFlow(factory);\n const initRemoteEntryFlow = createInitRemoteEntryFlow(factory);\n\n return hostInstancesReady\n .then(() => initFlow(remotesOrManifestUrl))\n .then(({ loadRemoteModule }) => nodeConfig.nodeLoader.ready().then(() => loadRemoteModule))\n .then(loadRemoteModule =>\n createFederationResult({\n config,\n adapters,\n loadRemoteModule,\n initRemoteEntryFlow,\n afterInitRemoteEntry: () => nodeConfig.nodeLoader.ready(),\n })\n )\n .catch(e => {\n createStateDump(config, adapters)(`[init] STATE DUMP`);\n return Promise.reject(e);\n });\n};\n\nexport { initNodeFederation };\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,QACJ,OAAO,YAAY,YACnB,QAAQ,OACR,QAAQ,IAAI,cACZ,cAAc,KAAK,QAAQ,IAAI,UAAU,IACvC,IAAI,SAAS,QAAQ,MAAM,UAAU,GAAG,IAAI,IAC5C,MAAM;AAAA,IAAC;AAEX,WAAO,UAAU;AAAA;AAAA;;;ACVjB;AAAA;AAAA;AAIA,QAAM,sBAAsB;AAE5B,QAAM,aAAa;AACnB,QAAM,mBAAmB,OAAO;AAAA,IACL;AAG3B,QAAM,4BAA4B;AAIlC,QAAM,wBAAwB,aAAa;AAE3C,QAAM,gBAAgB;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,WAAO,UAAU;AAAA,MACf;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,yBAAyB;AAAA,MACzB,YAAY;AAAA,IACd;AAAA;AAAA;;;ACpCA;AAAA;AAAA;AAEA,QAAM;AAAA,MACJ;A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,CAAC;AAAA,EACH,EACC,MAAM,OAAK;AACV,oBAAgB,QAAQ,QAAQ,EAAE,mBAAmB;AACrD,WAAO,QAAQ,OAAO,CAAC;AAAA,EACzB,CAAC;AACL;",
6
- "names": ["SemVer", "SemVer", "SemVer", "SemVer", "cached", "SemVer", "SemVer", "require_valid", "import_valid", "SemVer", "semverValid", "semverSatisfies", "semverValidRange", "semverMinVersion", "importMap", "cached", "missOf", "byTag", "toll", "getScope", "cached", "runsOffMap", "rank", "require", "pathToFileURL"]
3
+ "sources": ["../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/debug.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/constants.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/re.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/parse-options.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/identifiers.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/classes/semver.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/parse.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/valid.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/lrucache.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/compare.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/eq.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/neq.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/gt.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/gte.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/lt.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/lte.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/cmp.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/classes/comparator.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/internal/trim-comparator-whitespace.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/classes/range.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/functions/satisfies.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/ranges/min-version.js", "../../node_modules/.pnpm/semver@7.8.6/node_modules/semver/ranges/valid.js", "../../src/lib/core/3.adapters/browser/browser.ts", "../../src/lib/core/3.adapters/checks/version.check.ts", "../../src/lib/core/native-federation.error.ts", "../../src/lib/utils/integrity.ts", "../../src/lib/node/utils/read-source.ts", "../../src/lib/node/adapters/fs-manifest-provider.ts", "../../src/lib/core/1.domain/remote-entry/mark-dense.ts", "../../node_modules/.pnpm/@softarc+native-federation@4.10.0/node_modules/@softarc/native-federation/dist/lib/domain/core/chunk.js", "../../node_modules/.pnpm/@softarc+native-federation@4.10.0/node_modules/@softarc/native-federation/dist/lib/utils/normalize.js", "../../node_modules/.pnpm/@softarc+native-federation@4.10.0/node_modules/@softarc/native-federation/dist/lib/core/output/densify-externals.js", "../../src/lib/core/3.adapters/remote-entry/normalize-remote-entry.ts", "../../src/lib/node/adapters/fs-remote-entry-provider.ts", "../../src/lib/node/adapters/noop-sse.ts", "../../src/lib/core/2.app/config/storage.contract.ts", "../../src/lib/utils/path.ts", "../../src/lib/utils/optional.ts", "../../src/lib/core/3.adapters/storage/remote-info.repository.ts", "../../src/lib/core/3.adapters/storage/scoped-externals.repository.ts", "../../src/lib/core/1.domain/externals/external.contract.ts", "../../src/lib/core/3.adapters/storage/cache-state.ts", "../../src/lib/core/3.adapters/storage/shared-externals.repository.ts", "../../src/lib/core/3.adapters/storage/chunk.repository.ts", "../../src/lib/core/4.config/import-map/trusted-types.ts", "../../src/lib/core/4.config/import-map/replace-in-dom.ts", "../../src/lib/core/4.config/import-map/preload-in-dom.ts", "../../src/lib/core/4.config/import-map/use-default.ts", "../../src/lib/core/4.config/import-map/no-preload.ts", "../../src/lib/core/4.config/import-map/import-map.config.ts", "../../src/lib/core/4.config/host/host.config.ts", "../../src/lib/core/4.config/logging/noop.logger.ts", "../../src/lib/core/2.app/config/log.contract.ts", "../../src/lib/core/4.config/logging/log.handler.ts", "../../src/lib/core/4.config/logging/log.config.ts", "../../src/lib/utils/clone-entry.ts", "../../src/lib/core/4.config/storage/global-this.storage.ts", "../../src/lib/core/4.config/orchestrator-version.ts", "../../src/lib/core/4.config/storage/publish-storage-info.ts", "../../src/lib/core/4.config/storage/storage.config.ts", "../../src/lib/core/4.config/mode/default.profile.ts", "../../src/lib/core/4.config/mode/mode.config.ts", "../../src/lib/core/5.di/config.factory.ts", "../../src/lib/core/2.app/flows/init.flow.ts", "../../src/lib/core/2.app/flows/init-remote-entry.flow.ts", "../../src/lib/core/2.app/steps/store-remote-entry.ts", "../../src/lib/core/2.app/steps/get-remote-entries.ts", "../../src/lib/utils/compare-strings.ts", "../../src/lib/core/1.domain/externals/basis.ts", "../../src/lib/core/1.domain/externals/rows.ts", "../../src/lib/core/2.app/steps/process-remote-entries.ts", "../../src/lib/core/1.domain/externals/compatibility.ts", "../../src/lib/core/2.app/steps/apply-winner.ts", "../../src/lib/core/2.app/steps/determine-shared-externals.ts", "../../src/lib/utils/union-find.ts", "../../src/lib/core/1.domain/externals/specifier.ts", "../../src/lib/core/1.domain/pooling/builds.ts", "../../src/lib/core/1.domain/pooling/rules.ts", "../../src/lib/core/1.domain/pooling/election.ts", "../../src/lib/core/1.domain/pooling/membership.ts", "../../src/lib/core/1.domain/pooling/pool-state.ts", "../../src/lib/core/1.domain/pooling/records.ts", "../../src/lib/core/1.domain/pooling/plan.ts", "../../src/lib/core/2.app/steps/pooling/pool-shared-externals.ts", "../../src/lib/core/1.domain/externals/serving.ts", "../../src/lib/core/2.app/steps/decide-serving-builds.ts", "../../src/lib/core/1.domain/externals/claims.ts", "../../src/lib/core/2.app/steps/generate-import-map.ts", "../../src/lib/core/2.app/steps/preload-hint.ts", "../../src/lib/core/1.domain/import-map/eager-preloads.ts", "../../src/lib/core/2.app/steps/collect-eager-preloads.ts", "../../src/lib/core/2.app/steps/commit-changes.ts", "../../src/lib/core/2.app/steps/rollback-changes.ts", "../../src/lib/core/2.app/steps/expose-module-loader.ts", "../../src/lib/core/2.app/steps/get-remote-entry.ts", "../../src/lib/core/2.app/steps/update-cache.ts", "../../src/lib/core/1.domain/pooling/gate.ts", "../../src/lib/core/2.app/steps/pooling/pool-dynamic-externals.ts", "../../src/lib/core/2.app/steps/convert-to-import-map.ts", "../../src/lib/core/5.di/init.factory.ts", "../../src/lib/core/5.di/federation-result.factory.ts", "../../src/lib/node/adapters/node-loader.client.ts", "../../src/lib/node/adapters/loader-url.ts", "../../src/lib/node/use-node.ts", "../../src/lib/node/resolve-host-instances.ts", "../../src/lib/node/utils/to-url.ts", "../../src/lib/node/init-federation.node.ts"],
4
+ "sourcesContent": ["'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\n// ECMAScript whitespace and line terminators matched by \\s.\nconst WHITESPACE_CHARACTERS = [\n '\\t',\n '\\n',\n '\\v',\n '\\f',\n '\\r',\n ' ',\n '\\u00a0',\n '\\u1680',\n '\\u2000',\n '\\u2001',\n '\\u2002',\n '\\u2003',\n '\\u2004',\n '\\u2005',\n '\\u2006',\n '\\u2007',\n '\\u2008',\n '\\u2009',\n '\\u200a',\n '\\u2028',\n '\\u2029',\n '\\u202f',\n '\\u205f',\n '\\u3000',\n '\\ufeff',\n]\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n WHITESPACE_CHARACTERS,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n const identifiers = identifier.split('.')\n if (identifiers.length > prerelease.length) {\n return false\n }\n\n for (let i = 0; i < identifiers.length; i++) {\n if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n return false\n }\n }\n\n return true\n}\n\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n const prereleaseBase = this.prerelease[identifier.split('.').length]\n if (isNaN(prereleaseBase)) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "// @ts-check\n'use strict'\n\n// Reproduce safeRe[COMPARATORTRIM] replacement boundaries, not version\n// validation. Each end-index finder returns an exclusive end, or its start\n// on no match.\n// Positions count from zero. An end of 3 means characters 0, 1, and 2 were read;\n// range.slice(start, end) gives the matched text, not a converted number.\nconst {\n MAX_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n WHITESPACE_CHARACTERS,\n} = require('./constants')\n\n/**\n * Remembers the last two rows of digits so their characters need not be reread.\n * Positions start at -1 until a row has been found.\n *\n * @typedef {object} DigitRunCache\n * @property {number} start The first character of the most recently found row.\n * @property {number} end The position after that row's last character.\n * @property {number} previousStart The first character of the previous row.\n * @property {number} previousEnd The position after the previous row.\n */\n\n// One entry per UTF-16 code unit keeps membership checks constant-time.\nconst whitespace = new Uint8Array(0x10000)\nfor (const char of WHITESPACE_CHARACTERS) {\n whitespace[char.charCodeAt(0)] = 1\n}\n\n/**\n * Checks whether a character is whitespace, like a space, tab, or newline.\n * Looking past the end of the string returns false.\n *\n * @param {string|undefined} char One character, or undefined past the string's end.\n * @returns {boolean} Whether the character is whitespace.\n * @example isWhitespace(' ') // true\n * @example isWhitespace('1') // false\n */\nconst isWhitespace = char =>\n char !== undefined && whitespace[char.charCodeAt(0)] === 1\n\n/**\n * Checks for v, =, or whitespace before the version number.\n * These are historical version prefixes, not range operators:\n * < and > are handled separately, as are tilde and caret ranges.\n *\n * @param {string|undefined} char One character to check.\n * @returns {boolean} Whether the character can belong to a version prefix.\n * @example isVersionPrefix('=') // true\n * @example isVersionPrefix('>') // false\n */\nconst isVersionPrefix = char =>\n char === 'v' ||\n char === '=' ||\n isWhitespace(char)\n\n/**\n * Checks whether a character is one of the digits 0 through 9.\n *\n * @param {string|undefined} char One character to check.\n * @returns {boolean} Whether the character is an ASCII digit.\n * @example isDigit('7') // true\n * @example isDigit('.') // false\n */\nconst isDigit = char => char !== undefined && char >= '0' && char <= '9'\n\n/**\n * Checks whether a character is an English letter, uppercase or lowercase.\n *\n * @param {string|undefined} char One character to check.\n * @returns {boolean} Whether the character is an ASCII letter.\n * @example isLetter('b') // true\n * @example isLetter('7') // false\n */\nconst isLetter = char =>\n char !== undefined && (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z')\n )\n\n/**\n * Checks for a letter, digit, or hyphen: the characters allowed inside\n * prerelease and build names such as beta-1.\n *\n * @param {string|undefined} char One character to check.\n * @returns {boolean} Whether the character can be part of an identifier.\n * @example isIdentifierCharacter('-') // true\n * @example isIdentifierCharacter('.') // false; dots separate identifiers\n */\nconst isIdentifierCharacter = char => isDigit(char) || isLetter(char) || char === '-'\n\n/**\n * Checks whether a version component can begin here: with a digit or\n * a wildcard such as x, X, or *.\n *\n * @param {string|undefined} char One character to check.\n * @returns {boolean} Whether a number or wildcard can start with this character.\n * @example isVersionStart('x') // true\n * @example isVersionStart('v') // false; v belongs to the prefix\n */\nconst isVersionStart = char =>\n isDigit(char) ||\n char === 'x' ||\n char === 'X' ||\n char === '*'\n\n/**\n * Finds the end of a row of digits, but returns no more than limit digits.\n * Remembers the last two rows so looking at them again does not reread them.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position of the first character to check.\n * @param {number} limit The most digit characters the returned match can include.\n * @param {DigitRunCache} digitRuns Shared cache of digit-run positions, updated in place.\n * @returns {number} The position after the matched digits, or start if none match.\n * @example findDigitsEndIndex('123abc', 0, 10, digitRuns) // 3, pointing at a\n * @example findDigitsEndIndex('123abc', 0, 2, digitRuns) // 2, pointing at the unread 3\n */\nconst findDigitsEndIndex = (range, start, limit, digitRuns) => {\n if (!isDigit(range[start])) {\n return start\n }\n if (start >= digitRuns.start && start < digitRuns.end) {\n return Math.min(start + limit, digitRuns.end)\n }\n if (start >= digitRuns.previousStart && start < digitRuns.previousEnd) {\n return Math.min(start + limit, digitRuns.previousEnd)\n }\n let end = start + 1\n while (isDigit(range[end])) {\n end++\n }\n // A failed full version can rewind from its second run to its first.\n digitRuns.previousStart = digitRuns.start\n digitRuns.previousEnd = digitRuns.end\n digitRuns.start = start\n digitRuns.end = end\n return Math.min(start + limit, end)\n}\n\n/**\n * Reads a number using the old regex's length and leading-zero rules.\n * Strict mode reads just the first zero in 012; loose mode can read all three.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position where the number should begin.\n * @param {boolean} loose Whether to allow leading zeros.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position after the matched digits, not their numeric value.\n * @example findVersionNumberEndIndex('012', 0, false, digitRuns) // 1\n * @example findVersionNumberEndIndex('012', 0, true, digitRuns) // 3\n */\nconst findVersionNumberEndIndex = (range, start, loose, digitRuns) => {\n if (!loose && range[start] === '0') {\n return start + 1\n }\n // Strict syntax allows an initial nonzero digit plus MAX_LENGTH digits.\n return findDigitsEndIndex(range, start, loose ? MAX_LENGTH : MAX_LENGTH + 1, digitRuns)\n}\n\n/**\n * Reads one piece of a prerelease name, such as beta or 1 in beta.1.\n * Tries the letter-or-hyphen form first, then the number-only form.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position where the identifier should begin.\n * @param {boolean} loose Whether numeric identifiers may have leading zeros.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position after the identifier, or start if none matches.\n * @example findPrereleaseIdentifierEndIndex('beta.1', 0, false, digitRuns) // 4, at the dot\n * @example findPrereleaseIdentifierEndIndex('001beta', 0, false, digitRuns) // 7\n */\nconst findPrereleaseIdentifierEndIndex = (range, start, loose, digitRuns) => {\n const digitsEnd = findDigitsEndIndex(range, start, MAX_LENGTH, digitRuns)\n // The legacy regex tries a nonnumeric identifier before a numeric one.\n if (isLetter(range[digitsEnd]) || range[digitsEnd] === '-') {\n let end = digitsEnd + 1\n const limit = end + MAX_SAFE_BUILD_LENGTH\n while (end < limit && isIdentifierCharacter(range[end])) {\n end++\n }\n return end\n }\n return findVersionNumberEndIndex(range, start, loose, digitRuns)\n}\n\n/**\n * Reads a prerelease suffix such as -beta.1, one dot-separated piece at a time.\n * Loose mode also allows the name without its opening hyphen.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position where the suffix should begin, including -.\n * @param {boolean} loose Whether the opening hyphen is optional and zeros allowed.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position after the matched suffix, or start if absent.\n * @example findPrereleaseEndIndex('-beta.1+sha', 0, false, digitRuns) // 7, at the plus\n * @example findPrereleaseEndIndex('beta', 0, false, digitRuns) // 0; no opening hyphen\n */\nconst findPrereleaseEndIndex = (range, start, loose, digitRuns) => {\n const hyphen = range[start] === '-'\n if (!loose && !hyphen) {\n return start\n }\n const identifierStart = start + (hyphen ? 1 : 0)\n let end = findPrereleaseIdentifierEndIndex(range, identifierStart, loose, digitRuns)\n if (end === identifierStart) {\n if (!loose || !hyphen) {\n return start\n }\n // In loose syntax, a lone hyphen can itself be the identifier.\n end = findPrereleaseIdentifierEndIndex(range, start, loose, digitRuns)\n }\n while (range[end] === '.') {\n const next = findPrereleaseIdentifierEndIndex(range, end + 1, loose, digitRuns)\n if (next === end + 1) {\n break\n }\n end = next\n }\n return end\n}\n\n/**\n * Reads one build-name piece, such as sha or 123 in +sha.123.\n * Stops at a disallowed character or the old regex's length limit.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position where the identifier should begin.\n * @returns {number} The position after the identifier, or start if none matches.\n * @example findBuildIdentifierEndIndex('sha.123', 0) // 3, at the dot\n * @example findBuildIdentifierEndIndex('001', 0) // 3; leading zeros are allowed\n */\nconst findBuildIdentifierEndIndex = (range, start) => {\n let end = start\n while (end - start < MAX_SAFE_BUILD_LENGTH && isIdentifierCharacter(range[end])) {\n end++\n }\n return end\n}\n\n/**\n * Reads optional build metadata such as +sha.123.\n * Leaves the position unchanged if there is no plus sign followed by a name.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position where the opening + should be.\n * @returns {number} The position after the matched metadata, or start if absent.\n * @example findBuildEndIndex('+sha.123 <2', 0) // 8, at the space\n * @example findBuildEndIndex('+', 0) // 0; a plus sign alone is not a match\n */\nconst findBuildEndIndex = (range, start) => {\n if (range[start] !== '+') {\n return start\n }\n let end = findBuildIdentifierEndIndex(range, start + 1)\n if (end === start + 1) {\n return start\n }\n while (range[end] === '.') {\n const next = findBuildIdentifierEndIndex(range, end + 1)\n if (next === end + 1) {\n break\n }\n end = next\n }\n return end\n}\n\n/**\n * Reads three numbers separated by dots, then any prerelease and build suffixes.\n * Uses loose rules, so forms such as 01.02.03beta can match here.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position of the first number, after any prefix.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position after the version match, or start if none matches.\n * @example findLooseFullVersionEndIndex('1.2.3-beta+sha <2', 0, digitRuns) // 14\n * @example findLooseFullVersionEndIndex('1.2', 0, digitRuns) // 0; needs three numbers\n */\nconst findLooseFullVersionEndIndex = (range, start, digitRuns) => {\n let end = start\n for (let component = 0; component < 3; component++) {\n const next = findVersionNumberEndIndex(range, end, true, digitRuns)\n if (next === end) {\n return start\n }\n end = next\n if (component < 2) {\n if (range[end] !== '.') {\n return start\n }\n end++\n }\n }\n const prereleaseEnd = findPrereleaseEndIndex(range, end, true, digitRuns)\n return findBuildEndIndex(range, prereleaseEnd)\n}\n\n/**\n * Reads one component of a partial or wildcard version, such as 2 or x in 2.x.\n * Numbers use strict leading-zero rules; wildcards take up one character.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position where the component should begin.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position after the component, or start if none matches.\n * @example findPartialVersionComponentEndIndex('2.x', 0, digitRuns) // 1, at the dot\n * @example findPartialVersionComponentEndIndex('2.x', 2, digitRuns) // 3, after x\n */\nconst findPartialVersionComponentEndIndex = (range, start, digitRuns) => {\n if (isDigit(range[start])) {\n return findVersionNumberEndIndex(range, start, false, digitRuns)\n }\n return isVersionStart(range[start]) ? start + 1 : start\n}\n\n/**\n * Reads up to three components, allowing forms such as 1, 1.2, or 1.x.\n * After the third component, also reads any strict prerelease and build suffixes.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position of a number or wildcard, after any prefix.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position after the matched version text.\n * @example findPartialVersionEndIndex('1.x <2', 0, digitRuns) // 3, at the space\n * @example findPartialVersionEndIndex('1.', 0, digitRuns) // 1; the trailing dot is unread\n */\nconst findPartialVersionEndIndex = (range, start, digitRuns) => {\n let end = findPartialVersionComponentEndIndex(range, start, digitRuns)\n for (let component = 0; component < 2; component++) {\n if (range[end] !== '.') {\n return end\n }\n const next = findPartialVersionComponentEndIndex(range, end + 1, digitRuns)\n if (next === end + 1) {\n return end\n }\n end = next\n }\n const prereleaseEnd = findPrereleaseEndIndex(range, end, false, digitRuns)\n return findBuildEndIndex(range, prereleaseEnd)\n}\n\n/**\n * Finds where a version match ends, without deciding whether the range is valid.\n * Tries a loose full version first, then a partial or wildcard version, just\n * like the old regex's LOOSEPLAIN and XRANGEPLAIN alternatives.\n *\n * @param {string} range The text to read; it is not changed.\n * @param {number} start The position of a number or wildcard, after any prefix.\n * @param {DigitRunCache} digitRuns Shared digit-run cache, updated as needed.\n * @returns {number} The position where scanning the next candidate can resume.\n * @example findVersionEndIndex('1.2.3 <2', 0, digitRuns) // 5, at the space\n * @example findVersionEndIndex('1.x <2', 0, digitRuns) // 3, at the space\n */\nconst findVersionEndIndex = (range, start, digitRuns) => {\n const fullVersionEnd = findLooseFullVersionEndIndex(range, start, digitRuns)\n return fullVersionEnd !== start\n ? fullVersionEnd\n : findPartialVersionEndIndex(range, start, digitRuns)\n}\n\n/**\n * Finds the one whitespace character the old replacement would remove.\n * Keeps leading whitespace, skips an optional operator, and checks immediately\n * after it. Returns -1 if there is nothing to remove.\n *\n * @param {string} range The text containing a candidate already found by the caller.\n * @param {number} matchStart The candidate's position, including leading whitespace.\n * @returns {number} The position of the removable whitespace, or -1 if absent.\n * @example findRemovableWhitespaceIndex(' > 1', 0) // 2; keep the space at position 0\n * @example findRemovableWhitespaceIndex('>1', 0) // -1\n */\nconst findRemovableWhitespaceIndex = (range, matchStart) => {\n let position = matchStart\n if (isWhitespace(range[position])) {\n position++\n }\n if (range[position] === '<' || range[position] === '>') {\n position++\n }\n if (range[position] === '=') {\n position++\n }\n return isWhitespace(range[position]) ? position : -1\n}\n\n/**\n * Joins an operator to its version, turning > 1.2.3 into >1.2.3.\n * Copies everything else according to the old regex's matching rules.\n * Moves forward through prefixes and whole versions to avoid repeatedly\n * searching the same characters on long inputs.\n *\n * @param {string} range The range text to process; the original string is unchanged.\n * @returns {string} The range with matched operator whitespace removed.\n * @example trimComparatorWhitespace('> 1.2.3 < 2') // '>1.2.3 <2'\n * @example trimComparatorWhitespace('> invalid') // '> invalid'\n */\nconst trimComparatorWhitespace = range => {\n let result = ''\n let copyFrom = 0\n let cursor = 0\n const digitRuns = { start: -1, end: -1, previousStart: -1, previousEnd: -1 }\n\n while (cursor < range.length) {\n const matchStart = cursor\n if (range[cursor] === '<' || range[cursor] === '>') {\n cursor++\n } else if (!isVersionPrefix(range[cursor]) && !isVersionStart(range[cursor])) {\n cursor++\n continue\n }\n\n // Consume a v/=/whitespace run once, even when no version follows it.\n while (cursor < range.length && isVersionPrefix(range[cursor])) {\n cursor++\n }\n if (!isVersionStart(range[cursor])) {\n continue\n }\n\n const whitespacePosition = findRemovableWhitespaceIndex(range, matchStart)\n if (whitespacePosition !== -1) {\n result += range.slice(copyFrom, whitespacePosition)\n copyFrom = whitespacePosition + 1\n }\n\n // Skip the entire match, so a prerelease's trailing v cannot be\n // reconsidered as the prefix of another version.\n cursor = findVersionEndIndex(range, cursor, digitRuns)\n }\n\n return result + range.slice(copyFrom)\n}\n\nmodule.exports = trimComparatorWhitespace\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // strip build metadata so it can't bleed into the version\n range = range.replace(BUILDSTRIPRE, '')\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = trimComparatorWhitespace(range)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst trimComparatorWhitespace = require('../internal/trim-comparator-whitespace')\nconst {\n safeRe: re,\n src,\n t,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n (isX(M) && !isX(m)) ||\n (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n // if we're including prereleases in the match, then the lower bound is\n // -0, the lowest possible prerelease value, just like x-ranges and carets.\n // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n if (invalidXRangeOrder(M, m, p)) {\n return comp\n }\n\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n", "import type { ForBrowserTasks } from 'lib/core/2.app/driving-ports/for-browser-tasks';\nimport type { ImportMapConfig } from 'lib/core/2.app/config/import-map.contract';\n\nconst createBrowser = (config: ImportMapConfig): ForBrowserTasks => {\n return {\n setImportMapFn: config.setImportMapFn,\n importModule: config.loadModuleFn,\n preloadModules: config.preloadModulesFn,\n };\n};\n\nexport { createBrowser };\n", "import type { ForVersionChecking } from 'lib/core/2.app/driving-ports/for-version-checking.port';\nimport semverValid from 'semver/functions/valid';\nimport semverSatisfies from 'semver/functions/satisfies';\nimport SemVer from 'semver/classes/semver';\nimport semverMinVersion from 'semver/ranges/min-version';\nimport semverValidRange from 'semver/ranges/valid';\n\nconst createVersionCheck = (): ForVersionChecking => {\n const parsed = new Map<string, SemVer>();\n const parse = (v: string) => {\n let hit = parsed.get(v);\n if (!hit) parsed.set(v, (hit = new SemVer(v, true)));\n return hit;\n };\n const satisfied = new Map<string, Map<string, boolean>>();\n return {\n isValidSemver: function (version: string) {\n return semverValid(version) !== null;\n },\n isCompatible: function (version: string, range: string) {\n let byVersion = satisfied.get(range);\n if (!byVersion) satisfied.set(range, (byVersion = new Map()));\n let hit = byVersion.get(version);\n if (hit === undefined) byVersion.set(version, (hit = semverSatisfies(version, range)));\n return hit;\n },\n compare: function (versionA: string, versionB: string) {\n return parse(versionA).compare(parse(versionB));\n },\n smallestVersion: function (versionRange: string) {\n if (!semverValidRange(versionRange)) return '0.0.0';\n const minVersion = semverMinVersion(versionRange);\n return minVersion?.raw ?? '0.0.0';\n },\n };\n};\n\nexport { createVersionCheck };\n", "class NFError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause ? { cause } : undefined);\n this.name = 'NFError';\n }\n}\n\nexport { NFError };\n", "const SUPPORTED_ALGORITHMS = {\n 'sha256-': 'SHA-256',\n 'sha384-': 'SHA-384',\n 'sha512-': 'SHA-512',\n} as const;\n\ntype Prefix = keyof typeof SUPPORTED_ALGORITHMS;\n\nconst parseIntegrity = (integrity: string): { algorithm: string; expected: string } | null => {\n for (const prefix of Object.keys(SUPPORTED_ALGORITHMS) as Prefix[]) {\n if (integrity.startsWith(prefix)) {\n return { algorithm: SUPPORTED_ALGORITHMS[prefix], expected: integrity };\n }\n }\n return null;\n};\n\nconst toBase64 = (bytes: ArrayBuffer): string => {\n const view = new Uint8Array(bytes);\n let bin = '';\n for (let i = 0; i < view.length; i++) bin += String.fromCharCode(view[i]!);\n return btoa(bin);\n};\n\nexport const verifyIntegrity = async (bytes: ArrayBuffer, integrity: string): Promise<void> => {\n const parsed = parseIntegrity(integrity);\n if (!parsed) {\n throw new TypeError(\n `Unsupported integrity prefix in '${integrity}'. Expected sha256-, sha384-, or sha512-.`\n );\n }\n\n const subtle =\n typeof crypto !== 'undefined' && crypto.subtle ? crypto.subtle : undefined;\n if (!subtle) {\n throw new Error('SubtleCrypto is not available in this environment.');\n }\n\n const digest = await subtle.digest(parsed.algorithm, bytes);\n const actual =\n integrity.substring(0, integrity.indexOf('-') + 1) + toBase64(digest);\n\n if (actual !== parsed.expected) {\n throw new Error(`Integrity mismatch: expected ${parsed.expected}, got ${actual}`);\n }\n};\n", "import * as fs from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport { NFError } from 'lib/core/native-federation.error';\n\nconst isHttpUrl = (input: string): boolean =>\n input.startsWith('http://') || input.startsWith('https://');\n\nconst isFileUrl = (input: string): boolean => input.startsWith('file://');\n\nexport const readSourceBytes = async (input: string): Promise<ArrayBuffer> => {\n if (isHttpUrl(input)) {\n const response = await fetch(input);\n if (!response.ok) {\n throw new NFError(`${response.status} - ${response.statusText}`);\n }\n return response.arrayBuffer();\n }\n\n const path = isFileUrl(input) ? fileURLToPath(input) : input;\n const buffer = await fs.readFile(path);\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n};\n", "import type { FederationManifest } from 'lib/core/1.domain';\nimport type { ForProvidingManifest } from 'lib/core/2.app/driving-ports/for-providing-manifest.port';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { verifyIntegrity } from 'lib/utils/integrity';\nimport { readSourceBytes } from 'lib/node/utils/read-source';\n\nconst createFsManifestProvider = (): ForProvidingManifest => {\n const formatError = (manifestUrl: string) => (err: unknown) => {\n if (err instanceof NFError) throw err;\n const msg = err instanceof Error ? err.message : String(err);\n throw new NFError(`Read of '${manifestUrl}' returned ${msg}`);\n };\n\n return {\n provide: async function (\n remotesOrManifestUrl: string | FederationManifest,\n opts: { integrity?: string } = {}\n ) {\n if (typeof remotesOrManifestUrl !== 'string') return remotesOrManifestUrl;\n\n try {\n const bytes = await readSourceBytes(remotesOrManifestUrl);\n if (opts.integrity) await verifyIntegrity(bytes, opts.integrity);\n return JSON.parse(new TextDecoder().decode(bytes)) as FederationManifest;\n } catch (err) {\n return formatError(remotesOrManifestUrl)(err);\n }\n },\n };\n};\n\nexport { createFsManifestProvider };\n", "import type { DenseSharedInfo, RemoteSharedInfo, SharedInfo } from './remote-entry.contract';\n\n// Runs on the raw `shared` array: normalizing wraps a flat entry into the dense shape, after which the two\n// can't be told apart.\nexport function markDense(\n shared: (SharedInfo | DenseSharedInfo)[]\n): (SharedInfo | RemoteSharedInfo)[] {\n return shared.map(entry => ('entries' in entry ? { ...entry, dense: true } : entry));\n}\n", "const CHUNK_PREFIX = \"@nf-internal\";\nconst SCRIPT_EXTENSION = /\\.(m|c)?js$/;\nfunction toChunkImport(fileName) {\n if (fileName.startsWith(\"./\")) {\n fileName = fileName.slice(2);\n }\n const packageName = fileName.replace(SCRIPT_EXTENSION, \"\");\n return CHUNK_PREFIX + \"/\" + packageName;\n}\nexport {\n CHUNK_PREFIX,\n SCRIPT_EXTENSION,\n toChunkImport\n};\n", "import { toPosix } from \"./path-patterns.js\";\nfunction normalize(path, trailingSlash) {\n let cand = toPosix(path);\n if (typeof trailingSlash === \"undefined\") {\n return cand;\n }\n while (cand.endsWith(\"/\")) {\n cand = cand.substring(0, cand.length - 1);\n }\n if (trailingSlash) {\n return cand + \"/\";\n }\n return cand;\n}\nfunction normalizePackageName(fileName) {\n const sanitized = fileName.replace(/[^A-Za-z0-9]/g, \"_\");\n return sanitized.startsWith(\"_\") ? sanitized.slice(1) : sanitized;\n}\nfunction inferPackageFromSecondary(secondary) {\n const parts = secondary.split(\"/\");\n if (secondary.startsWith(\"@\") && parts.length >= 2) {\n return parts[0] + \"/\" + parts[1];\n }\n return parts[0];\n}\nfunction sharedBundlePackage(key, build) {\n return build === \"separate\" ? key : inferPackageFromSecondary(key);\n}\nfunction sharedBundleName(platform, packageName) {\n return `${platform}-${normalizePackageName(packageName)}`;\n}\nexport {\n inferPackageFromSecondary,\n normalize,\n normalizePackageName,\n sharedBundleName,\n sharedBundlePackage\n};\n", "import { CHUNK_PREFIX } from \"../../domain/core/chunk.js\";\nimport { inferPackageFromSecondary } from \"../../utils/normalize.js\";\nfunction isDense(entry) {\n return \"entries\" in entry;\n}\nfunction isFlatChunk(entry) {\n return entry.packageName.startsWith(CHUNK_PREFIX);\n}\nfunction densifyExternals(shared, declaredPackages) {\n const result = [];\n const groupIndex = /* @__PURE__ */ new Map();\n for (const entry of shared) {\n if (isDense(entry)) {\n result.push(entry);\n continue;\n }\n if (isFlatChunk(entry)) {\n const { outFileName: outFileName2, ...rest } = entry;\n result.push({ ...rest, entries: { [entry.packageName]: outFileName2 } });\n continue;\n }\n const { outFileName, packageName, dev, ...meta } = entry;\n const parent = declaredPackages.get(packageName) ?? inferPackageFromSecondary(packageName);\n const sig = JSON.stringify(meta, Object.keys(meta).sort());\n const key = parent + \" \" + sig;\n const existing = groupIndex.get(key);\n if (existing === void 0) {\n const dense = {\n ...meta,\n packageName: parent,\n entries: { [packageName]: outFileName }\n };\n if (dev !== void 0) dense.dev = dev;\n groupIndex.set(key, result.length);\n result.push(dense);\n } else {\n result[existing].entries[packageName] = outFileName;\n }\n }\n return result;\n}\nfunction toDenseSharedInfoFormat(shared) {\n return shared.map((external) => {\n if (\"entries\" in external) return external;\n const { outFileName, ...baseSharedInfoProps } = external;\n return {\n ...baseSharedInfoProps,\n entries: { [external.packageName]: outFileName }\n };\n });\n}\nexport {\n densifyExternals,\n toDenseSharedInfoFormat\n};\n", "import type {\n RawRemoteEntry,\n RemoteEntry,\n} from 'lib/core/1.domain/remote-entry/remote-entry.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { markDense } from 'lib/core/1.domain/remote-entry/mark-dense';\nimport {\n densifyExternals,\n toDenseSharedInfoFormat,\n} from '@softarc/native-federation/internal/browser';\n\nconst normalizeRemoteEntry = (\n raw: RawRemoteEntry,\n remoteEntryUrl: string,\n config: ModeConfig\n): RemoteEntry => {\n const marked = markDense(raw.shared ?? []);\n // Flat entries carry no package declaration, so densifying groups them by npm name.\n const shared = config.feature.convertFlatSharedInfo\n ? densifyExternals(marked, new Map())\n : toDenseSharedInfoFormat(marked);\n const remoteEntry = { ...raw, shared } as RemoteEntry;\n if (!remoteEntry.exposes) remoteEntry.exposes = [];\n if (!remoteEntry.url) remoteEntry.url = remoteEntryUrl;\n return remoteEntry;\n};\n\nexport { normalizeRemoteEntry };\n", "import type { RawRemoteEntry } from 'lib/core/1.domain/remote-entry/remote-entry.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { normalizeRemoteEntry } from 'lib/core/3.adapters/remote-entry/normalize-remote-entry';\nimport type { ForProvidingRemoteEntries } from 'lib/core/2.app/driving-ports/for-providing-remote-entries.port';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { verifyIntegrity } from 'lib/utils/integrity';\nimport { readSourceBytes } from 'lib/node/utils/read-source';\n\nconst createFsRemoteEntryProvider = (config: ModeConfig): ForProvidingRemoteEntries => {\n const formatError = (remoteEntryUrl: string) => (err: unknown) => {\n if (err instanceof NFError) throw err;\n const msg = err instanceof Error ? err.message : String(err);\n throw new NFError(`Read of '${remoteEntryUrl}' returned ${msg}`);\n };\n\n return {\n provide: async function (remoteEntryUrl: string, opts: { integrity?: string } = {}) {\n try {\n const bytes = await readSourceBytes(remoteEntryUrl);\n if (opts.integrity) await verifyIntegrity(bytes, opts.integrity);\n const raw = JSON.parse(new TextDecoder().decode(bytes)) as RawRemoteEntry;\n return normalizeRemoteEntry(raw, remoteEntryUrl, config);\n } catch (err) {\n return formatError(remoteEntryUrl)(err);\n }\n },\n };\n};\n\nexport { createFsRemoteEntryProvider };\n", "import type { ForSSE } from 'lib/core/2.app/driving-ports/for-sse.port';\n\nconst createNoopSSE = (): ForSSE => ({\n watchRemoteBuilds: () => {\n /* no-op */\n },\n closeAll: () => {\n /* no-op */\n },\n});\n\nexport { createNoopSSE };\n", "// `set` stores a copy and `get` returns a fresh one: a repository's uncommitted edits must never reach storage.\ntype StorageEntry<TValue> = {\n set: (value: TValue) => StorageEntry<TValue>;\n get: () => TValue | undefined;\n clear: () => StorageEntry<TValue>;\n};\n\ntype StorageEntryKey = number | symbol | string;\n\ntype StorageType = 'globalThis' | 'localStorage' | 'sessionStorage' | 'custom';\n\n// `type` is only read to describe the storage on globalThis.__NF_ORCHESTRATOR__; untagged creators report 'custom'.\ntype StorageEntryCreator = {\n (namespace: string): StorageEntryHandler;\n type?: StorageType;\n};\n\nconst STORAGE_KEYS = {\n remotes: 'remotes',\n sharedExternals: 'shared-externals',\n scopedExternals: 'scoped-externals',\n sharedChunks: 'shared-chunks',\n cacheState: 'cache-state',\n} as const;\n\ntype StorageKey = (typeof STORAGE_KEYS)[keyof typeof STORAGE_KEYS];\n\n// The orchestrator version that wrote the cache, beside the records: a cache stamped with any other is dropped.\n// `undecidedScopes` are the share scopes a runtime load wrote since their serving builds were last decided.\ntype CacheState = { version: string; undecidedScopes: string[] };\n\ntype StorageEntryHandler = <TValue>(key: string, initialValue: TValue) => StorageEntry<TValue>;\n\ntype StorageConfig = {\n storage: StorageEntryHandler;\n clearStorage: boolean;\n};\n\ntype StorageOptions = {\n storage?: StorageEntryCreator;\n clearStorage?: boolean;\n storageNamespace?: string;\n exposeStorageGetter?: boolean;\n};\n\nexport {\n StorageEntry,\n StorageEntryKey,\n StorageEntryHandler,\n StorageConfig,\n StorageOptions,\n StorageEntryCreator,\n StorageType,\n StorageKey,\n STORAGE_KEYS,\n CacheState,\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", "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", "import type { RemoteInfo, RemoteName, Remotes } from 'lib/core/1.domain';\nimport {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForRemoteInfoStorage } from 'lib/core/2.app/driving-ports/for-remote-info-storage.port';\nimport * as _path from 'lib/utils/path';\nimport { Optional } from 'lib/utils/optional';\n\nconst createRemoteInfoRepository = (config: StorageConfig): ForRemoteInfoStorage => {\n const STORAGE: StorageEntry<Remotes> = config.storage(STORAGE_KEYS.remotes, {});\n if (config.clearStorage) STORAGE.clear();\n\n let _cache: Remotes = STORAGE.get() ?? {};\n\n let _dirty = false;\n\n return {\n contains: function (remoteName: RemoteName) {\n return !!_cache[remoteName];\n },\n remove: function (remoteName: RemoteName) {\n if (remoteName in _cache) {\n delete _cache[remoteName];\n _dirty = true;\n }\n return this;\n },\n addOrUpdate: function (remoteName: string, remote: RemoteInfo) {\n _cache[remoteName] = remote;\n _dirty = true;\n return this;\n },\n tryGet: function (remoteName: RemoteName) {\n return Optional.of(_cache[remoteName]);\n },\n tryGetModule: function (remoteName: RemoteName, exposedModule: string) {\n return Optional.of(_cache[remoteName]?.exposes.find(m => m.moduleName === exposedModule)).map(\n m => _path.join(_cache[remoteName]!.scopeUrl, m.file)\n );\n },\n getModuleChunkUrls: function (remoteName: RemoteName, exposedModule: string) {\n const remote = _cache[remoteName];\n const chunks = remote?.exposes.find(m => m.moduleName === exposedModule)?.chunks ?? [];\n return chunks.map(file => _path.join(remote!.scopeUrl, file));\n },\n getAll: function () {\n return _cache;\n },\n commit: function () {\n if (!_dirty) return this;\n STORAGE.set(_cache);\n _dirty = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? {};\n _dirty = false;\n return this;\n },\n };\n};\n\nexport { createRemoteInfoRepository };\n", "import type { ScopedExternals } from 'lib/core/1.domain/externals/external.contract';\nimport {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForScopedExternalsStorage } from 'lib/core/2.app/driving-ports/for-scoped-externals-storage.port';\nimport type { RemoteName, ScopedVersion } from 'lib/core/1.domain';\nimport { Optional } from 'lib/utils/optional';\n\nconst createScopedExternalsRepository = (config: StorageConfig): ForScopedExternalsStorage => {\n const STORAGE: StorageEntry<ScopedExternals> = config.storage(STORAGE_KEYS.scopedExternals, {});\n\n if (config.clearStorage) STORAGE.clear();\n\n let _cache: ScopedExternals = STORAGE.get() ?? {};\n\n let _dirty = false;\n\n return {\n addExternal: function (remoteName: RemoteName, external: string, version: ScopedVersion) {\n if (!_cache[remoteName]) _cache[remoteName] = {};\n _cache[remoteName][external] = version;\n _dirty = true;\n return this;\n },\n remove: function (remoteName: RemoteName) {\n if (remoteName in _cache) {\n delete _cache[remoteName];\n _dirty = true;\n }\n return this;\n },\n getAll: function () {\n return _cache;\n },\n tryGet: function (remoteName: string) {\n return Optional.of(_cache[remoteName]);\n },\n commit: function () {\n if (!_dirty) return this;\n STORAGE.set(_cache);\n _dirty = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? {};\n _dirty = false;\n return this;\n },\n };\n};\n\nexport { createScopedExternalsRepository };\n", "import type { RemoteName } from '../remote/remote-info.contract';\nimport 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 // The pool this external resolves in, as pooling last computed it; absent when it is in none.\n poolName?: string;\n // The build its pool's last election made global; a tied re-election keeps it.\n poolWinner?: RemoteName;\n // The build every specifier of this external's package is served from in this scope; the same on each of them.\n // A remote, not a tag: a host serves every tag it ships.\n servingBuild?: RemoteName;\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", "import {\n STORAGE_KEYS,\n type CacheState,\n type StorageEntryHandler,\n} from 'lib/core/2.app/config/storage.contract';\n\n// `cache-state` has two writers, the storage config (`version`) and the shared-externals repository\n// (`undecidedScopes`). Each write re-reads the stored object, so neither ever drops the other's field.\nexport const createCacheState = (storage: StorageEntryHandler) => {\n const entry = storage<unknown>(STORAGE_KEYS.cacheState, null);\n\n const read = (): Partial<CacheState> => {\n const stored = entry.get();\n if (typeof stored !== 'object' || stored === null) return {};\n const { version, undecidedScopes } = stored as Record<string, unknown>;\n return {\n ...(typeof version === 'string' ? { version } : {}),\n ...(Array.isArray(undecidedScopes)\n ? { undecidedScopes: undecidedScopes.filter(s => typeof s === 'string') }\n : {}),\n };\n };\n\n return {\n read,\n update: (fields: Partial<CacheState>): void => void entry.set({ ...read(), ...fields }),\n };\n};\n", "import {\n type SharedExternal,\n type SharedExternals,\n GLOBAL_SCOPE,\n STRICT_SCOPE,\n} from 'lib/core/1.domain/externals/external.contract';\nimport {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForSharedExternalsStorage } from 'lib/core/2.app/driving-ports/for-shared-externals-storage.port';\nimport { createCacheState } from './cache-state';\nimport { Optional } from 'lib/utils/optional';\n\nconst createSharedExternalsRepository = (config: StorageConfig): ForSharedExternalsStorage => {\n const STORAGE: StorageEntry<SharedExternals> = config.storage<SharedExternals>(\n STORAGE_KEYS.sharedExternals,\n { [GLOBAL_SCOPE]: {} }\n );\n\n const cacheState = createCacheState(config.storage);\n const storedUndecided = () => new Set(cacheState.read().undecidedScopes);\n\n if (config.clearStorage) {\n STORAGE.clear();\n cacheState.update({ undecidedScopes: [] });\n }\n\n let _cache: SharedExternals = STORAGE.get() ?? { [GLOBAL_SCOPE]: {} };\n\n const _uncommitted = new Set<string>();\n\n let _undecided = storedUndecided();\n let _undecidedChanged = false;\n\n return {\n getFromScope: function (shareScope?: string) {\n return { ..._cache[shareScope ?? GLOBAL_SCOPE] };\n },\n addOrUpdate: function (externalName: string, external: SharedExternal, shareScope?: string) {\n if (!_cache[shareScope ?? GLOBAL_SCOPE]) _cache[shareScope ?? GLOBAL_SCOPE] = {};\n _cache[shareScope ?? GLOBAL_SCOPE]![externalName] = external;\n _uncommitted.add(shareScope ?? GLOBAL_SCOPE);\n return this;\n },\n getScopes: function (o = { includeGlobal: true }) {\n if (o.includeGlobal) return Object.keys(_cache);\n return Object.keys(_cache).filter(s => s !== GLOBAL_SCOPE);\n },\n // Batched: one traversal of the graph per init instead of one per overridden remote.\n removeFromAllScopes: function (remoteNames: ReadonlySet<string>) {\n if (remoteNames.size === 0) return;\n\n Object.entries(_cache).forEach(([scopeName, scope]) => {\n const removeExternals: string[] = [];\n\n Object.entries(scope).forEach(([name, external]) => {\n let removedCopy = false;\n\n for (let i = external.versions.length - 1; i >= 0; i--) {\n const version = external.versions[i]!;\n const remotes = version.remotes;\n // The host is `remotes[0]` of a flagged version, and the filter below is about to move it.\n const host = version.host ? remotes[0]?.name : undefined;\n\n let keep = 0;\n for (let r = 0; r < remotes.length; r++) {\n if (remoteNames.has(remotes[r]!.name)) continue;\n remotes[keep++] = remotes[r]!;\n }\n if (keep !== remotes.length) {\n remotes.length = keep;\n removedCopy = true;\n _uncommitted.add(scopeName);\n // Or `determine` keeps granting host precedence to a tag the host has left.\n if (host !== undefined && remoteNames.has(host)) version.host = false;\n }\n\n if (remotes.length === 0) {\n external.versions.splice(i, 1);\n _uncommitted.add(scopeName);\n }\n }\n\n // Any lost copy re-elects the external, not only one that emptied a version: the copy may have\n // been the version's basis, or the build a surviving copy's `servedBy` names. A replacement entry\n // that no longer declares this external never marks it dirty itself, so the record would keep\n // pointing at a build that does not serve it any more.\n if (removedCopy) {\n external.dirty = true;\n if (external.versions.length === 0) removeExternals.push(name);\n }\n });\n\n const lostPools = new Set<string>();\n for (const name of removeExternals) {\n const poolName = scope[name]!.poolName;\n if (poolName !== undefined) lostPools.add(poolName);\n delete scope[name];\n }\n // Nothing dirty is left behind, so mark its pool's siblings dirty or the next init skips the scope.\n if (lostPools.size > 0)\n for (const external of Object.values(scope))\n if (external.poolName !== undefined && lostPools.has(external.poolName))\n external.dirty = true;\n });\n },\n scopeType: function (shareScope?: string) {\n switch (shareScope) {\n case GLOBAL_SCOPE:\n case null:\n case undefined:\n return 'global';\n case STRICT_SCOPE:\n return 'strict';\n default:\n return 'shareScope';\n }\n },\n tryGet: function (external: string, shareScope?: string) {\n return Optional.of(_cache[shareScope ?? GLOBAL_SCOPE]?.[external]);\n },\n uncommittedScopes: function () {\n return [..._uncommitted];\n },\n markUndecided: function (shareScope: string) {\n if (_undecided.has(shareScope)) return;\n _undecided.add(shareScope);\n _undecidedChanged = true;\n },\n isUndecided: function (shareScope: string) {\n return _undecided.has(shareScope);\n },\n markDecided: function (shareScope: string) {\n if (_undecided.delete(shareScope)) _undecidedChanged = true;\n },\n // Records before marks: should their write throw, the stored marks still send the next init to decide them. A\n // failed cache-state write after the records loses only this load's marks.\n commit: function () {\n if (_uncommitted.size > 0) {\n STORAGE.set(_cache);\n _uncommitted.clear();\n }\n if (_undecidedChanged) cacheState.update({ undecidedScopes: [..._undecided] });\n _undecidedChanged = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? { [GLOBAL_SCOPE]: {} };\n _uncommitted.clear();\n _undecided = storedUndecided();\n _undecidedChanged = false;\n return this;\n },\n };\n};\n\nexport { createSharedExternalsRepository };\n", "import {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { ForSharedChunksStorage } from 'lib/core/2.app/driving-ports/for-shared-chunks-storage.port';\nimport type { SharedChunks } from 'lib/core/1.domain/externals/chunks.contract';\nimport { Optional } from 'lib/utils/optional';\n\nconst createChunkRepository = (config: StorageConfig): ForSharedChunksStorage => {\n const STORAGE: StorageEntry<SharedChunks> = config.storage(STORAGE_KEYS.sharedChunks, {});\n\n if (config.clearStorage) STORAGE.clear();\n\n let _cache: SharedChunks = STORAGE.get() ?? {};\n\n let _dirty = false;\n\n return {\n addOrReplace: function (remoteName: string, bundleName: string, chunks: string[]) {\n if (!_cache[remoteName]) _cache[remoteName] = {};\n _cache[remoteName][bundleName] = chunks;\n _dirty = true;\n return this;\n },\n // Whole-remote: a build that stops chunking a bundle omits the key, so `addOrReplace` cannot clear it.\n remove: function (remoteName: string) {\n if (remoteName in _cache) {\n delete _cache[remoteName];\n _dirty = true;\n }\n return this;\n },\n tryGet: function (remoteName: string, bundleName: string) {\n return Optional.of(_cache[remoteName]?.[bundleName]);\n },\n commit: function () {\n if (!_dirty) return this;\n STORAGE.set(_cache);\n _dirty = false;\n return this;\n },\n rollback: function () {\n _cache = STORAGE.get() ?? {};\n _dirty = false;\n return this;\n },\n };\n};\n\nexport { createChunkRepository };\n", "type TTCreateScript = (input: string) => string;\ntype TTCreateScriptURL = (input: string) => string;\n\ntype TTPolicyRules = {\n createScript?: TTCreateScript;\n createScriptURL?: TTCreateScriptURL;\n};\n\ntype TrustedValue = { toString(): string };\n\ntype TTPolicy = {\n createScript: (input: string) => TrustedValue;\n createScriptURL: (input: string) => TrustedValue;\n};\n\ntype TTFactory = {\n createPolicy: (name: string, rules: TTPolicyRules) => TTPolicy;\n};\n\nexport type NFTrustedTypesPolicy = {\n // `script.text` is a TrustedScript sink, so this must stay the genuine object.\n createScript: (input: string) => TrustedValue;\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),\n createScriptURL: input => String(native.createScriptURL(input)),\n };\n return cachedPolicy;\n};\n\nexport const __resetTrustedTypesPolicyForTests = (): void => {\n cachedPolicy = null;\n};\n", "import type { ImportMap } from 'lib/core/1.domain';\nimport type { SetImportMap } from 'lib/core/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 { PreloadModules } from 'lib/core/2.app/config/import-map.contract';\n\n// No crossorigin or integrity: the attributes must match the import's own request, and the import map's\n// integrity already applies to a link without one. Only document.head, the one place es-module-shims watches.\nexport const preloadInDOM = (rel: 'modulepreload' | 'modulepreload-shim'): PreloadModules => {\n // A module is loaded again on every visit to its route; without this the head grows a link per visit.\n const preloaded = new Set<string>();\n return urls => {\n for (const href of urls) {\n if (preloaded.has(href)) continue;\n preloaded.add(href);\n document.head.appendChild(Object.assign(document.createElement('link'), { rel, href }));\n }\n };\n};\n", "import type { ImportMapConfig } from 'lib/core/2.app/config/import-map.contract';\nimport { replaceInDOM } from './replace-in-dom';\nimport { preloadInDOM } from './preload-in-dom';\nimport { getTrustedTypesPolicy } from './trusted-types';\n\nconst useDefaultImportMap = (trustedTypesPolicyName: string | false = 'nfo'): ImportMapConfig => ({\n loadModuleFn: url => {\n const trusted = getTrustedTypesPolicy(trustedTypesPolicyName).createScriptURL(url);\n return import(/* @vite-ignore */ trusted);\n },\n setImportMapFn: replaceInDOM('importmap', trustedTypesPolicyName),\n preloadModulesFn: preloadInDOM('modulepreload'),\n reloadBrowserFn: () => {\n window.location.reload();\n },\n});\n\nexport { useDefaultImportMap };\n", "import type { PreloadModules } from 'lib/core/2.app/config/import-map.contract';\n\nexport const noPreload: PreloadModules = () => {};\n", "import type {\n ImportMapConfig,\n ImportMapOptions,\n} from 'lib/core/2.app/config/import-map.contract';\nimport { useDefaultImportMap } from './use-default';\nimport { noPreload } from './no-preload';\n\nexport const createImportMapConfig = (o: Partial<ImportMapOptions>): ImportMapConfig => {\n const fallback = useDefaultImportMap(o.trustedTypesPolicyName);\n return {\n setImportMapFn: o.setImportMapFn ?? fallback.setImportMapFn,\n loadModuleFn: o.loadModuleFn ?? fallback.loadModuleFn,\n reloadBrowserFn: o.reloadBrowserFn ?? fallback.reloadBrowserFn,\n preloadModulesFn: o.preloadModulesFn ?? defaultPreload(o, fallback),\n };\n};\n\n// The DOM preset only helps the default loader: a custom one never reuses its <link> fetches.\nconst defaultPreload = (o: Partial<ImportMapOptions>, fallback: ImportMapConfig) =>\n o.loadModuleFn ? noPreload : fallback.preloadModulesFn;\n", "import type { HostConfig, HostOptions } from 'lib/core/2.app/config/host.contract';\n\nexport const createHostConfig = (override: Partial<HostOptions>): HostConfig => {\n const extras = override?.manifestIntegrity\n ? { manifestIntegrity: override.manifestIntegrity }\n : {};\n\n if (!override?.hostRemoteEntry) {\n return { hostRemoteEntry: false, ...extras };\n }\n if (typeof override.hostRemoteEntry === 'string') {\n return {\n hostRemoteEntry: {\n name: '__NF-HOST__',\n url: override.hostRemoteEntry,\n },\n ...extras,\n };\n }\n return {\n hostRemoteEntry: {\n name: '__NF-HOST__',\n ...override.hostRemoteEntry,\n },\n ...extras,\n };\n};\n", "import type { Logger } from 'lib/core/2.app/config/log.contract';\n\nconst noopLogger: Logger = {\n debug: () => {},\n error: () => {},\n warn: () => {},\n};\n\nexport { noopLogger };\n", "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 {\n type LogType,\n type LogHandler,\n type Logger,\n LogLevel,\n} from 'lib/core/2.app/config/log.contract';\n\nconst createLogHandler = (logger: Logger, logLevel: LogType): LogHandler => {\n const logTypes = Object.keys(LogLevel).filter(key => isNaN(Number(key))) as LogType[];\n\n return logTypes.reduce(\n (acc, logMessageType) => {\n return {\n ...acc,\n [logMessageType]: (step: number, message: string, details: unknown) => {\n if (LogLevel[logMessageType] >= LogLevel[logLevel]) {\n logger[logMessageType](step, message, details);\n }\n },\n };\n },\n { level: logLevel } as LogHandler\n );\n};\n\nexport { createLogHandler };\n", "import type { LoggingConfig, LoggingOptions } from 'lib/core/2.app/config/log.contract';\nimport { noopLogger } from './noop.logger';\nimport { createLogHandler } from './log.handler';\n\nexport const createLogConfig = ({ logger, logLevel, sse }: LoggingOptions): LoggingConfig => ({\n log: createLogHandler(logger ?? noopLogger, logLevel ?? 'error'),\n sse: !!sse,\n});\n", "import type { StorageEntryKey } from 'lib/core/2.app/config/storage.contract';\nimport { NFError } from 'lib/core/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 'lib/utils/clone-entry';\nimport {\n type StorageEntryCreator,\n type StorageEntry,\n} from 'lib/core/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\n const entry: StorageEntry<TValue> = {\n get(): TValue {\n return cloneEntry(key, key in storage ? storage[key] : initialValue)!;\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\nglobalThisStorageEntry.type = 'globalThis';\nObject.freeze(globalThisStorageEntry);\n\nexport { globalThisStorageEntry };\n", "// Injected by build.js; bundles built without that define (e.g. the e2e harness) report 'dev'.\ndeclare const __NF_ORCHESTRATOR_VERSION__: string | undefined;\n\nexport const ORCHESTRATOR_VERSION =\n typeof __NF_ORCHESTRATOR_VERSION__ === 'string' ? __NF_ORCHESTRATOR_VERSION__ : 'dev';\n", "import type {\n NFOrchestratorGlobal,\n NFOrchestratorStorageInfo,\n} from 'lib/core/2.app/config/orchestrator-global.contract';\nimport {\n STORAGE_KEYS,\n type StorageEntryHandler,\n type StorageKey,\n type StorageType,\n} from 'lib/core/2.app/config/storage.contract';\nimport { cloneEntry } from 'lib/utils/clone-entry';\nimport { ORCHESTRATOR_VERSION } from 'lib/core/4.config/orchestrator-version';\n\nconst KEYS: readonly StorageKey[] = Object.freeze(Object.values(STORAGE_KEYS));\n\nconst isStorageKey = (key: string): key is StorageKey => (KEYS as readonly string[]).includes(key);\n\ntype StorageInfoOptions = {\n type: StorageType;\n namespace: string;\n storage: StorageEntryHandler;\n exposeGetter: boolean;\n};\n\nconst createStorageInfo = ({\n type,\n namespace,\n storage,\n exposeGetter,\n}: StorageInfoOptions): NFOrchestratorStorageInfo => {\n const info: NFOrchestratorStorageInfo = {\n version: ORCHESTRATOR_VERSION,\n type,\n namespace,\n keys: KEYS,\n };\n if (!exposeGetter) return Object.freeze(info);\n\n return Object.freeze({\n ...info,\n // Cloned again because custom storages may hand out live references.\n get: (key: string) =>\n isStorageKey(key) ? cloneEntry(key, storage(key, undefined).get()) : undefined,\n });\n};\n\n// Replaced (not mutated) so earlier namespaces survive while the published object stays frozen.\n// Diagnostic only: a locked-down or foreign global must never break init, so failures are swallowed.\nexport const publishStorageInfo = (options: StorageInfoOptions): void => {\n try {\n globalThis.__NF_ORCHESTRATOR__ = Object.freeze<NFOrchestratorGlobal>({\n storage: Object.freeze({\n ...globalThis.__NF_ORCHESTRATOR__?.storage,\n [options.namespace]: createStorageInfo(options),\n }),\n });\n } catch {\n /* the global is not writable */\n }\n};\n", "import {\n STORAGE_KEYS,\n type StorageConfig,\n type StorageEntry,\n type StorageEntryHandler,\n type StorageOptions,\n} from 'lib/core/2.app/config/storage.contract';\nimport type { LogHandler } from 'lib/core/2.app/config/log.contract';\nimport { cloneEntry } from 'lib/utils/clone-entry';\nimport { globalThisStorageEntry } from './global-this.storage';\nimport { publishStorageInfo } from './publish-storage-info';\nimport { ORCHESTRATOR_VERSION } from 'lib/core/4.config/orchestrator-version';\nimport { createCacheState } from 'lib/core/3.adapters/storage/cache-state';\n\n// Every entry goes, not only the outdated one: a warm init skips fetching any remote it still has\n// cached, so a dropped externals entry would never be refilled.\nconst isOutdatedCache = (storage: StorageEntryHandler): boolean => {\n const cacheState = createCacheState(storage);\n if (cacheState.read().version === ORCHESTRATOR_VERSION) return false;\n cacheState.update({ version: ORCHESTRATOR_VERSION, undecidedScopes: [] });\n return Object.values(STORAGE_KEYS)\n .filter(key => key !== STORAGE_KEYS.cacheState)\n .some(key => storage(key, null).get() !== null);\n};\n\n// After one failed write the page stops persisting and keeps every later write in memory: a cache-state update\n// would otherwise re-stamp the version, and a rollback would re-read the half-written records.\nconst guardWrites = (storage: StorageEntryHandler, log: LogHandler): StorageEntryHandler => {\n let failed = false;\n const memory = new Map<string, unknown>();\n\n const write = (key: string, value: unknown, persist: () => void): void => {\n if (!failed) {\n try {\n persist();\n return;\n } catch (error) {\n failed = true;\n try {\n // Replaces the stamp with the smallest value, so the next page clears the cache.\n storage(STORAGE_KEYS.cacheState, null).set(null);\n } catch {\n /* the next page may inherit the broken cache */\n }\n log.warn(\n 5,\n `Could not save '${key}' to storage; this page runs from memory and the next page starts without a cache.`,\n error\n );\n }\n }\n memory.set(key, cloneEntry(key, value));\n };\n\n return <TValue>(key: string, initialValue: TValue) => {\n const inner = storage(key, initialValue);\n const entry: StorageEntry<TValue> = {\n get: () => (memory.has(key) ? cloneEntry(key, memory.get(key) as TValue) : inner.get()),\n set: value => {\n write(key, value, () => void inner.set(value));\n return entry;\n },\n clear: () => {\n write(key, initialValue, () => void inner.clear());\n return entry;\n },\n };\n return entry;\n };\n};\n\nexport const createStorageConfig = (override: StorageOptions, log: LogHandler): StorageConfig => {\n const creator = override.storage ?? globalThisStorageEntry;\n const namespace = override.storageNamespace ?? '__NATIVE_FEDERATION__';\n const storage = guardWrites(creator(namespace), log);\n publishStorageInfo({\n type: creator.type ?? 'custom',\n namespace,\n storage,\n exposeGetter: override.exposeStorageGetter ?? true,\n });\n const outdated = isOutdatedCache(storage);\n\n return {\n storage,\n clearStorage: (override.clearStorage ?? false) || outdated,\n };\n};\n", "import type { ModeProfileConfig } from 'lib/core/2.app/config/mode.contract';\n\nexport const defaultProfile: ModeProfileConfig = {\n latestSharedExternal: false,\n skipInvalidExternalVersions: false,\n overrideCachedRemotes: 'init-only',\n overrideCachedRemotesIfURLMatches: false,\n mergeManifests: true,\n enableDebugging: false,\n};\n", "import type { ModeConfig, ModeOptions } from 'lib/core/2.app/config/mode.contract';\nimport { defaultProfile } from './default.profile';\n\nexport const createModeConfig = (override: ModeOptions): ModeConfig => {\n const strictnessConfig =\n typeof override.strict === 'boolean'\n ? {\n strictRemoteEntry: override.strict,\n strictExternalCompatibility: override.strict,\n strictExternalSameVersionCompatibility: override.strict,\n strictExternalVersion: override.strict,\n strictImportMap: override.strict,\n }\n : {\n strictRemoteEntry: override.strict?.strictRemoteEntry ?? false,\n strictExternalCompatibility: override.strict?.strictExternalCompatibility ?? false,\n strictExternalSameVersionCompatibility:\n override.strict?.strictExternalSameVersionCompatibility ?? false,\n strictExternalVersion: override.strict?.strictExternalVersion ?? false,\n strictImportMap: override.strict?.strictImportMap ?? false,\n };\n\n return {\n strict: strictnessConfig,\n profile: { ...defaultProfile, ...(override.profile ?? {}) },\n feature: {\n convertFlatSharedInfo: override.feature?.convertFlatSharedInfo ?? false,\n },\n };\n};\n", "import type { ConfigContract, NFOptions } from 'lib/core/2.app/config/config.contract';\nimport { createImportMapConfig } from 'lib/core/4.config/import-map/import-map.config';\nimport { createHostConfig } from 'lib/core/4.config/host/host.config';\nimport { createLogConfig } from 'lib/core/4.config/logging/log.config';\nimport { createStorageConfig } from 'lib/core/4.config/storage/storage.config';\nimport { createModeConfig } from 'lib/core/4.config/mode/mode.config';\n\nexport const createConfigHandlers = (overrides: NFOptions): ConfigContract => {\n const logConfig = createLogConfig(overrides);\n return {\n ...createImportMapConfig(overrides),\n ...createHostConfig(overrides),\n ...logConfig,\n ...createStorageConfig(overrides, logConfig.log),\n ...createModeConfig(overrides),\n };\n};\n", "import type { FLOW_FACTORY } from '../driver-ports/flow-factory.contract';\nimport type { InitDriversContract } from '../driver-ports/init/drivers.contract';\nimport type { InitFlow } from '../driver-ports/init/flow.contract';\n\nexport const createInitFlow = ({\n flow,\n adapters,\n config,\n}: FLOW_FACTORY<InitDriversContract>): InitFlow => {\n return remotesOrManifestUrl =>\n flow\n .getRemoteEntries(remotesOrManifestUrl)\n .then(flow.processRemoteEntries)\n .then(flow.poolSharedExternals)\n .then(flow.determineSharedExternals)\n .then(flow.decideServingBuilds)\n .then(flow.generateImportMap)\n .then(importMap => flow.commitChanges(importMap, { override: true }))\n .then(flow.exposeModuleLoader)\n .then(access => ({\n config,\n adapters,\n ...access,\n }));\n};\n", "import type { RemoteEntry } from 'lib/core/1.domain';\nimport type { FLOW_FACTORY } from '../driver-ports/flow-factory.contract';\nimport type { InitDriversContract } from '../driver-ports/init/drivers.contract';\nimport type { InitRemoteEntryFlow } from '../driver-ports/init/flow.contract';\n\nexport const createInitRemoteEntryFlow = ({\n flow,\n}: FLOW_FACTORY<InitDriversContract>): InitRemoteEntryFlow => {\n const processDynamicRemoteEntry = (remoteEntry: RemoteEntry) =>\n flow\n .updateCache(remoteEntry)\n .then(flow.poolDynamicExternals)\n .then(flow.convertToImportMap)\n .then(importMap => flow.commitChanges(importMap, { markUndecided: true }));\n\n return (remoteEntryUrl, remote) =>\n flow\n .getRemoteEntry(remoteEntryUrl, remote)\n .then(entry => entry.map(processDynamicRemoteEntry).orElse(Promise.resolve()))\n .then(() => undefined)\n .catch((error: unknown) => {\n const remoteName = typeof remote === 'string' ? remote : remote?.name;\n return flow\n .rollbackChanges(`[dynamic-init][${remoteName ?? remoteEntryUrl}]`)\n .then(() => Promise.reject(error));\n });\n};\n", "import {\n type RemoteEntry,\n type RemoteInfo,\n type RemoteName,\n type ScopedVersion,\n type SharedExternal,\n type DenseSharedInfo,\n type RemoteSharedInfo,\n type SharedVersion,\n type SharedVersionMeta,\n} from 'lib/core/1.domain';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport * as _path from 'lib/utils/path';\n\nexport type StoreRemoteEntry = (\n remoteEntry: RemoteEntry,\n onSharedExternal: SharedExternalHandler\n) => void;\n\nexport type RemoveCachedRemoteEntries = (remoteNames: ReadonlySet<RemoteName>) => void;\n\n// Kept out of `storeRemoteEntry`: `removeFromAllScopes` traverses the whole shared-externals graph, so each\n// caller evicts its whole set at once.\nexport function createRemoveCachedRemoteEntries(\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedExternalsRepo' | 'sharedChunksRepo'\n >\n): RemoveCachedRemoteEntries {\n return remoteNames => {\n if (remoteNames.size === 0) return;\n\n for (const remoteName of remoteNames) {\n ports.remoteInfoRepo.remove(remoteName);\n ports.scopedExternalsRepo.remove(remoteName);\n ports.sharedChunksRepo.remove(remoteName);\n }\n ports.sharedExternalsRepo.removeFromAllScopes(remoteNames);\n };\n}\n\nexport type SharedExternalHandler = (\n remoteEntry: RemoteEntry,\n external: DenseSharedInfo,\n ctx: SharedExternalContext\n) => void;\n\nexport type SharedExternalContext = {\n tag: string;\n remote: SharedVersionMeta;\n readRecord: () => SharedExternal;\n scopeType: 'global' | 'strict' | 'shareScope';\n assertSameVersionCompatibility: (matchingVersion: SharedVersion) => void;\n write: () => void;\n};\n\n// Shared by the init and dynamic storage steps, which must stay separate (docs/version-resolver.md \"Dynamic\n// Init\"): if a change needs a flag here to serve only one caller, inline this back into the steps instead.\n// Every entry is merged additively; evicting an overridden remote is the caller's job.\nexport function createStoreRemoteEntry(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'scopedExternalsRepo'\n | 'sharedExternalsRepo'\n | 'sharedChunksRepo'\n | 'versionCheck'\n >,\n logStep: number\n): StoreRemoteEntry {\n return (remoteEntry, onSharedExternal) => {\n addRemoteInfoToStorage(remoteEntry);\n addExternalsToStorage(remoteEntry, onSharedExternal);\n addSharedChunksToStorage(remoteEntry);\n };\n\n function addRemoteInfoToStorage({ name, url, exposes, integrity }: RemoteEntry): void {\n ports.remoteInfoRepo.addOrUpdate(name, {\n scopeUrl: _path.getScope(url),\n exposes: Object.values(exposes ?? []).map(m => {\n // Only the static closure is certain to be needed; lazy rows are left to the module's own import().\n const chunks = Object.values(m.chunks ?? {})\n .filter(c => c.initial)\n .map(c => c.file);\n return {\n moduleName: m.key,\n file: m.outFileName,\n ...(chunks.length ? { chunks } : {}),\n };\n }),\n ...(integrity ? { integrity } : {}),\n } as RemoteInfo);\n }\n\n function addExternalsToStorage(\n remoteEntry: RemoteEntry,\n onSharedExternal: SharedExternalHandler\n ): void {\n remoteEntry.shared.forEach(external => {\n const tag = resolveVersion(remoteEntry, external);\n if (tag === null) return;\n\n if (external.singleton) {\n if (\n external.requiredVersion &&\n !ports.versionCheck.isCompatible(tag, external.requiredVersion)\n )\n config.log.warn(\n logStep,\n `[${remoteEntry.name}][${external.packageName}] requiredVersion '${external.requiredVersion}' excludes its own version '${tag}'; '${tag}' is still accepted for it.`\n );\n onSharedExternal(remoteEntry, external, sharedExternalContext(remoteEntry, external, tag));\n } else {\n addScopedExternal(remoteEntry, external, tag);\n }\n });\n }\n\n function addSharedChunksToStorage(remoteEntry: RemoteEntry): void {\n if (!remoteEntry.chunks) return;\n config.log.debug(\n logStep,\n `Adding chunks for remote \"${remoteEntry.name}\", bundles: [${Object.keys(remoteEntry.chunks).join(', ')}]`\n );\n Object.entries(remoteEntry.chunks).forEach(([bundleName, chunks]) => {\n ports.sharedChunksRepo.addOrReplace(remoteEntry.name, bundleName, chunks);\n });\n }\n\n function addScopedExternal(\n remoteEntry: RemoteEntry,\n sharedInfo: DenseSharedInfo,\n tag: string\n ): void {\n const { packageName, entries } = sharedInfo;\n // Split records (#134) never share an entrypoint, so keying a root-less one by its first keeps them all.\n const key = packageName in entries ? packageName : (Object.keys(entries)[0] ?? packageName);\n ports.scopedExternalsRepo.addExternal(remoteEntry.name, key, {\n tag,\n bundle: sharedInfo.bundle,\n entries,\n ...(sharedInfo.preload ? { preload: true as const } : {}),\n } as ScopedVersion);\n }\n\n function resolveVersion(remoteEntry: RemoteEntry, external: DenseSharedInfo): string | null {\n if (external.version && ports.versionCheck.isValidSemver(external.version)) {\n return external.version;\n }\n\n const errorMsg = `[${remoteEntry.name}][${external.packageName}] Version '${external.version}' is not a valid version.`;\n if (config.strict.strictExternalVersion) {\n config.log.error(logStep, errorMsg);\n throw new NFError(`Could not process remote '${remoteEntry.name}'`);\n }\n if (config.profile.skipInvalidExternalVersions) {\n config.log.warn(logStep, `${errorMsg} Skipping external.`);\n return null;\n }\n config.log.warn(logStep, errorMsg);\n return ports.versionCheck.smallestVersion(external.requiredVersion);\n }\n\n function sharedExternalContext(\n remoteEntry: RemoteEntry,\n sharedInfo: RemoteSharedInfo,\n tag: string\n ): SharedExternalContext {\n const scopeType = ports.sharedExternalsRepo.scopeType(sharedInfo.shareScope);\n\n const remote: SharedVersionMeta = {\n name: remoteEntry.name,\n bundle: sharedInfo.bundle,\n strictVersion: sharedInfo.strictVersion,\n cached: false,\n requiredVersion: scopeType === 'strict' ? tag : sharedInfo.requiredVersion || tag,\n ...(sharedInfo.pool?.trim() ? { pool: sharedInfo.pool } : {}),\n ...(sharedInfo.dense ? { dense: true as const } : {}),\n entries: sharedInfo.entries,\n ...(sharedInfo.preload ? { preload: true as const } : {}),\n ...(sharedInfo.dev ? { dev: true as const } : {}),\n };\n\n // Read on first use: a runtime load stores its copies only after deciding them all, and an entry may list\n // one external twice (one row per tag).\n let stored: SharedExternal | undefined;\n const readRecord = (): SharedExternal =>\n (stored ??= ports.sharedExternalsRepo\n .tryGet(sharedInfo.packageName, sharedInfo.shareScope)\n .get() ?? { dirty: false, versions: [] });\n\n return {\n tag,\n remote,\n readRecord,\n scopeType,\n assertSameVersionCompatibility(matchingVersion: SharedVersion): void {\n if (!remote.strictVersion) return;\n if (matchingVersion.remotes[0]!.requiredVersion === remote.requiredVersion) return;\n\n const errorMsg = `[${remoteEntry.name}][${sharedInfo.packageName}@${\n sharedInfo.version\n }] Required version-range '${\n remote.requiredVersion\n }' does not match cached version-range '${matchingVersion.remotes[0]!.requiredVersion}'`;\n\n if (config.strict.strictExternalSameVersionCompatibility) {\n config.log.error(logStep, errorMsg);\n throw new NFError(`Could not process remote '${remoteEntry.name}'`);\n }\n config.log.warn(logStep, errorMsg);\n },\n write(): void {\n ports.sharedExternalsRepo.addOrUpdate(\n sharedInfo.packageName,\n {\n ...readRecord(),\n versions: readRecord().versions.sort((a, b) =>\n ports.versionCheck.compare(b.tag, a.tag)\n ),\n },\n sharedInfo.shareScope\n );\n },\n };\n }\n}\n", "import type { RemoteEntry } from 'lib/core/1.domain/remote-entry/remote-entry.contract';\nimport type {\n FederationManifest,\n RemoteEntryDescriptor,\n RemoteEntryUrl,\n} from 'lib/core/1.domain/remote-entry/manifest.contract';\nimport type { RemoteInfo, RemoteName } from 'lib/core/1.domain/remote/remote-info.contract';\nimport type { ForGettingRemoteEntries } from '../driver-ports/init/for-getting-remote-entries.port';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { ModeConfig } from '../config/mode.contract';\nimport type { HostConfig } from '../config/host.contract';\nimport * as _path from 'lib/utils/path';\nimport { createRemoveCachedRemoteEntries } from './store-remote-entry';\n\nexport function createGetRemoteEntries(\n config: LoggingConfig & ModeConfig & HostConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteEntryProvider'\n | 'manifestProvider'\n | 'remoteInfoRepo'\n | 'scopedExternalsRepo'\n | 'sharedExternalsRepo'\n | 'sharedChunksRepo'\n | 'sse'\n >\n): ForGettingRemoteEntries {\n const removeCachedRemoteEntries = createRemoveCachedRemoteEntries(ports);\n\n /**\n * Step 1: Fetch the remoteEntry JSON objects:\n *\n * A Manifest or URL to a Manifest is used as the input. Based on the defined remotes\n * in the manifest, the library will download the remoteEntry.json files which contain the\n * metadata of the defined remotes (name, exposed modules and required dependencies a.k.a. externals).\n * With `profile.mergeManifests: false`, stored remotes the manifest doesn't list are dropped first.\n *\n * @param config\n * @param adapters\n * @returns A list of the remoteEntry json objects\n */\n return (remotesOrManifestUrl = {}) => {\n const manifestPromise = config.manifestIntegrity\n ? ports.manifestProvider.provide(remotesOrManifestUrl, {\n integrity: config.manifestIntegrity,\n })\n : ports.manifestProvider.provide(remotesOrManifestUrl);\n\n return manifestPromise\n .catch(e => {\n config.log.error(1, 'Could not fetch manifest.', e);\n return Promise.reject(new NFError('Failed to fetch manifest'));\n })\n .then(addHostRemoteEntry)\n .then(dropUnlistedRemotes)\n .then(fetchRemoteEntries)\n .then(removeSkippedRemotes)\n .then(checkForSSE);\n };\n\n function addHostRemoteEntry(manifest: FederationManifest): FederationManifest {\n if (!config.hostRemoteEntry) return manifest;\n\n const { name, url, integrity } = config.hostRemoteEntry;\n\n return {\n ...manifest,\n [name]: integrity ? { url, integrity } : url,\n };\n }\n\n // Here rather than with the overrides in process-remote-entries: an unlisted remote has no fetched entry, and\n // only this step knows the manifest.\n function dropUnlistedRemotes(manifest: FederationManifest): FederationManifest {\n if (config.profile.mergeManifests !== false) return manifest;\n\n const listedUrls = new Set(\n Object.values(manifest).map(descriptor => normalizeEntry(descriptor).url)\n );\n // A remote fetched under another name than its manifest key is stored under the fetched one.\n const isListed = (remoteName: RemoteName, info: RemoteInfo) =>\n Object.hasOwn(manifest, remoteName) || listedUrls.has(storedEntryUrl(info));\n\n const unlisted = new Set(\n Object.entries(ports.remoteInfoRepo.getAll())\n .filter(([remoteName, info]) => !isListed(remoteName, info))\n .map(([remoteName]) => remoteName)\n );\n if (unlisted.size > 0)\n config.log.debug(\n 1,\n `Removing stored remotes the manifest doesn't list: ${[...unlisted].join(', ')}.`\n );\n removeCachedRemoteEntries(unlisted);\n return manifest;\n }\n\n function storedEntryUrl(info: RemoteInfo): RemoteEntryUrl {\n return _path.join(info.scopeUrl, 'remoteEntry.json');\n }\n\n function normalizeEntry(descriptor: RemoteEntryDescriptor): {\n url: RemoteEntryUrl;\n integrity?: string;\n } {\n return typeof descriptor === 'string' ? { url: descriptor } : descriptor;\n }\n\n function withCacheTag(url: string, cacheTag?: string): string {\n if (!cacheTag) return url;\n return `${url}${url.includes('?') ? '&' : '?'}cacheTag=${cacheTag}`;\n }\n\n function resolveCacheTag(remoteName: RemoteName): string | undefined {\n if (\n config.hostRemoteEntry &&\n remoteName === config.hostRemoteEntry.name &&\n config.hostRemoteEntry.cacheTag\n ) {\n return config.hostRemoteEntry.cacheTag;\n }\n return config.profile.cacheTag;\n }\n\n async function fetchRemoteEntries(\n manifest: FederationManifest\n ): Promise<(RemoteEntry | false)[]> {\n const fetchPromises = Object.entries(manifest).map(([remoteName, descriptor]) =>\n fetchRemoteEntry(remoteName, descriptor)\n );\n return Promise.all(fetchPromises);\n }\n\n async function fetchRemoteEntry(\n remoteName: RemoteName,\n descriptor: RemoteEntryDescriptor\n ): Promise<RemoteEntry | false> {\n const { url: remoteEntryUrl, integrity } = normalizeEntry(descriptor);\n let isOverride = false;\n let skip = false;\n\n ports.remoteInfoRepo.tryGet(remoteName).ifPresent(cachedRemoteInfo => {\n if (\n config.profile.overrideCachedRemotes !== 'never' &&\n (remoteEntryUrl !== storedEntryUrl(cachedRemoteInfo) ||\n config.profile.overrideCachedRemotesIfURLMatches)\n ) {\n config.log.debug(1, `Overriding existing remote '${remoteName}' with '${remoteEntryUrl}'.`);\n isOverride = true;\n } else {\n config.log.debug(1, `Found remote '${remoteName}' in storage, omitting fetch.`);\n skip = true;\n }\n });\n\n if (skip) return false;\n\n const fetchUrl = withCacheTag(remoteEntryUrl, resolveCacheTag(remoteName));\n\n try {\n const remoteEntry = integrity\n ? await ports.remoteEntryProvider.provide(fetchUrl, { integrity })\n : await ports.remoteEntryProvider.provide(fetchUrl);\n\n config.log.debug(\n 1,\n `Fetched '${remoteEntry.name}' from '${remoteEntry.url}', exposing: ${JSON.stringify(remoteEntry.exposes)}`\n );\n\n return prepareRemoteEntry(remoteEntry, remoteName, isOverride);\n } catch (error) {\n if (config.strict.strictRemoteEntry) {\n config.log.error(1, `Could not fetch remote '${remoteName}'.`, error);\n return Promise.reject(new NFError(`Could not fetch remote '${remoteName}'`));\n }\n config.log.warn(1, `Could not fetch remote '${remoteName}'. skipping init.`, error);\n\n return Promise.resolve(false);\n }\n }\n\n function prepareRemoteEntry(\n remoteEntry: RemoteEntry,\n expectedRemoteName: string,\n isOverride: boolean\n ): RemoteEntry {\n if (isOverride) remoteEntry.override = isOverride;\n\n if (!!config.hostRemoteEntry && expectedRemoteName === config.hostRemoteEntry.name) {\n remoteEntry.host = true;\n remoteEntry.name = config.hostRemoteEntry!.name;\n }\n\n if (remoteEntry.name !== expectedRemoteName) {\n const errorDetails = `Fetched remote '${remoteEntry.name}' does not match requested '${expectedRemoteName}'.`;\n if (config.strict.strictRemoteEntry) {\n throw new NFError(errorDetails);\n }\n config.log.warn(1, `${errorDetails} Omitting expected name.`);\n }\n\n return remoteEntry;\n }\n\n function removeSkippedRemotes(remoteEntries: (RemoteEntry | false)[]): RemoteEntry[] {\n return remoteEntries.filter((entry): entry is RemoteEntry => entry !== false);\n }\n\n function checkForSSE(remoteEntries: RemoteEntry[]): RemoteEntry[] {\n if (config.sse) {\n remoteEntries.forEach(entry => {\n if (entry.buildNotificationsEndpoint) {\n ports.sse.watchRemoteBuilds(\n _path.join(_path.getScope(entry.url), entry.buildNotificationsEndpoint)\n );\n config.log.debug(1, `Registered SSE endpoint of remote '${entry.name}' `);\n return;\n }\n config.log.debug(1, `Remote ${entry.name} has no defined 'buildNotificationsEndpoint'`);\n });\n }\n\n return remoteEntries;\n }\n}\n", "// Code-unit order: unlike `localeCompare`, the same in every browser and locale, so anything stored or elected\n// from a name comes out identical everywhere.\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nexport { compareStrings };\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport type { SharedVersion, SharedVersionMeta } from './version.contract';\n\nconst coverage = (remote: SharedVersionMeta): number => Object.keys(remote.entries).length;\n\n// `remotes[0]` is the basis: the copy every consumer of the version resolves to. Host and cached\n// outrank coverage because repointing them invalidates a committed import map. An exact tie goes to the\n// name, so the basis does not depend on the order remotes register in. `preferDev` (#118) ranks a dev build\n// above cached: only page-load init passes it, where nothing is committed yet, so cached means an earlier page.\nexport function isBetterBasis(\n candidate: SharedVersionMeta,\n basis: SharedVersionMeta,\n preferDev = false\n): boolean {\n if (preferDev && Boolean(basis.dev) !== Boolean(candidate.dev)) return Boolean(candidate.dev);\n if (basis.cached !== candidate.cached) return candidate.cached;\n const byCoverage = coverage(candidate) - coverage(basis);\n return byCoverage === 0 ? compareStrings(candidate.name, basis.name) < 0 : byCoverage > 0;\n}\n\nexport function addRemoteToVersion(\n version: SharedVersion,\n remote: SharedVersionMeta,\n isHost = false,\n preferDev = false\n): void {\n if (isHost) {\n version.host = true;\n version.remotes.unshift(remote);\n return;\n }\n\n const basis = version.remotes[0];\n if (basis && !version.host && isBetterBasis(remote, basis, preferDev)) {\n version.remotes.unshift(remote);\n return;\n }\n\n version.remotes.push(remote);\n}\n\n// `remotes[0]` answers \"who serves this version\", never \"what does this version demand\":\n// `requiredVersion`, `strictVersion` and `cached` are per-build settings, so remotes sharing a tag\n// can disagree on all three. Negotiation must therefore aggregate over every remote, or basis\n// precedence would decide compatibility. Deduped because those settings repeat across a version's\n// remotes, which keeps the resolver's O(versions\u00B2) selection from also scaling with remote count.\nexport function versionDemands(version: SharedVersion): SharedVersionMeta[] {\n if (version.remotes.length < 2) return version.remotes;\n\n const distinct = new Map<string, SharedVersionMeta>();\n for (const remote of version.remotes) {\n const key = `${remote.requiredVersion}|${remote.strictVersion}|${remote.cached}`;\n if (!distinct.has(key)) distinct.set(key, remote);\n }\n return Array.from(distinct.values());\n}\n\n// Which copies of a version may publish a specifier, in basis precedence; callers keep the first claim. The\n// copies build one tag, so this is what the version ships, not whose files a consumer runs; see\n// docs/version-resolver.md#copies-of-one-version.\n//\n// Only copies that publish their own files count. Pooling places a copy in a subpool running a foreign\n// build via `servedBy`, and the import map then names that build's files for it, per consumer \u2014 so what\n// such a copy bundles answers for nobody but itself, and counting it would promise a specifier no\n// consumer of this version can resolve. Pooling keeps a subpool copy out of the basis slot for exactly\n// this reason, so a `share` version's basis always survives the skip. `accepts` lets a caller discount a\n// copy without dropping its specifiers for the next copy to claim.\nexport function forEachVersionEntry(\n version: DeepReadonly<SharedVersion>,\n accepts: ((remote: SharedVersionMeta) => boolean) | undefined,\n visit: (entrypoint: string, remote: SharedVersionMeta) => void\n): void {\n for (const remote of version.remotes) {\n if (remote.servedBy) continue;\n if (accepts && !accepts(remote)) continue;\n for (const entrypoint in remote.entries) visit(entrypoint, remote);\n }\n}\n\ntype Covered = Pick<ReadonlySet<string>, 'has'>;\n\n// Counted rather than listed: the resolver's O(versions\u00B2) selection loop asks this once per remote per\n// candidate.\nexport function countUncoveredEntrypoints(remote: SharedVersionMeta, covered: Covered): number {\n let uncovered = 0;\n for (const entrypoint in remote.entries) {\n if (!covered.has(entrypoint)) uncovered++;\n }\n return uncovered;\n}\n", "import type { RemoteName } from '../remote/remote-info.contract';\nimport type { AcceptsTag } from './compatibility';\nimport type {\n SharedVersion,\n SharedVersionAction,\n SharedVersionMeta,\n VersionName,\n} from './version.contract';\n\n// Newest tag first, as `write()` orders a record. Leaves a tag's rows in their order (`sort` is stable).\nexport const byTag =\n (compare: (a: VersionName, b: VersionName) => number) =>\n (a: SharedVersion, b: SharedVersion): number =>\n compare(b.tag, a.tag);\n\nexport const rowAt = (\n versions: readonly SharedVersion[],\n tag: VersionName,\n action: SharedVersionAction\n): SharedVersion | undefined => versions.find(v => v.tag === tag && v.action === action);\n\n// One row per (tag, action): the first row of each absorbs the copies of the later ones, in place. `lead` is\n// that first row wherever it stands, so its copies stay in front.\nexport function mergeRows(versions: SharedVersion[], lead?: SharedVersion): SharedVersion[] {\n const merged = new Map<string, SharedVersion>();\n if (lead) merged.set(`${lead.tag}|${lead.action}`, lead);\n return versions.filter(v => {\n const key = `${v.tag}|${v.action}`;\n const first = merged.get(key);\n if (first === v) return true;\n if (!first) {\n merged.set(key, v);\n return true;\n }\n first.remotes.push(...v.remotes);\n return false;\n });\n}\n\n// `redirectRow` and `scopeRemote` can leave a `scope` row beside a shareable one at the same tag.\nexport function findVersionForTag(\n versions: SharedVersion[],\n tag: string\n): SharedVersion | undefined {\n let scoped: SharedVersion | undefined;\n for (const version of versions) {\n if (version.tag !== tag) continue;\n if (version.action !== 'scope') return version;\n scoped ??= version;\n }\n return scoped;\n}\n\n// Points a row at `tag`: its copies skip to it, and only the strict ones that reject it keep their own build,\n// split off into a `scope` row beside it. Returns the rows that replace `version`, in order; mutates it in place.\nexport function redirectRow(\n version: SharedVersion,\n tag: VersionName,\n acceptsTag: AcceptsTag\n): SharedVersion[] {\n const objecting = new Set(\n version.remotes.filter(r => r.strictVersion && !acceptsTag(tag, version.tag, r.requiredVersion))\n );\n\n if (objecting.size === 0) {\n version.action = 'skip';\n return [version];\n }\n if (objecting.size === version.remotes.length) {\n version.action = 'scope';\n return [version];\n }\n\n version.remotes = version.remotes.filter(r => !objecting.has(r));\n version.action = 'skip';\n // Beside its source rather than appended: the record stays newest-first, which `write()`\n // guarantees and a later election reads as \"the latest\".\n return [version, { tag: version.tag, host: false, action: 'scope', remotes: [...objecting] }];\n}\n\n// Moves each of `remotes`' copies out of every `share` and `skip` row into the `scope` row of their tag; a new scope\n// row goes right after its source, so the record stays newest-first. In one pass, yet ordered as if each remote\n// moved in turn: copies by remote then by row, a host's in front. Mutates the source rows, returns the new list.\nexport function scopeRemotes(\n versions: SharedVersion[],\n remotes: readonly RemoteName[]\n): SharedVersion[] {\n if (remotes.length === 0) return versions;\n const turn = new Map(remotes.map((remote, i) => [remote, i]));\n const moves = new Map<VersionName, Move[]>();\n versions.forEach((source, at) => {\n if (source.action === 'scope') return;\n const byTurn = new Map<number, SharedVersionMeta[]>();\n for (const copy of source.remotes) {\n const i = turn.get(copy.name);\n if (i === undefined) continue;\n const copies = byTurn.get(i);\n if (copies) copies.push(copy);\n else byTurn.set(i, [copy]);\n }\n if (byTurn.size === 0) return;\n // The host leads its row and a later election finds the host's tag by the flag, so both move with it.\n const hostTurn = source.host ? turn.get(source.remotes[0]!.name) : undefined;\n source.remotes = source.remotes.filter(r => !turn.has(r.name));\n if (hostTurn !== undefined) source.host = false;\n const tagMoves = moves.get(source.tag) ?? [];\n for (const [i, copies] of byTurn)\n tagMoves.push({ turn: i, at, source, copies, host: i === hostTurn });\n moves.set(source.tag, tagMoves);\n });\n\n const rows = [...versions];\n for (const [tag, tagMoves] of moves) {\n tagMoves.sort((a, b) => a.turn - b.turn || a.at - b.at);\n let scoped = rowAt(rows, tag, 'scope');\n if (!scoped) {\n scoped = { tag, host: false, action: 'scope', remotes: [] };\n rows.splice(rows.indexOf(tagMoves[0]!.source) + 1, 0, scoped);\n }\n for (const { copies, host } of tagMoves)\n if (host) {\n scoped.host = true;\n scoped.remotes.unshift(...copies);\n } else scoped.remotes.push(...copies);\n }\n return rows.filter(v => v.remotes.length > 0);\n}\n\ntype Move = {\n turn: number;\n at: number;\n source: SharedVersion;\n copies: SharedVersionMeta[];\n host: boolean;\n};\n", "import type { ForProcessingRemoteEntries } from '../driver-ports/init/for-processing-remote-entries.port';\nimport type { RemoteEntry, RemoteName, DenseSharedInfo } from 'lib/core/1.domain';\nimport { addRemoteToVersion } from 'lib/core/1.domain/externals/basis';\nimport { findVersionForTag } from 'lib/core/1.domain/externals/rows';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport {\n createRemoveCachedRemoteEntries,\n createStoreRemoteEntry,\n type SharedExternalContext,\n} from './store-remote-entry';\n\nexport function createProcessRemoteEntries(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'sharedExternalsRepo'\n | 'scopedExternalsRepo'\n | 'sharedChunksRepo'\n | 'versionCheck'\n >\n): ForProcessingRemoteEntries {\n const storeRemoteEntry = createStoreRemoteEntry(config, ports, 2);\n const removeCachedRemoteEntries = createRemoveCachedRemoteEntries(ports);\n\n /**\n * Step 2: Merge the remote-info, externals and chunks of the provided remoteEntry\n * objects into the cache. Shared externals are only registered here; resolution\n * happens later in determine-shared-externals, per scope, with global knowledge.\n */\n return remoteEntries => {\n try {\n const evictPerEntry = evictOverriddenRemotes(remoteEntries);\n remoteEntries.forEach(remoteEntry => {\n if (remoteEntry?.override && evictPerEntry.has(remoteEntry.name)) {\n removeCachedRemoteEntries(new Set([remoteEntry.name]));\n }\n storeRemoteEntry(remoteEntry, addSharedExternal);\n });\n return Promise.resolve(remoteEntries);\n } catch (e) {\n return Promise.reject(e);\n }\n };\n\n /**\n * Evict every overridden remote in one traversal of the shared-externals graph. Hoisting it ahead\n * of the merge is equivalent because removal only touches records carrying that remote's name \u2014\n * unless a name appears twice in the batch, which `get-remote-entries` permits when\n * `strictRemoteEntry` is off and a fetched entry disagrees with its manifest key.\n *\n * @returns the names that must still be evicted per entry, inside the merge loop.\n */\n function evictOverriddenRemotes(remoteEntries: RemoteEntry[]): Set<RemoteName> {\n const batched = new Set<RemoteName>();\n const repeated = new Set<RemoteName>();\n const seen = new Set<RemoteName>();\n\n for (const remoteEntry of remoteEntries) {\n if (!remoteEntry) continue;\n if (seen.has(remoteEntry.name)) repeated.add(remoteEntry.name);\n seen.add(remoteEntry.name);\n if (remoteEntry.override) batched.add(remoteEntry.name);\n }\n for (const remoteName of repeated) batched.delete(remoteName);\n\n removeCachedRemoteEntries(batched);\n return repeated;\n }\n\n function addSharedExternal(\n remoteEntry: RemoteEntry,\n _sharedInfo: DenseSharedInfo,\n {\n tag,\n remote,\n readRecord,\n scopeType,\n assertSameVersionCompatibility,\n write,\n }: SharedExternalContext\n ): void {\n const cached = readRecord();\n // Resolution is a function of the whole remote set, not of the tag list: a remote joining an\n // existing version can take the basis slot (changing what the version serves) and always adds\n // to `versionDemands` (changing what it accepts). Either way the cached actions are stale.\n if (scopeType !== 'strict') cached.dirty = true;\n\n const matchingVersion = findVersionForTag(cached.versions, tag);\n\n if (matchingVersion) {\n assertSameVersionCompatibility(matchingVersion);\n addRemoteToVersion(\n matchingVersion,\n remote,\n !matchingVersion.host && !!remoteEntry?.host,\n config.profile.enableDebugging\n );\n } else {\n cached.versions.push({\n tag,\n action: scopeType === 'strict' ? 'share' : 'skip',\n host: !!remoteEntry?.host,\n remotes: [remote],\n });\n }\n\n write();\n }\n}\n", "import type { SharedExternal } from './external.contract';\nimport type { SharedVersion, SharedVersionMeta } from './version.contract';\nimport { versionDemands } from './basis';\n\nexport type AcceptsTag = (offered: string, ownTag: string, requiredVersion: string) => boolean;\n\n// A copy runs the build it ships whatever its range says, so a range that excludes its own version (one\n// drifted from the lockfile) never rejects that version. Semver-equal, not string-equal: `v1.0.0` is `1.0.0`.\nexport function createAcceptsTag(\n isCompatible: (tag: string, requiredVersion: string) => boolean,\n compare: (a: string, b: string) => number\n): AcceptsTag {\n return (offered, ownTag, requiredVersion) =>\n isCompatible(offered, requiredVersion) || offered === ownTag || compare(offered, ownTag) === 0;\n}\n\nexport type VersionAcceptance = {\n // A version can only be redirected to `tag` if none of its remotes rejects that tag.\n accepts: (version: SharedVersion, tag: string) => boolean;\n // A representative copy that makes the redirect unsafe: it rejects `tag` while `strictVersion` is set,\n // so it keeps its own build instead of being deduped away. One is enough for the message and the\n // strict check; `redirectRow` enumerates the rest itself when it splits the version.\n objector: (version: SharedVersion, tag: string) => SharedVersionMeta | undefined;\n};\n\n// Every compatibility question is asked of the whole version, not of its basis: see `versionDemands`.\n// Computed once per external, since the selection loop is O(versions\u00B2).\nexport function versionAcceptance(\n external: SharedExternal,\n acceptsTag: AcceptsTag\n): VersionAcceptance {\n const demands = new Map<SharedVersion, SharedVersionMeta[]>(\n external.versions.map(v => [v, versionDemands(v)])\n );\n\n return {\n accepts: (version, tag) =>\n demands.get(version)!.every(d => acceptsTag(tag, version.tag, d.requiredVersion)),\n objector: (version, tag) =>\n demands\n .get(version)!\n .find(d => d.strictVersion && !acceptsTag(tag, version.tag, d.requiredVersion)),\n };\n}\n", "import type { SharedExternal, SharedVersion, SharedVersionMeta } from 'lib/core/1.domain';\nimport { mergeRows, redirectRow } from 'lib/core/1.domain/externals/rows';\nimport type { AcceptsTag, VersionAcceptance } from 'lib/core/1.domain/externals/compatibility';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\n\n// Fails init for a strict copy whose range rejects what is shared at `servedAt`; both are `name@tag`.\nexport function rejectIncompatible(\n config: LoggingConfig,\n copy: SharedVersionMeta,\n rejected: string,\n servedAt: string\n): never {\n config.log.error(\n 3,\n `[${copy.name}][${rejected}] Is not compatible with requiredRange '${copy.requiredVersion}' of shared ${servedAt}.`\n );\n throw new NFError(`External ${rejected} could not be shared.`);\n}\n\n/**\n * The tail of winner election: derive every other version's verdict from the chosen one, clear `dirty`.\n * `determine` is the only caller, and passes its `acceptsTag` plus the `acceptance` it already built for\n * the election.\n */\nexport function createApplyWinner(config: LoggingConfig & ModeConfig) {\n return function applyWinner(\n externalName: string,\n external: SharedExternal,\n winner: SharedVersion,\n acceptsTag: AcceptsTag,\n acceptance: VersionAcceptance\n ): SharedExternal {\n // Every copy accepts its own tag, so a lone version, like the winner, is never redirected or split.\n if (external.versions.length > 1) {\n const rebuilt: SharedVersion[] = [];\n\n for (const v of external.versions) {\n const objector =\n config.strict.strictExternalCompatibility && acceptance.objector(v, winner.tag);\n\n if (objector)\n rejectIncompatible(\n config,\n objector,\n `${externalName}@${v.tag}`,\n `${externalName}@${winner.tag}`\n );\n\n rebuilt.push(...redirectRow(v, winner.tag, acceptsTag));\n }\n\n // One row per (tag, action), which the record keeps: a warm record can already hold a `scope` row at\n // the tag a split produces. Merged after the loop, not during it: a row's verdict is not final until\n // the winner has been applied to it. The winner absorbs its tag's other rows, or the `share` below\n // would land on a row merged away.\n external.versions = mergeRows(rebuilt, winner);\n }\n\n winner.action = 'share';\n\n external.dirty = false;\n return external;\n };\n}\n", "import type { ForDeterminingSharedExternals } from '../driver-ports/init/for-determining-shared-externals.port';\nimport { GLOBAL_SCOPE, type SharedExternal, type SharedVersion } from 'lib/core/1.domain';\nimport { countUncoveredEntrypoints, forEachVersionEntry } from 'lib/core/1.domain/externals/basis';\nimport {\n type AcceptsTag,\n createAcceptsTag,\n versionAcceptance,\n} from 'lib/core/1.domain/externals/compatibility';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport { createApplyWinner } from './apply-winner';\n\nexport function createDetermineSharedExternals(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'versionCheck' | 'sharedExternalsRepo'>\n): ForDeterminingSharedExternals {\n const applyWinner = createApplyWinner(config);\n\n /**\n * Step 3: Determine which version is the optimal version to share.\n *\n * The shared external versions that were merged into the cache/storage caused the shared\n * external to be 'dirty', this step re-elects every dirty external by calculating the most optimal\n * version to share since only 1 version can be shared globally. Pooling runs first and writes every\n * member it elects with `dirty: false`, so determine never sees one. Every other copy\n * either skips onto the winner or, where its own range rejects it and `strictVersion` is set, is split\n * out into a scoped external of its own tag.\n *\n * Check the docs for a full explanation of the dependency resolver.\n *\n * Priority:\n * 1) Latest external defined in 'host' remoteEntry (if available).\n * 2) If defined in config, prioritize latest available version.\n * 3) Find most optimal version, by comparing potential extra downloads per version.\n *\n * @param config\n * @param adapters\n */\n return () => {\n const acceptsTag = createAcceptsTag(\n ports.versionCheck.isCompatible,\n ports.versionCheck.compare\n );\n\n for (const shareScope of ports.sharedExternalsRepo.getScopes()) {\n // The strict scope shares every tag side by side; an eviction still marks its externals dirty.\n if (ports.sharedExternalsRepo.scopeType(shareScope) === 'strict') continue;\n const sharedExternals = ports.sharedExternalsRepo.getFromScope(shareScope);\n\n try {\n Object.entries(sharedExternals)\n .filter(([_, e]) => e.dirty)\n .forEach(([name, external]) => {\n ports.sharedExternalsRepo.addOrUpdate(\n name,\n setVersionActions(name, external, acceptsTag),\n shareScope\n );\n });\n } catch (error) {\n config.log.error(\n 3,\n `[${shareScope ?? GLOBAL_SCOPE}] failed to determine shared externals.`,\n {\n sharedExternals,\n error,\n }\n );\n return Promise.reject(\n new NFError(\n `Could not determine shared externals in scope ${shareScope}.`,\n error as Error\n )\n );\n }\n }\n return Promise.resolve();\n };\n\n // Entrypoints declared by the versions `winner` would skip that none of its copies can serve. Every copy counts:\n // the serving build is decided later and may be any of them.\n function uncoveredTears(\n external: SharedExternal,\n winner: SharedVersion,\n accepts: (version: SharedVersion, tag: string) => boolean\n ): number {\n const covered = new Set<string>();\n forEachVersionEntry(winner, undefined, entrypoint => covered.add(entrypoint));\n return external.versions.reduce((sum, v) => {\n if (v === winner) return sum;\n if (!accepts(v, winner.tag)) return sum;\n return v.remotes.reduce((n, r) => n + countUncoveredEntrypoints(r, covered), sum);\n }, 0);\n }\n\n function setVersionActions(\n externalName: string,\n external: SharedExternal,\n acceptsTag: AcceptsTag\n ) {\n const acceptance = versionAcceptance(external, acceptsTag);\n\n if (external.versions.length === 1) {\n return applyWinner(externalName, external, external.versions[0]!, acceptsTag, acceptance);\n }\n\n const { accepts } = acceptance;\n\n let sharedVersion = external.versions.find(v => v.host);\n\n if (!sharedVersion && config.profile.latestSharedExternal) {\n sharedVersion = external.versions[0];\n }\n\n if (!sharedVersion) {\n // find version with least extra downloads, sorted by SEMVER version (O^2 complexity)\n let leastExtraDownloads = Number.MAX_VALUE;\n let leastTears = Number.MAX_VALUE;\n let leaderShared = false;\n // What a rejected version really costs: `applyWinner` splits it, so only the copies that themselves\n // reject the winner keep their own build. Cached copies are already downloaded and non-strict ones take\n // whatever is shared, so neither costs anything. Grouped by range so the O(versions\u00B2) selection loop\n // does not also scale with remote count.\n const selfServing = new Map<SharedVersion, { requiredVersion: string; copies: number }[]>(\n external.versions.map(v => {\n const groups = new Map<string, { requiredVersion: string; copies: number }>();\n for (const remote of v.remotes) {\n if (remote.cached || !remote.strictVersion) continue;\n const group = groups.get(remote.requiredVersion);\n if (group) group.copies++;\n else\n groups.set(remote.requiredVersion, {\n requiredVersion: remote.requiredVersion,\n copies: 1,\n });\n }\n return [v, [...groups.values()]];\n })\n );\n\n const costOf = (version: SharedVersion, tag: string) =>\n selfServing\n .get(version)!\n .reduce(\n (n, g) => (acceptsTag(tag, version.tag, g.requiredVersion) ? n : n + g.copies),\n 0\n );\n\n external.versions.forEach(vA => {\n const extraDownloads = external.versions.reduce((sum, vB) => sum + costOf(vB, vA.tag), 0);\n // A downloads tie goes to the version already shared, as keeping it saves a download, then to the one\n // that leaves fewest entrypoints uncovered across the versions it would skip (tears / scope-promotions).\n const alreadyShared = vA.action === 'share' && !!vA.remotes[0]?.cached;\n if (extraDownloads < leastExtraDownloads) {\n leastExtraDownloads = extraDownloads;\n leastTears = uncoveredTears(external, vA, accepts);\n leaderShared = alreadyShared;\n sharedVersion = vA;\n return;\n }\n if (extraDownloads > leastExtraDownloads || leaderShared) return;\n\n const tears = uncoveredTears(external, vA, accepts);\n if (alreadyShared || tears < leastTears) {\n leastTears = tears;\n leaderShared = alreadyShared;\n sharedVersion = vA;\n }\n });\n }\n\n if (!sharedVersion) {\n throw new NFError(`[${externalName}] Could not determine shared version!`);\n }\n\n // Determine action of other versions based on chosen sharedVersion\n return applyWinner(externalName, external, sharedVersion, acceptsTag, acceptance);\n }\n}\n", "// Iterative path halving: no stack growth in the browser.\nexport function unionFind() {\n const parent = new Map<string, string>();\n const find = (node: string): string => {\n for (let up = parent.get(node); up !== undefined; up = parent.get(node)) {\n const grand = parent.get(up);\n if (grand === undefined) return up;\n parent.set(node, grand);\n node = grand;\n }\n return node;\n };\n const union = (a: string, b: string): void => {\n const rootA = find(a);\n const rootB = find(b);\n if (rootA !== rootB) parent.set(rootB, rootA);\n };\n return { find, union };\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport { unionFind } from 'lib/utils/union-find';\nimport type { ExternalName, shareScope } from './external.contract';\nimport type { SharedVersionMeta, VersionName } from './version.contract';\n\n// An entrypoint as a consumer imports it; pooling keys by it, not by external name (see `pooling/builds.ts`).\nexport type Specifier = string;\n\n// An npm package name carries at most one `/` (after a leading `@scope`), so any deeper segment is a\n// subpath of the package above it: `@framework/core/testing` -> `@framework/core`, `rxjs/operators`\n// -> `rxjs`.\nexport function npmPackageOf(name: ExternalName): ExternalName {\n const depth = name.startsWith('@') ? 2 : 1;\n let cut = -1;\n for (let seen = 0; seen < depth; seen++) {\n cut = name.indexOf('/', cut + 1);\n if (cut === -1) return name;\n }\n return name.slice(0, cut);\n}\n\nexport type PackageOf = (specifier: Specifier) => ExternalName;\n\ntype StoredCopy = readonly [ExternalName, DeepReadonly<SharedVersionMeta>];\n\n// See docs/version-resolver.md \u00A7\"One build per package\".\nexport function packageOfIn(\n scope: DeepReadonly<shareScope>,\n loading: readonly StoredCopy[] = []\n): PackageOf {\n // A fast path, measured: without a declared library the records group by npm name anyway.\n if (!declaresLibrary(scope, loading)) return npmPackageOf;\n\n // Each component keeps its shortest name.\n const { find, union } = unionFind();\n const shortest = new Map<ExternalName, ExternalName>();\n for (const [name, copy] of copiesIn(scope, loading)) {\n const anchor = anchorOf(name, copy);\n for (const specifier in copy.entries) {\n const best = shorter(\n shortest.get(find(anchor)) ?? anchor,\n shortest.get(find(specifier)) ?? specifier\n );\n union(anchor, specifier);\n shortest.set(find(anchor), best);\n }\n }\n // An unlisted specifier joins whatever its npm name joined.\n return specifier => {\n const npm = npmPackageOf(specifier);\n return shortest.get(find(specifier)) ?? shortest.get(find(npm)) ?? npm;\n };\n}\n\nconst shorter = (a: ExternalName, b: ExternalName): ExternalName =>\n b.length < a.length || (b.length === a.length && compareStrings(b, a) < 0) ? b : a;\n\nfunction declaresLibrary(scope: DeepReadonly<shareScope>, loading: readonly StoredCopy[]): boolean {\n const isLibrary = (name: ExternalName, copies: readonly DeepReadonly<SharedVersionMeta>[]) =>\n npmPackageOf(name) !== name && copies.some(copy => copy.dense);\n return (\n loading.some(([name, copy]) => isLibrary(name, [copy])) ||\n Object.entries(scope).some(([name, external]) =>\n external.versions.some(version => isLibrary(name, version.remotes))\n )\n );\n}\n\n// A flat copy declares no package, so it is at least its npm package.\nconst anchorOf = (name: ExternalName, copy: DeepReadonly<SharedVersionMeta>): ExternalName =>\n copy.dense ? name : npmPackageOf(name);\n\nfunction* copiesIn(\n scope: DeepReadonly<shareScope>,\n loading: readonly StoredCopy[]\n): Generator<StoredCopy> {\n yield* loading;\n for (const [name, external] of Object.entries(scope))\n for (const version of external.versions) for (const copy of version.remotes) yield [name, copy];\n}\n\n// Tags per specifier that also pin the rest of their package: a package is one version, so its tag is the\n// root's, else the first entrypoint's \u2014 a package can ship entrypoints only (`material/table`, no root).\nexport class SpecifierTags extends Map<Specifier, VersionName> {\n private readonly packages = new Map<ExternalName, VersionName>();\n\n constructor(\n private readonly packageOf: PackageOf,\n entries: Iterable<readonly [Specifier, VersionName]> = []\n ) {\n super();\n for (const [specifier, tag] of entries) this.set(specifier, tag);\n }\n\n override set(specifier: Specifier, tag: VersionName): this {\n super.set(specifier, tag);\n const pkg = this.packageOf(specifier);\n if (pkg === specifier || !this.packages.has(pkg)) this.packages.set(pkg, tag);\n return this;\n }\n\n override clear(): void {\n super.clear();\n this.packages.clear();\n }\n\n pinnedTag(specifier: Specifier): VersionName | undefined {\n return this.get(specifier) ?? this.packages.get(this.packageOf(specifier));\n }\n}\n\nexport function groupByPackage<T>(\n items: Iterable<T>,\n nameOf: (item: T) => ExternalName,\n packageOf: PackageOf\n): Map<ExternalName, T[]> {\n const packages = new Map<ExternalName, T[]>();\n for (const item of items) {\n const pkg = packageOf(nameOf(item));\n const group = packages.get(pkg);\n if (group) group.push(item);\n else packages.set(pkg, [item]);\n }\n return packages;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type {\n ExternalName,\n RemoteName,\n SharedVersion,\n SharedVersionMeta,\n VersionName,\n} from 'lib/core/1.domain';\nimport {\n type PackageOf,\n type Specifier,\n SpecifierTags,\n} from 'lib/core/1.domain/externals/specifier';\nimport type { PoolMember } from './membership';\n\n// Keyed by specifier so flat and dense builds of one package compare.\n\nexport type Copy = {\n member: ExternalName;\n tag: VersionName;\n requiredVersion: string;\n strict: boolean;\n // Basis precedence puts the host's own copy first on a `host: true` version.\n host: boolean;\n specifiers: Specifier[];\n};\n\nexport type Build = {\n owner: RemoteName;\n tags: SpecifierTags;\n tagByMember: Map<ExternalName, VersionName>;\n host: boolean;\n};\n\nexport function copiesByRemote(members: readonly PoolMember[]): Map<RemoteName, Copy[]> {\n const shipped = new Map<RemoteName, Copy[]>();\n for (const member of members)\n for (const [remote, records] of recordsByRemote(member)) {\n let copies = shipped.get(remote);\n if (!copies) shipped.set(remote, (copies = []));\n for (const { version, meta } of records)\n copies.push({\n member: member.name,\n tag: version.tag,\n requiredVersion: meta.requiredVersion,\n strict: meta.strictVersion,\n host: version.host && meta === version.remotes[0],\n specifiers: Object.keys(meta.entries),\n });\n }\n return shipped;\n}\n\n// One record the remote ships for the member, with the row it sits in.\nexport type RemoteRecord = DeepReadonly<{ version: SharedVersion; meta: SharedVersionMeta }>;\n\n// A build ships a member at one tag, so a record at a second tag is one it cannot produce; the first tag wins\n// whole, so a build never covers a specifier at a tag it does not ship. Several records at that tag are one\n// build split across bundles, each its own copy (#133).\nexport function recordsByRemote(member: PoolMember): Map<RemoteName, RemoteRecord[]> {\n const records = new Map<RemoteName, RemoteRecord[]>();\n for (const version of member.external.versions)\n for (const meta of version.remotes) {\n const mine = records.get(meta.name);\n if (!mine) records.set(meta.name, [{ version, meta }]);\n else if (mine[0]!.version.tag === version.tag) mine.push({ version, meta });\n }\n return records;\n}\n\nexport const specifierCount = (copies: readonly Copy[]): number =>\n copies.reduce((n, copy) => n + copy.specifiers.length, 0);\n\nexport function buildOf(owner: RemoteName, copies: readonly Copy[], packageOf: PackageOf): Build {\n const tags = new SpecifierTags(packageOf);\n const tagByMember = new Map<ExternalName, VersionName>();\n for (const copy of copies) {\n for (const specifier of copy.specifiers)\n if (!tags.has(specifier)) tags.set(specifier, copy.tag);\n tagByMember.set(copy.member, copy.tag);\n }\n return { owner, tags, tagByMember, host: copies.some(c => c.host) };\n}\n", "import type { AcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport type { Specifier, SpecifierTags } from 'lib/core/1.domain/externals/specifier';\nimport type { Build, Copy } from './builds';\n\n// Plain loops: the election calls these per remote pair.\n// See docs/version-resolver.md \u00A7\"How pooling resolves\".\n\n// A specifier the tags do not list is still pinned by its package's tag: a flat `core/testing` at 22.0.6 next\n// to a build's `core` at 22.0.8 is two cores, whoever lists the entrypoint.\nexport function agrees(copies: readonly Copy[], tags: SpecifierTags): boolean {\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const tag = tags.pinnedTag(s);\n if (tag !== undefined && tag !== copy.tag) return false;\n }\n return true;\n}\n\nexport function serves(\n copies: readonly Copy[],\n tags: SpecifierTags,\n acceptsTag: AcceptsTag\n): boolean {\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const tag = tags.get(s);\n if (tag === undefined || !acceptsTag(tag, copy.tag, copy.requiredVersion)) return false;\n }\n return true;\n}\n\n// One build must have shipped the combination the copies would run at these tags; a build witnesses\n// its packages' other entrypoints at its tag. The gap is the first specifier no build ships next to\n// the ones before it.\nexport function unwitnessedGap(\n copies: readonly Copy[],\n tags: SpecifierTags,\n builds: Iterable<Build>\n): Specifier | undefined {\n const specifiers = copies.flatMap(c => c.specifiers);\n let gap = 0;\n for (const build of builds) {\n const miss = specifiers.findIndex(s => build.tags.pinnedTag(s) !== tags.get(s));\n if (miss === -1) return undefined;\n gap = Math.max(gap, miss);\n }\n return specifiers[gap];\n}\n", "import type { ExternalName, PoolCause, RemoteName, VersionName } from 'lib/core/1.domain';\nimport type { AcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport {\n type PackageOf,\n type Specifier,\n SpecifierTags,\n} from 'lib/core/1.domain/externals/specifier';\nimport { type Build, buildOf, type Copy, copiesByRemote } from './builds';\nimport type { PoolMember } from './membership';\nimport { agrees, serves, unwitnessedGap } from './rules';\nimport { compareStrings } from 'lib/utils/compare-strings';\n\n// See docs/version-resolver.md \u00A7\"How pooling resolves\".\n\ntype ElectionInput = {\n members: readonly PoolMember[];\n packageOf: PackageOf;\n acceptsTag: AcceptsTag;\n compare: (a: VersionName, b: VersionName) => number;\n // The stored record's winner, which breaks round-1 ties.\n previousWinner?: RemoteName;\n latestFirst: boolean;\n};\n\n// `unshipped`: the map serves every specifier, but no build shipped them together.\nexport type PoolMiss =\n | { cause: 'incompatible'; member: ExternalName; tag: VersionName; strict: boolean }\n | { cause: 'uncovered'; gap: Specifier; unshipped?: true };\n\n// A subpool's owner is placed in its own subpool.\nexport type Placement =\n { kind: 'global' } | { kind: 'subpool'; owner: RemoteName } | { kind: 'self'; cause: PoolCause };\n\nexport type Election = {\n winner: RemoteName;\n winnerIsHost: boolean;\n globalTags: SpecifierTags;\n placements: ReadonlyMap<RemoteName, Placement>;\n // In warning order: subpools in election order, then self. A strict range's rejection wins, as\n // `strictExternalCompatibility` refuses that. Undefined only for a subpool's owner the global map\n // would serve.\n misses: ReadonlyMap<RemoteName, PoolMiss | undefined>;\n};\n\ntype Subpool = { owner: RemoteName; remotes: RemoteName[] };\n\ntype Pool = ElectionInput & {\n shipped: Map<RemoteName, Copy[]>;\n builds: Map<RemoteName, Build>;\n packages: Map<RemoteName, Map<ExternalName, PackageCopy | null>>;\n // In record order: the order remotes first appear in the pool's versions.\n remotes: RemoteName[];\n servesAt: (remote: RemoteName, tags: SpecifierTags) => boolean;\n agreesAt: (remote: RemoteName, tags: SpecifierTags) => boolean;\n};\n\n// What each step hands the next.\ntype State = {\n readonly winner: RemoteName;\n globalTags: SpecifierTags;\n globalRemotes: Set<RemoteName>;\n // The packages the winner does not ship that the global tags publish.\n extensions: Set<ExternalName>;\n subpools: Subpool[];\n pending: RemoteName[];\n};\n\nexport function elect(input: ElectionInput): Election {\n const shipped = copiesByRemote(input.members);\n const builds = new Map<RemoteName, Build>();\n for (const [owner, copies] of shipped) builds.set(owner, buildOf(owner, copies, input.packageOf));\n const pool: Pool = {\n ...input,\n shipped,\n builds,\n packages: new Map(\n [...shipped].map(([owner, copies]) => [owner, packageCopies(owner, copies, input.packageOf)])\n ),\n remotes: [...shipped.keys()],\n servesAt: (remote, tags) => serves(shipped.get(remote)!, tags, input.acceptsTag),\n agreesAt: (remote, tags) => agrees(shipped.get(remote)!, tags),\n };\n\n // The host cannot be repointed, so its build is the global one whenever it ships any member.\n const hostRemote = pool.remotes.find(r => builds.get(r)!.host);\n const state = roundOne(pool, hostRemote);\n formSubpools(pool, state);\n // Last, so it only moves remotes no later round could place in a subpool.\n addExtensions(pool, state);\n promote(pool, state);\n while (settle(pool, state)) formSubpools(pool, state);\n\n const firstSeen = new Map(pool.remotes.map((r, i) => [r, i]));\n const self = state.pending.sort((a, b) => firstSeen.get(a)! - firstSeen.get(b)!);\n return {\n winner: state.winner,\n winnerIsHost: hostRemote !== undefined,\n globalTags: state.globalTags,\n ...placeRemotes(state.globalRemotes, state.subpools, self, r => missOf(pool, state, r)),\n };\n}\n\n// The first member both ship, in pool order, whose tags differ decides, so two unrelated version lines are\n// never compared.\nfunction newer(pool: Pool, a: Build, b: Build): number {\n for (const { name } of pool.members) {\n const tagA = a.tagByMember.get(name);\n const tagB = b.tagByMember.get(name);\n if (tagA === undefined || tagB === undefined) continue;\n const d = pool.compare(tagA, tagB);\n if (d !== 0) return d;\n }\n return 0;\n}\n\n// What the keys leave tied goes to the newer build, then to the name that sorts first. `newer` ties unrelated\n// builds, so three can still rank in a cycle; presorting by name keeps record order out of that too.\nfunction rank<C extends { build: Build }>(pool: Pool, candidates: C[], keys: ((c: C) => number)[]) {\n const scored = [...candidates]\n .sort((a, b) => compareStrings(a.build.owner, b.build.owner))\n .map(c => ({ c, k: keys.map(key => key(c)) }));\n scored.sort((a, b) => {\n for (let i = 0; i < keys.length; i++) {\n const d = b.k[i]! - a.k[i]!;\n if (d !== 0) return d;\n }\n return newer(pool, b.c.build, a.c.build) || compareStrings(a.c.build.owner, b.c.build.owner);\n });\n return scored[0]?.c;\n}\n\nfunction roundOne(pool: Pool, hostRemote: RemoteName | undefined): State {\n const { remotes } = pool;\n type Candidate = {\n build: Build;\n served: RemoteName[];\n // Remotes that agree without being served: when no build serves more than itself, they separate a build\n // its peers share from an outlier.\n agreeing: number;\n };\n const scored = new Map<string, Omit<Candidate, 'build'>>();\n const round1 = (hostRemote ? [hostRemote] : remotes).map<Candidate>(owner => {\n const build = pool.builds.get(owner)!;\n // Keyed in insertion order, which decides `pinnedTag`.\n const key = JSON.stringify([[...build.tags], [...build.tagByMember]]);\n let score = scored.get(key);\n if (!score) {\n const served = new Set(remotes.filter(r => pool.servesAt(r, build.tags)));\n const agreeing = remotes.filter(r => !served.has(r) && pool.agreesAt(r, build.tags)).length;\n scored.set(key, (score = { served: [...served], agreeing }));\n }\n return { build, ...score };\n });\n const newerThan = (c: Candidate) => round1.filter(o => newer(pool, c.build, o.build) > 0).length;\n const round1Winner = rank(pool, round1, [\n ...(pool.latestFirst ? [newerThan] : []),\n c => c.served.length,\n c => c.agreeing,\n c => (c.build.owner === pool.previousWinner ? 1 : 0),\n ])!;\n\n const winner = round1Winner.build.owner;\n const globalTags = new SpecifierTags(pool.packageOf, round1Winner.build.tags);\n const globalRemotes = new Set([winner, ...round1Winner.served]);\n\n const pending = remotes.filter(r => !globalRemotes.has(r));\n return { winner, globalTags, globalRemotes, extensions: new Set(), subpools: [], pending };\n}\n\nfunction formSubpools(pool: Pool, state: State): void {\n // The global tags hold still within a call and pending only shrinks, so who each build serves is found once.\n const servable = new Map(\n state.pending.map(owner => {\n const build = pool.builds.get(owner)!;\n const served = state.pending.filter(r => pool.servesAt(r, build.tags));\n return [owner, { build, served }];\n })\n );\n for (;;) {\n const stillPending = new Set(state.pending);\n const candidates = state.pending\n .map(owner => {\n const { build, served } = servable.get(owner)!;\n return { build, served: served.filter(r => stillPending.has(r)) };\n })\n .filter(c => c.served.includes(c.build.owner) && c.served.length >= 2);\n const best = rank(pool, candidates, [c => c.served.length]);\n if (!best) break;\n state.subpools.push({ owner: best.build.owner, remotes: best.served });\n state.pending = state.pending.filter(r => !best.served.includes(r));\n }\n}\n\nfunction promote(pool: Pool, state: State): void {\n const { globalTags, globalRemotes } = state;\n // Whoever the global tags now serve resolves globally, in a subpool or not \u2014 but a subpool's owner only once\n // no other member needs it. A subpool of one is none: its owner goes global when served, else serves itself.\n const takesGlobal = (remote: RemoteName) =>\n pool.servesAt(remote, globalTags) &&\n unwitnessedGap(pool.shipped.get(remote)!, globalTags, pool.builds.values()) === undefined;\n for (const remote of state.pending) if (takesGlobal(remote)) globalRemotes.add(remote);\n state.pending = state.pending.filter(r => !globalRemotes.has(r));\n for (const subpool of state.subpools) {\n const moved = subpool.remotes.filter(r => r !== subpool.owner && takesGlobal(r));\n for (const remote of moved) globalRemotes.add(remote);\n subpool.remotes = subpool.remotes.filter(r => !moved.includes(r));\n }\n state.subpools = state.subpools.filter(subpool => {\n if (subpool.remotes.length >= 2) return true;\n if (takesGlobal(subpool.owner)) globalRemotes.add(subpool.owner);\n else state.pending.push(subpool.owner);\n return false;\n });\n}\n\n// A package round 1 does not ship at all is published from one build that agrees with the global tags, so it\n// runs whole from that build: the copy that contains the most others. A subpool copy resolves globally only\n// when its subpool's owner agrees. Under a host, the agreeing members of subpools whose build disagrees with\n// the host then offer the packages still missing, so they can move onto the host's runtime.\nfunction addExtensions(pool: Pool, state: State): void {\n const { globalTags, globalRemotes } = state;\n const runsOn = (remote: RemoteName) =>\n state.subpools.find(p => p.remotes.includes(remote))?.owner ?? remote;\n const agreeing = pool.remotes.filter(r => !globalRemotes.has(r) && pool.agreesAt(r, globalTags));\n const runsGlobally = (remote: RemoteName) => pool.agreesAt(runsOn(remote), globalTags);\n const offered = offers(pool, globalTags, agreeing.filter(runsGlobally));\n const fill = pool.builds.get(state.winner)!.host ? agreeing.filter(r => !runsGlobally(r)) : [];\n for (const [pkg, offer] of offers(pool, globalTags, fill))\n if (!offered.has(pkg)) offered.set(pkg, offer);\n for (const [pkg, offer] of offered) {\n if (!offer) continue;\n state.extensions.add(pkg);\n for (const s of offer.specifiers) globalTags.set(s, offer.tag);\n }\n}\n\ntype PackageCopy = { owner: RemoteName; tag: VersionName; specifiers: Set<Specifier> };\n\n// A remote's copy of each package, or null where it ships the package at two tags.\nfunction packageCopies(\n owner: RemoteName,\n copies: readonly Copy[],\n packageOf: PackageOf\n): Map<ExternalName, PackageCopy | null> {\n const packages = new Map<ExternalName, PackageCopy | null>();\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const pkg = packageOf(s);\n const seen = packages.get(pkg);\n if (seen === undefined) packages.set(pkg, { owner, tag: copy.tag, specifiers: new Set([s]) });\n else if (seen && seen.tag !== copy.tag) packages.set(pkg, null);\n else seen?.specifiers.add(s);\n }\n return packages;\n}\n\n// Per package the remotes ship and the global tags do not pin: the copy chosen to publish it, or null when\n// they ship it at two tags.\nfunction offers(pool: Pool, globalTags: SpecifierTags, remotes: RemoteName[]) {\n const candidates = new Map<ExternalName, (PackageCopy | null)[]>();\n for (const owner of remotes)\n for (const [pkg, copy] of pool.packages.get(owner)!)\n if (globalTags.pinnedTag(pkg) === undefined)\n candidates.set(pkg, [...(candidates.get(pkg) ?? []), copy]);\n const offered = new Map<ExternalName, PackageCopy | null>();\n for (const [pkg, copies] of candidates)\n offered.set(pkg, oneTag(copies) ? coveringCopy(copies) : null);\n return offered;\n}\n\nconst oneTag = (copies: (PackageCopy | null)[]): copies is PackageCopy[] =>\n copies.every(c => c !== null && c.tag === copies[0]!.tag);\n\n// The copy that contains the most others, then the widest; ties go to the name that sorts first.\nfunction coveringCopy(candidates: PackageCopy[]): PackageCopy {\n const scored = candidates.map(c => ({\n c,\n covers: candidates.filter(o => contains(c.specifiers, o.specifiers)).length,\n }));\n scored.sort(\n (a, b) =>\n b.covers - a.covers ||\n b.c.specifiers.size - a.c.specifiers.size ||\n compareStrings(a.c.owner, b.c.owner)\n );\n return scored[0]!.c;\n}\n\nconst contains = (a: ReadonlySet<Specifier>, b: ReadonlySet<Specifier>) =>\n [...b].every(s => a.has(s));\n\n// The global map publishes a package the winner does not ship only while a global remote ships a copy of\n// exactly its tags: the chosen one or another, as the same files at one tag are the same code. Otherwise the\n// package's tags drop, whole; whoever that leaves unserved joins the first subpool whose owner serves it,\n// else goes back to the later rounds.\nfunction settle(pool: Pool, state: State): boolean {\n const { globalTags, globalRemotes, extensions } = state;\n let demoted = false;\n for (;;) {\n const dropped = new Set([...extensions].filter(pkg => !publishedWhole(pool, state, pkg)));\n if (dropped.size === 0) return demoted;\n for (const pkg of dropped) extensions.delete(pkg);\n const kept = [...globalTags].filter(([s]) => !dropped.has(pool.packageOf(s)));\n globalTags.clear();\n for (const [s, tag] of kept) globalTags.set(s, tag);\n for (const remote of globalRemotes)\n if (remote !== state.winner && !pool.servesAt(remote, globalTags)) {\n globalRemotes.delete(remote);\n const subpool = state.subpools.find(p =>\n pool.servesAt(remote, pool.builds.get(p.owner)!.tags)\n );\n if (subpool) subpool.remotes.push(remote);\n else state.pending.push(remote);\n demoted = true;\n }\n }\n}\n\nfunction publishedWhole(pool: Pool, state: State, pkg: string): boolean {\n const published = new Set([...state.globalTags.keys()].filter(s => pool.packageOf(s) === pkg));\n const tag = state.globalTags.pinnedTag(pkg);\n return [...state.globalRemotes].some(remote => {\n const copy = pool.packages.get(remote)!.get(pkg);\n return (\n !!copy &&\n copy.tag === tag &&\n copy.specifiers.size === published.size &&\n contains(copy.specifiers, published)\n );\n });\n}\n\nfunction missOf(pool: Pool, state: State, remote: RemoteName): PoolMiss | undefined {\n const { globalTags } = state;\n const copies = pool.shipped.get(remote)!;\n let rejected: PoolMiss | undefined;\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const tag = globalTags.get(s);\n if (tag === undefined || pool.acceptsTag(tag, copy.tag, copy.requiredVersion)) continue;\n if (copy.strict) return { cause: 'incompatible', member: copy.member, tag, strict: true };\n rejected ??= { cause: 'incompatible', member: copy.member, tag, strict: false };\n }\n if (rejected) return rejected;\n for (const copy of copies)\n for (const s of copy.specifiers) if (!globalTags.has(s)) return { cause: 'uncovered', gap: s };\n const gap = unwitnessedGap(copies, globalTags, pool.builds.values());\n if (gap) return { cause: 'uncovered', gap, unshipped: true };\n // Everyone else the final global tags serve is global, so only a subpool's owner can lack a reason.\n if (state.subpools.some(p => p.owner === remote)) return undefined;\n throw new Error(`'${remote}' missed the global map with nothing it rejects or lacks.`);\n}\n\n// A member that joined since carries no winner yet; only two stored winners that conflict void it.\nexport function previousWinner(members: PoolMember[]): RemoteName | undefined {\n const winners = new Set(members.flatMap(m => m.external.poolWinner ?? []));\n const [winner] = winners;\n if (winners.size !== 1) return undefined;\n const ships = members.some(m =>\n m.external.versions.some(v => v.remotes.some(r => r.name === winner))\n );\n return ships ? winner : undefined;\n}\n\nfunction placeRemotes(\n globalRemotes: ReadonlySet<RemoteName>,\n subpools: readonly Subpool[],\n self: readonly RemoteName[],\n missOf: (remote: RemoteName) => PoolMiss | undefined\n): Pick<Election, 'placements' | 'misses'> {\n const misses = new Map<RemoteName, PoolMiss | undefined>();\n for (const remote of [...subpools.flatMap(p => p.remotes), ...self])\n misses.set(remote, missOf(remote));\n const placements = new Map<RemoteName, Placement>();\n for (const remote of globalRemotes) placements.set(remote, { kind: 'global' });\n for (const { owner, remotes } of subpools)\n for (const remote of remotes) placements.set(remote, { kind: 'subpool', owner });\n for (const remote of self)\n placements.set(remote, { kind: 'self', cause: misses.get(remote)!.cause });\n return { placements, misses };\n}\n", "import type { ExternalName, SharedExternal, shareScope } from 'lib/core/1.domain';\nimport { type PackageOf, packageOfIn } from 'lib/core/1.domain/externals/specifier';\nimport type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport { unionFind } from 'lib/utils/union-find';\n\n// Unique per share scope: the most-declared of the labels merged into the pool.\nexport type PoolName = string;\n\nexport type PoolMember = {\n name: ExternalName;\n external: DeepReadonly<SharedExternal>;\n};\n\nexport type Membership = {\n pools: Map<PoolName, PoolMember[]>;\n // In scope order.\n labelledAlone: ExternalName[];\n packageOf: PackageOf;\n};\n\n// A copy the record doesn't hold yet: its external and its `pool` label.\nexport type LabelledCopy = { name: ExternalName; pool?: string };\n\n// A label is one node across every remote: the label is the pool's identity.\n// NUL-separated so a label can never alias an external.\nconst extNode = (name: ExternalName): string => `ext\\x00${name}`;\nconst labelNode = (label: string): string => `label\\x00${label}`;\n\nconst labelOf = (pool?: string): string | undefined => pool?.trim() || undefined;\n\n// One entry per declaring copy, which `mostDeclaredLabel` counts; in scope order.\nfunction labelsIn(sharedExternals: DeepReadonly<shareScope>): Map<ExternalName, string[]> {\n const labelsOf = new Map<ExternalName, string[]>();\n for (const [name, external] of Object.entries(sharedExternals))\n labelsOf.set(\n name,\n external.versions.flatMap(v => v.remotes.flatMap(r => labelOf(r.pool) ?? []))\n );\n return labelsOf;\n}\n\n// A pool is a connected component of `external -> label` and `entrypoint -> package` edges; see\n// docs/version-resolver.md \u00A7\"Enabling pooling\". Components in `labelsOf` order, each with a label.\nfunction labelledComponents(\n labelsOf: ReadonlyMap<ExternalName, readonly string[]>,\n packageOf: PackageOf\n): ExternalName[][] {\n const { find, union } = unionFind();\n for (const [name, labels] of labelsOf)\n for (const label of labels) union(extNode(name), labelNode(label));\n\n // An entrypoint follows its package into whatever pool the package joins, labelled or not: a flat build\n // that labels only the package would otherwise leave its entrypoints out \u2014 measured as a torn package.\n // The package's node needs no root external, so a package that ships only entrypoints stays one unit too.\n for (const name of labelsOf.keys()) {\n const owner = packageOf(name);\n if (owner !== name) union(extNode(name), extNode(owner));\n }\n\n const byComponent = new Map<string, ExternalName[]>();\n for (const name of labelsOf.keys()) {\n const root = find(extNode(name));\n const names = byComponent.get(root) ?? byComponent.set(root, []).get(root)!;\n names.push(name);\n }\n // A property of the component, not of one member: an entrypoint carries no label of its own yet pools\n // with the package that does.\n return [...byComponent.values()].filter(names => names.some(n => labelsOf.get(n)!.length > 0));\n}\n\nexport function buildPools(\n sharedExternals: DeepReadonly<shareScope>,\n packageOf: PackageOf = packageOfIn(sharedExternals)\n): Membership {\n const labelsOf = labelsIn(sharedExternals);\n // Unique without suffixing: a label belongs to exactly one component, so two pools never pick the same one.\n const pools = new Map<PoolName, PoolMember[]>();\n const labelledAlone: ExternalName[] = [];\n for (const names of labelledComponents(labelsOf, packageOf)) {\n if (names.length < 2) labelledAlone.push(names[0]!);\n else {\n const members = names.map(name => ({ name, external: sharedExternals[name]! }));\n pools.set(\n mostDeclaredLabel(members, labelsOf),\n members.sort((a, b) => compareStrings(a.name, b.name))\n );\n }\n }\n return { pools, labelledAlone, packageOf };\n}\n\n// The packages `buildPools` pools once `copies` are stored in the scope.\nexport function pooledPackagesWith(\n sharedExternals: DeepReadonly<shareScope>,\n copies: readonly LabelledCopy[],\n packageOf: PackageOf\n): Set<ExternalName> {\n const labelsOf = labelsIn(sharedExternals);\n for (const { name, pool } of copies) {\n const labels = labelsOf.get(name) ?? [];\n const label = labelOf(pool);\n labelsOf.set(name, label === undefined ? labels : [...labels, label]);\n }\n return new Set(\n labelledComponents(labelsOf, packageOf)\n .filter(names => names.length > 1)\n .flatMap(names => names.map(packageOf))\n );\n}\n\nfunction mostDeclaredLabel(\n members: readonly PoolMember[],\n labelsOf: ReadonlyMap<ExternalName, readonly string[]>\n): string {\n const counts = new Map<string, number>();\n for (const member of members)\n for (const label of labelsOf.get(member.name)!) counts.set(label, (counts.get(label) ?? 0) + 1);\n\n let best = '';\n let top = 0;\n for (const [label, count] of counts)\n if (count > top || (count === top && compareStrings(label, best) < 0))\n [best, top] = [label, count];\n return best;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type { SharedExternal, shareScope } from '../externals/external.contract';\n\n// Outside a pool, pool results are stale. The declared `pool` label is pooling's input, not a result, and\n// always stays.\nexport function hasPoolResults(external: DeepReadonly<SharedExternal>): boolean {\n if (external.poolName !== undefined || external.poolWinner !== undefined) return true;\n return external.versions.some(v =>\n v.remotes.some(r => r.servedBy !== undefined || r.poolCause !== undefined)\n );\n}\n\n// Stored results outlive the last label that left, so they count; read from the record, not this init.\nexport function scopeHasPoolState(scope: DeepReadonly<shareScope>): boolean {\n for (const name in scope) {\n const external = scope[name]!;\n if (hasPoolResults(external)) return true;\n for (const version of external.versions)\n for (const remote of version.remotes) if (remote.pool?.trim()) return true;\n }\n return false;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type {\n ExternalName,\n PoolCause,\n RemoteName,\n SharedExternal,\n SharedVersion,\n SharedVersionMeta,\n shareScope,\n VersionName,\n} from 'lib/core/1.domain';\nimport { addRemoteToVersion } from 'lib/core/1.domain/externals/basis';\nimport { byTag, mergeRows, rowAt } from 'lib/core/1.domain/externals/rows';\nimport type { Election } from './election';\nimport type { PoolMember, PoolName } from './membership';\n\nexport type PlacedPool = Election & { poolName: PoolName };\n\n// One row per (tag, action); see docs/version-resolver.md \u00A7\"How the verdicts land in the record and the map\".\nexport function memberRecord(\n member: PoolMember,\n pool: PlacedPool,\n compare: (a: VersionName, b: VersionName) => number\n): SharedExternal {\n const { globalTags, placements } = pool;\n // The external's own specifier fixes its shared tag; a package can ship only secondary entrypoints\n // (`material/table` without `material`), so failing that it is whatever round 1 serves any of them at.\n let sharedTag = globalTags.get(member.name);\n for (const version of member.external.versions)\n for (const meta of version.remotes)\n for (const s in meta.entries) sharedTag ??= globalTags.get(s);\n\n const claimsGlobally = (name: RemoteName) => placements.get(name)!.kind === 'global';\n\n const placed: SharedVersion[] = [];\n let winnerRow: SharedVersion | undefined;\n const place = (tag: VersionName, action: SharedVersion['action'], meta: SharedVersionMeta) => {\n const row = { tag, host: false, action, remotes: [meta] };\n placed.push(row);\n if (meta.name !== pool.winner) return;\n winnerRow ??= row;\n row.host = pool.winnerIsHost;\n };\n\n for (const version of member.external.versions)\n for (const stored of version.remotes) {\n const { servedBy: _servedBy, poolCause: _poolCause, ...rest } = stored;\n // The import map is rebuilt from scratch, so it re-marks what it publishes.\n const meta = { ...rest, cached: false };\n const placement = placements.get(meta.name)!;\n if (placement.kind === 'global')\n place(version.tag, version.tag === sharedTag ? 'share' : 'skip', meta);\n else if (placement.kind === 'subpool')\n place(version.tag, 'skip', { ...meta, servedBy: placement.owner });\n else place(version.tag, 'scope', { ...meta, poolCause: placement.cause });\n }\n\n // The winner's copies lead their row, every record of a split build (#133): `remotes[0]` is the basis, and\n // the import map publishes the first copy listing a specifier. Stable, so ties keep their stored order.\n const rank = (name: RemoteName) => (name === pool.winner ? 0 : claimsGlobally(name) ? 1 : 2);\n const rows = mergeRows(placed, winnerRow);\n for (const row of rows) row.remotes.sort((a, b) => rank(a.name) - rank(b.name));\n\n const order = { share: 0, skip: 1, scope: 2 };\n const newest = byTag(compare);\n const versions = rows.sort((a, b) => newest(a, b) || order[a.action] - order[b.action]);\n\n return { dirty: false, poolName: pool.poolName, versions };\n}\n\nexport type CopyMove = { cause: PoolCause } | { fromMap: true };\n\n// A fresh record, only the loaded remote's copy moved.\nexport function movedRecord(\n external: SharedExternal,\n remote: RemoteName,\n move: CopyMove,\n compare: (a: VersionName, b: VersionName) => number\n): SharedExternal {\n return withoutStaleServingBuild(moveCopy(external, remote, move, compare));\n}\n\n// The claim table trusts `servingBuild`, so a move that takes the named copy out of every share row drops it.\nfunction withoutStaleServingBuild(record: SharedExternal): SharedExternal {\n const { servingBuild, ...rest } = record;\n if (servingBuild === undefined) return record;\n const shares = record.versions.some(\n v => v.action === 'share' && v.remotes.some(r => r.name === servingBuild)\n );\n return shares ? record : rest;\n}\n\nfunction moveCopy(\n external: SharedExternal,\n remote: RemoteName,\n move: CopyMove,\n compare: (a: VersionName, b: VersionName) => number\n): SharedExternal {\n if ('fromMap' in move) return recordFromMap(external, remote);\n\n const moved: { tag: string; meta: SharedVersionMeta }[] = [];\n const versions = external.versions\n .map(v => {\n const replaced = new Map<SharedVersionMeta, SharedVersionMeta>();\n for (const copy of v.remotes) {\n if (copy.name !== remote) continue;\n const { servedBy: _servedBy, ...rest } = copy;\n replaced.set(copy, { ...rest, cached: true, poolCause: move.cause });\n }\n if (replaced.size === 0) return v;\n if (v.action === 'scope') return { ...v, remotes: v.remotes.map(r => replaced.get(r) ?? r) };\n for (const meta of replaced.values()) moved.push({ tag: v.tag, meta });\n return { ...v, remotes: v.remotes.filter(r => !replaced.has(r)) };\n })\n // A version only the loaded remote held \u2014 a `share` it introduced \u2014 leaves with it.\n .filter(v => v.remotes.length > 0);\n\n for (const { tag, meta } of moved) {\n const scoped = rowAt(versions, tag, 'scope');\n if (!scoped) versions.push({ tag, action: 'scope', host: false, remotes: [meta] });\n else versions[versions.indexOf(scoped)] = { ...scoped, remotes: [...scoped.remotes, meta] };\n }\n\n return { ...external, versions: versions.sort(byTag(compare)) };\n}\n\n// A copy that now runs the map's files moves into a skip row at its tag: it publishes nothing. A tag keeps one\n// row per action, so it joins a skip row already there.\nfunction recordFromMap(external: SharedExternal, remote: RemoteName): SharedExternal {\n // The copy sits alone in the share row it opened, among other islands in a scope row, or in a share row it\n // joined at the same tag, whose other copies stay.\n const opened = external.versions.find(\n v => v.action !== 'skip' && v.remotes.some(r => r.name === remote)\n )!;\n const joined = rowAt(external.versions, opened.tag, 'skip');\n const into = joined\n ? { ...joined, remotes: [...joined.remotes] }\n : { ...opened, action: 'skip' as const, remotes: [] };\n for (const copy of opened.remotes)\n if (copy.name === remote) addRemoteToVersion(into, { ...copy, cached: false });\n\n const versions = external.versions.flatMap(v => {\n if (v === joined) return [into];\n if (v !== opened) return [v];\n const left = { ...v, remotes: v.remotes.filter(r => r.name !== remote) };\n return [...(left.remotes.length > 0 ? [left] : []), ...(joined ? [] : [into])];\n });\n return { ...external, versions };\n}\n\nexport function withoutPoolResults(external: DeepReadonly<SharedExternal>): SharedExternal {\n const { poolName: _poolName, poolWinner: _poolWinner, ...rest } = external;\n return {\n ...rest,\n versions: external.versions.map(v => ({\n ...v,\n remotes: v.remotes.map(({ servedBy: _servedBy, poolCause: _poolCause, ...meta }) => meta),\n })),\n };\n}\n\n// Pool results are kept: a pool nobody re-elected can still be renamed by another. An external in no pool\n// keeps its stored name until the next dirty init strips it.\nexport function renamedRecords(\n scope: shareScope,\n pools: ReadonlyMap<PoolName, readonly PoolMember[]>\n): [ExternalName, SharedExternal][] {\n const renamed: [ExternalName, SharedExternal][] = [];\n for (const [poolName, members] of pools)\n for (const { name } of members)\n if (scope[name]!.poolName !== poolName) renamed.push([name, { ...scope[name]!, poolName }]);\n return renamed;\n}\n", "import type { ExternalName, SharedExternal, shareScope } from '../externals/external.contract';\nimport { buildPools, type PoolMember, type PoolName } from './membership';\nimport { hasPoolResults, scopeHasPoolState } from './pool-state';\nimport { withoutPoolResults } from './records';\nimport type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { type PackageOf, npmPackageOf } from '../externals/specifier';\n\nexport type ElectionPlan = {\n pools: Map<PoolName, PoolMember[]>;\n // Dirty so determine re-elects them.\n stripped: Map<ExternalName, SharedExternal>;\n labelledAlone: ExternalName[];\n packageOf: PackageOf;\n};\n\n// Any dirty external re-elects every pool of its scope.\n// See docs/version-resolver.md \u00A7\"How the verdicts land in the record and the map\".\nexport function planElection(scope: DeepReadonly<shareScope>, poolable: boolean): ElectionPlan {\n // Skip before building the graph: measured, that was the whole pooling cost of a warm init.\n if (\n !poolable ||\n !Object.values(scope).some(external => external.dirty) ||\n !scopeHasPoolState(scope)\n )\n return { pools: new Map(), stripped: new Map(), labelledAlone: [], packageOf: npmPackageOf };\n\n const { pools, labelledAlone, packageOf } = buildPools(scope);\n const pooled = new Set([...pools.values()].flatMap(members => members.map(m => m.name)));\n const stripped = new Map<ExternalName, SharedExternal>();\n for (const [name, external] of Object.entries(scope))\n if (!pooled.has(name) && hasPoolResults(external))\n stripped.set(name, { ...withoutPoolResults(external), dirty: true });\n return { pools, stripped, labelledAlone, packageOf };\n}\n", "import type { ForPoolingSharedExternals } from '../../driver-ports/init/for-pooling-shared-externals.port';\nimport type { ExternalName, RemoteName, SharedExternal, shareScope } from 'lib/core/1.domain';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { DrivingContract } from '../../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../../config/log.contract';\nimport type { ModeConfig } from '../../config/mode.contract';\nimport { createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport type { PackageOf } from 'lib/core/1.domain/externals/specifier';\nimport { type Copy, copiesByRemote, specifierCount } from 'lib/core/1.domain/pooling/builds';\nimport { elect, type PoolMiss, previousWinner } from 'lib/core/1.domain/pooling/election';\nimport type { PoolMember, PoolName } from 'lib/core/1.domain/pooling/membership';\nimport { type ElectionPlan, planElection } from 'lib/core/1.domain/pooling/plan';\nimport { memberRecord, type PlacedPool } from 'lib/core/1.domain/pooling/records';\n\nexport function createPoolSharedExternals(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'sharedExternalsRepo' | 'versionCheck'>\n): ForPoolingSharedExternals {\n const { compare } = ports.versionCheck;\n\n // See docs/version-resolver.md \u00A7\"How pooling resolves\".\n return () => {\n const repo = ports.sharedExternalsRepo;\n for (const scope of repo.getScopes()) {\n const sharedExternals = repo.getFromScope(scope);\n try {\n const plan = planElection(sharedExternals, repo.scopeType(scope) !== 'strict');\n logPlan(plan, sharedExternals, scope);\n for (const [poolName, members] of plan.pools)\n for (const [name, record] of poolRecords(poolName, members, plan.packageOf, scope))\n repo.addOrUpdate(name, record, scope);\n for (const [name, external] of plan.stripped) repo.addOrUpdate(name, external, scope);\n } catch (error) {\n if (error instanceof NFError) return Promise.reject(error);\n config.log.error(3, `[${scope}] failed to pool shared externals.`, {\n sharedExternals,\n error,\n });\n return Promise.reject(\n new NFError(`Could not pool shared externals in scope ${scope}.`, error as Error)\n );\n }\n }\n return Promise.resolve();\n };\n\n function logPlan(plan: ElectionPlan, sharedExternals: shareScope, scope: string): void {\n if (plan.pools.size > 0) {\n const dirty = Object.values(sharedExternals).filter(external => external.dirty).length;\n config.log.debug(\n 3,\n `[${scope}] re-electing ${plan.pools.size} pool(s): ${dirty} dirty external(s).`\n );\n }\n if (plan.stripped.size > 0)\n config.log.debug(\n 3,\n `[${scope}] ${plan.stripped.size} external(s) left every pool; cleared their pool state for re-election.`\n );\n for (const name of plan.labelledAlone)\n config.log.debug(\n 3,\n `[${scope}] '${name}' has a 'pool' label that joins no other external; likely a typo or a missing sibling.`\n );\n }\n\n function poolRecords(\n poolName: PoolName,\n members: PoolMember[],\n packageOf: PackageOf,\n scope: string\n ): [ExternalName, SharedExternal][] {\n const election = elect({\n members,\n packageOf,\n acceptsTag: createAcceptsTag(ports.versionCheck.isCompatible, compare),\n compare,\n previousWinner: previousWinner(members),\n latestFirst: config.profile.latestSharedExternal,\n });\n const placed: PlacedPool = { ...election, poolName };\n report(poolName, members, placed, scope);\n return members.map(m => [\n m.name,\n { ...memberRecord(m, placed, compare), poolWinner: placed.winner },\n ]);\n }\n\n function report(\n poolName: PoolName,\n members: PoolMember[],\n placed: PlacedPool,\n scope: string\n ): void {\n const { misses } = placed;\n // A range rejecting the elected build is what this flag refuses; a coverage miss never is.\n const rejecting = [...misses]\n .filter(([, miss]) => miss?.cause === 'incompatible' && miss.strict)\n .map(([remote]) => remote);\n if (config.strict.strictExternalCompatibility && rejecting.length > 0) {\n config.log.error(\n 3,\n `[${scope}][pool:${poolName}] version-incompatible remotes cannot be pooled: {${rejecting.join(', ')}}.`\n );\n throw new NFError(`Could not pool '${poolName}' in scope ${scope}.`);\n }\n\n const subpoolSizes = new Map<RemoteName, number>();\n for (const placement of placed.placements.values())\n if (placement.kind === 'subpool')\n subpoolSizes.set(placement.owner, (subpoolSizes.get(placement.owner) ?? 0) + 1);\n let shipped: Map<RemoteName, Copy[]> | undefined;\n for (const [remote, miss] of misses) {\n if (miss === undefined) {\n config.log.warn(\n 3,\n `[${scope}][pool:${poolName}] '${remote}' keeps subpool '${remote}': the elected build would serve it, but ${subpoolSizes.get(remote)! - 1} other remote(s) in it need its build.`\n );\n continue;\n }\n shipped ??= copiesByRemote(members);\n const counts = {\n imports: specifierCount(shipped.get(remote)!),\n subpoolSize: subpoolSizes.get(remote) ?? 0,\n };\n config.log.warn(\n 3,\n `[${scope}][pool:${poolName}] ${missWarning(remote, miss, placed, counts)}`\n );\n }\n }\n}\n\nfunction missWarning(\n remote: RemoteName,\n miss: PoolMiss,\n placed: PlacedPool,\n counts: { imports: number; subpoolSize: number }\n): string {\n // Wording is pinned in `island-warnings.contract.spec.ts` alone; tools read islands from the record.\n const { imports, subpoolSize } = counts;\n const placement = placed.placements.get(remote)!;\n const where =\n placement.kind === 'subpool' && placement.owner !== remote\n ? `It runs in subpool '${placement.owner}' for all ${imports} of its entrypoints.`\n : subpoolSize > 1\n ? `Its build serves subpool '${remote}': its ${imports} entrypoints and ${subpoolSize - 1} other remote(s).`\n : `All ${imports} of its entrypoints are scoped for it.`;\n\n if (miss.cause === 'incompatible')\n return `'${remote}' is islanded: its range rejects '${miss.member}@${miss.tag}' of the elected build '${placed.winner}'. ${where}`;\n if (miss.unshipped)\n return `'${remote}' serves its own family: no build shipped its entrypoints together at the elected versions (gap '${miss.gap}', closest '${placed.winner}'). ${where}`;\n return `'${remote}' serves its own family: no elected build offers every entrypoint it imports at a version it accepts (gap '${miss.gap}', closest '${placed.winner}'). ${where}`;\n}\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport { compareStrings } from 'lib/utils/compare-strings';\nimport type { RemoteName } from '../remote/remote-info.contract';\nimport type { AcceptsTag } from './compatibility';\nimport type { ExternalName, SharedExternal, shareScope } from './external.contract';\nimport { mergeRows, redirectRow, rowAt, scopeRemotes } from './rows';\nimport { groupByPackage, packageOfIn, type Specifier } from './specifier';\nimport type { SharedVersion, SharedVersionMeta, VersionName } from './version.contract';\n\nexport type ServingBuild = { remote: RemoteName; tag: VersionName };\n\nexport type ServingCandidate = ServingBuild & {\n host: boolean;\n downloads: number;\n fallbacks: number;\n rootBasis: boolean;\n};\n\nexport type PackageExternals = readonly (readonly [ExternalName, DeepReadonly<SharedExternal>])[];\ntype Row = DeepReadonly<SharedVersion>;\ntype Placed = { row: Row; copy: DeepReadonly<SharedVersionMeta> };\n\nexport const byServingRank = (a: ServingCandidate, b: ServingCandidate): number =>\n Number(b.host) - Number(a.host) ||\n a.downloads - b.downloads ||\n a.fallbacks - b.fallbacks ||\n Number(b.rootBasis) - Number(a.rootBasis) ||\n compareStrings(a.remote, b.remote);\n\nexport const packagesOf = (scope: DeepReadonly<shareScope>): Map<ExternalName, ExternalName[]> =>\n groupByPackage(Object.keys(scope), name => name, packageOfIn(scope));\n\nexport const isPooled = (externals: PackageExternals): boolean =>\n externals.some(([, e]) => e.poolName !== undefined);\n\n// `externals` are package `pkg`'s, in record order. A share row of the root fixes the tag its secondaries follow.\nexport function servingBuildOf(\n pkg: ExternalName,\n externals: PackageExternals,\n accepts: AcceptsTag\n): ServingBuild | undefined {\n if (externals.length === 0) return undefined;\n // A dense build names the record of secondaries it does not declare by npm name, without shipping that root.\n const rootRows = shareRows(externals.find(([name]) => name === pkg)?.[1]).filter(row =>\n row.remotes.some(copy => pkg in copy.entries)\n );\n const rows = rootRows.length > 0 ? rootRows : externals.flatMap(([, e]) => shareRows(e));\n\n // The election already chose the global build; ranking again per package could split a pool.\n if (isPooled(externals)) return pooledBuild(externals, rows);\n\n const consumers = consumersOf(externals);\n const builds = buildsOf(rows, rootRows, consumers);\n // A host build outranks every other at any cost: only two or more of the builds left need pricing.\n const hosts = builds.filter(b => b.host);\n const field = hosts.length > 0 ? hosts : builds;\n if (field.length <= 1) return field[0] && { remote: field[0].remote, tag: field[0].tag };\n return cheapestBuild(field, costTable(consumers, accepts));\n}\n\nfunction cheapestBuild(\n field: UnpricedBuild[],\n costOf: (build: ServingBuild) => Cost\n): ServingBuild {\n let best: ServingCandidate | undefined;\n for (const b of field) {\n const { downloads, fallbacks } = costOf(b);\n const candidate: ServingCandidate = {\n remote: b.remote,\n tag: b.tag,\n host: b.host,\n rootBasis: b.rootBasis,\n downloads,\n fallbacks,\n };\n if (!best || byServingRank(candidate, best) < 0) best = candidate;\n }\n const { remote, tag } = best!;\n return { remote, tag };\n}\n\n// The serving build's copies publish even where that external's own election skipped them, so every specifier\n// the build ships stays in its surface. Mutates `external` in place.\nexport function shareServingCopies(external: SharedExternal, serving: ServingBuild): void {\n for (const row of external.versions) {\n if (row.action !== 'skip' || rowAt(external.versions, row.tag, 'share')) continue;\n const own = row.remotes.filter(c => c.name === serving.remote);\n if (own.length === 0) continue;\n row.action = 'share';\n // A host leading the row stops being its basis.\n if (row.remotes[0] !== own[0]) row.host = false;\n // Every record of a split build leads, or another copy publishes what the second one ships (#133).\n row.remotes = [...own, ...row.remotes.filter(c => c.name !== serving.remote)];\n }\n}\n\nexport type ServingObjector = { copy: SharedVersionMeta; tag: VersionName };\n\n// Every share row at another tag follows the serving build the way a version follows its winner. Mutates\n// `external` in place; `objector` is the first strict copy that keeps its own build instead.\nexport function followServingBuild(\n external: SharedExternal,\n serving: ServingBuild,\n accepts: AcceptsTag\n): { external: SharedExternal; objector?: ServingObjector } {\n let objector: ServingObjector | undefined;\n const rebuilt = external.versions.flatMap(version => {\n if (\n version.action !== 'share' ||\n version.tag === serving.tag ||\n version.remotes[0]!.name === serving.remote\n )\n return [version];\n const rows = redirectRow(version, serving.tag, accepts);\n // A share row redirects into a `scope` row only of copies that reject the tag strictly.\n const scoped = rows.find(row => row.action === 'scope');\n if (scoped && !objector) objector = { copy: scoped.remotes[0]!, tag: scoped.tag };\n return rows;\n });\n external.versions = mergeRows(rebuilt);\n return { external, objector };\n}\n\n// A strict copy's range is its own tag, and a tag scope holds that tag only.\nconst sameTagOnly: AcceptsTag = (offered, ownTag) => offered === ownTag;\n\n// The strict scope shares every tag side by side, so each package at each tag is served on its own.\nexport const servedScopes = (scope: shareScope, strict: boolean): shareScope[] =>\n strict ? strictTagScopes(scope) : [scope];\n\n// See docs/version-resolver.md \u00A7\"Entrypoint coverage and tearing\". Rows are cloned, but each remote's copy in them is\n// the record's own, so the map's `cached` marks reach storage.\nfunction strictTagScopes(scope: shareScope): shareScope[] {\n const tagScopes: shareScope[] = [];\n for (const [pkg, names] of packagesOf(scope)) {\n const byTag = new Map<VersionName, shareScope>();\n for (const name of names)\n for (const row of scope[name]!.versions) {\n let tagScope = byTag.get(row.tag);\n if (!tagScope) byTag.set(row.tag, (tagScope = {}));\n const external = (tagScope[name] ??= { ...scope[name]!, versions: [] });\n external.versions.push({ ...row, remotes: [...row.remotes] });\n }\n for (const [tag, tagScope] of byTag) {\n // A record stored before determine skipped the strict scope can hold a skip row here, whose copy publishes\n // nothing.\n const lead = [tagScope[pkg], ...Object.values(tagScope)]\n .map(external => external && rowAt(external.versions, tag, 'share'))\n .find(row => row !== undefined);\n if (lead) {\n const serving = { remote: lead.remotes[0]!.name, tag };\n for (const external of Object.values(tagScope)) external.servingBuild = serving.remote;\n scopeFallbacks(Object.entries(tagScope), serving, sameTagOnly);\n }\n tagScopes.push(tagScope);\n }\n }\n return tagScopes;\n}\n\nfunction shareRows(external: DeepReadonly<SharedExternal> | undefined): Row[] {\n return external?.versions.filter(v => v.action === 'share') ?? [];\n}\n\n// Keyed by tag and remote rather than the first row per remote, so record order never decides.\nfunction buildsOf(\n rows: Row[],\n rootRows: Row[],\n consumers: Map<RemoteName, Placed[]>\n): UnpricedBuild[] {\n const builds = new Map<string, UnpricedBuild>();\n for (const row of rows)\n for (const copy of row.remotes) {\n const key = `${row.tag}|${copy.name}`;\n if (copy.servedBy || builds.has(key) || shipsTwoTags(consumers.get(copy.name)!)) continue;\n const basis = copy === row.remotes[0];\n builds.set(key, {\n remote: copy.name,\n tag: row.tag,\n host: basis && row.host,\n rootBasis: basis && rootRows.includes(row),\n });\n }\n return [...builds.values()];\n}\n\n// The pool's winner, where it ships the root (or, without one, any of the package); otherwise the widest copy:\n// every share-row copy lies within the one the election published, so the widest ships exactly it.\nfunction pooledBuild(externals: PackageExternals, rows: Row[]): ServingBuild | undefined {\n const winner = externals.find(([, e]) => e.poolWinner !== undefined)?.[1].poolWinner;\n const shipped = rows.flatMap(row =>\n row.remotes.filter(copy => !copy.servedBy).map(copy => ({ remote: copy.name, tag: row.tag }))\n );\n const own = shipped.find(c => c.remote === winner);\n if (own) return own;\n const width = ({ remote, tag }: ServingBuild) =>\n externals\n .flatMap(([, e]) => shareRows(e).find(row => row.tag === tag)?.remotes ?? [])\n .filter(copy => copy.name === remote)\n .reduce((n, copy) => n + Object.keys(copy.entries).length, 0);\n return shipped\n .map(c => ({ c, width: width(c) }))\n .sort((a, b) => b.width - a.width || compareStrings(a.c.remote, b.c.remote))[0]?.c;\n}\n\nexport function consumersOf(externals: PackageExternals): Map<RemoteName, Placed[]> {\n const consumers = new Map<RemoteName, Placed[]>();\n for (const [, external] of externals)\n for (const row of external.versions)\n for (const copy of row.remotes) {\n const placed = consumers.get(copy.name);\n if (placed) placed.push({ row, copy });\n else consumers.set(copy.name, [{ row, copy }]);\n }\n return consumers;\n}\n\ntype Cost = Pick<ServingCandidate, 'downloads' | 'fallbacks'>;\ntype UnpricedBuild = Omit<ServingCandidate, keyof Cost>;\n// The remotes that fall back and those that download their own build; a cached copy costs nothing.\ntype Toll = { fallbacks: Set<RemoteName>; downloads: Set<RemoteName> };\n\n// Builds at one tag that ship the same specifiers there cost the same but for their own remote, so each such\n// surface is tolled once.\nexport function costTable(\n consumers: Map<RemoteName, Placed[]>,\n accepts: AcceptsTag\n): (build: ServingBuild) => Cost {\n const scanned = new Map<VersionName, { surface: Surface; toll: Toll }[]>();\n const keyed = new Map<string, Toll>();\n const tollFor = (build: ServingBuild, surface: Surface): Toll => {\n let atTag = scanned.get(build.tag);\n if (!atTag) scanned.set(build.tag, (atTag = []));\n const known = atTag.find(t => sameSurface(t.surface, surface));\n if (known) return known.toll;\n if (atTag.length < SCANNED_SURFACES_PER_TAG) {\n const toll = tollOf(consumers, surface, build.tag, accepts);\n atTag.push({ surface, toll });\n return toll;\n }\n const key = [build.tag, ...[...surface].map(([s, tag]) => `${s}@${tag}`).sort()].join('\\n');\n let toll = keyed.get(key);\n if (!toll) keyed.set(key, (toll = tollOf(consumers, surface, build.tag, accepts)));\n return toll;\n };\n return build => {\n const surface = surfaceOf(consumers, build);\n const toll = tollFor(build, surface);\n const others = (remotes: Set<RemoteName>) => remotes.size - Number(remotes.has(build.remote));\n // The serving remote never falls back, and downloads its own build unless cached.\n return {\n downloads: others(toll.downloads) + Number(!allCached(consumers.get(build.remote) ?? [])),\n fallbacks: others(toll.fallbacks),\n };\n };\n}\n\nfunction tollOf(\n consumers: Map<RemoteName, Placed[]>,\n surface: Surface,\n tag: VersionName,\n accepts: AcceptsTag\n): Toll {\n const toll: Toll = { fallbacks: new Set(), downloads: new Set() };\n for (const [remote, placed] of consumers) {\n const fallback = fallsBack(placed, surface, tag, accepts);\n if (fallback) toll.fallbacks.add(remote);\n if (!allCached(placed) && (fallback || runsOffMap(placed, tag, accepts)))\n toll.downloads.add(remote);\n }\n return toll;\n}\n\nconst allCached = (placed: Placed[]): boolean => placed.every(({ copy }) => copy.cached);\n\n// The remotes that run part of the package off the map and part on it, ship a specifier outside the copies the\n// serving build publishes, or ship the package at two tags; without a serving build, every remote with a copy on\n// the map. Each serves the whole package from its own build instead, so none of its files imports another build's.\nexport function fallbacksOf(\n externals: PackageExternals,\n serving: ServingBuild | undefined,\n accepts: AcceptsTag\n): RemoteName[] {\n const consumers = consumersOf(externals);\n const surface: Surface = serving ? surfaceOf(consumers, serving) : new Map();\n return [...consumers]\n .filter(\n ([remote, placed]) =>\n remote !== serving?.remote && fallsBack(placed, surface, serving?.tag, accepts)\n )\n .map(([remote]) => remote);\n}\n\nexport function scopeFallbacks(\n externals: readonly (readonly [ExternalName, SharedExternal])[],\n serving: ServingBuild | undefined,\n accepts: AcceptsTag\n): void {\n const remotes = fallbacksOf(externals, serving, accepts);\n for (const [, external] of externals)\n external.versions = scopeRemotes(external.versions, remotes);\n}\n\n// The first copy, in record order, that `rejectsServingTag` while its remote's coverage alone (`splitsPackage`)\n// would keep it on the map: a remote its coverage already sends to its own build never refuses.\nexport function strictObjectorOf(\n externals: PackageExternals,\n serving: ServingBuild,\n accepts: AcceptsTag\n): (ServingObjector & { external: ExternalName }) | undefined {\n const consumers = consumersOf(externals);\n const surface = surfaceOf(consumers, serving);\n for (const [name, external] of externals)\n for (const row of external.versions)\n for (const copy of row.remotes)\n if (\n copy.name !== serving.remote &&\n rejectsServingTag({ row, copy }, surface, serving.tag, accepts) &&\n !splitsPackage(consumers.get(copy.name)!, surface, serving.tag, accepts)\n )\n return { external: name, copy, tag: row.tag };\n return undefined;\n}\n\n// Each specifier the serving build publishes, at the tag of the row it publishes it from.\ntype Surface = Map<Specifier, VersionName>;\n\n// Up to here a scan beats building the sorted key; a surface past it is looked up by that key after the scan.\nexport const SCANNED_SURFACES_PER_TAG = 8;\n\nfunction sameSurface(a: Surface, b: Surface): boolean {\n if (a.size !== b.size) return false;\n for (const [specifier, tag] of a) if (b.get(specifier) !== tag) return false;\n return true;\n}\n\nfunction surfaceOf(consumers: Map<RemoteName, Placed[]>, serving: ServingBuild): Surface {\n const surface: Surface = new Map();\n for (const p of consumers.get(serving.remote) ?? [])\n if ((p.row.tag === serving.tag && onMap(p)) || leadsShareRow(p))\n for (const s in p.copy.entries) if (!surface.has(s)) surface.set(s, p.row.tag);\n return surface;\n}\n\n// followServingBuild leaves these rows shared, so a host's copies at its other tags publish too.\nconst leadsShareRow = ({ row, copy }: Placed): boolean =>\n row.action === 'share' && row.remotes[0] === copy;\n\nconst onMap = ({ row }: Placed): boolean => row.action !== 'scope';\n\n// A remote with no copy on the map already runs the package wholly from its own build.\nfunction splitsPackage(\n placed: Placed[],\n surface: Surface,\n tag: VersionName | undefined,\n accepts: AcceptsTag\n): boolean {\n const uncovered = (p: Placed) =>\n Object.keys(p.copy.entries).some(s => {\n const servedAt = surface.get(s);\n // A strict copy takes a host's file at another tag only where its range accepts it; the serving tag is\n // `rejectsServingTag`'s to judge.\n return servedAt === undefined || (servedAt !== tag && rejectsTag(p, servedAt, accepts));\n });\n return (\n placed.some(onMap) && (shipsTwoTags(placed) || placed.some(p => !onMap(p) || uncovered(p)))\n );\n}\n\n// Whether a runtime load's copies split the package over the claims the committed map serves of it, as\n// `splitsPackage` judges a remote at init.\nexport function loadSplitsPackage(\n pkg: ExternalName,\n copies: readonly { tag: VersionName; copy: SharedVersionMeta }[],\n claims: readonly (readonly [Specifier, { tag: VersionName }])[],\n accepts: AcceptsTag\n): boolean {\n const root = claims.find(([specifier]) => specifier === pkg)?.[1];\n // Without a root claim the serving tag is unknown: every claim counts as at it, so only a gap or two tags\n // split.\n const servingTag = root?.tag ?? claims[0]![1].tag;\n const surface: Surface = new Map(\n claims.map(([specifier, { tag }]) => [specifier, root ? tag : servingTag])\n );\n // Each loaded copy as the share row it would join; a loader is never the host.\n const placed: Placed[] = copies.map(({ tag, copy }) => ({\n row: { tag, action: 'share', host: false, remotes: [copy] },\n copy,\n }));\n return splitsPackage(placed, surface, servingTag, accepts);\n}\n\nfunction fallsBack(\n placed: Placed[],\n surface: Surface,\n tag: VersionName | undefined,\n accepts: AcceptsTag\n): boolean {\n return (\n splitsPackage(placed, surface, tag, accepts) ||\n (tag !== undefined && placed.some(p => rejectsServingTag(p, surface, tag, accepts)))\n );\n}\n\n// A strict copy on the map whose range rejects the serving tag, where the serving build publishes one of its\n// files. A scoped copy already runs its own build, so it never objects.\nfunction rejectsServingTag(\n p: Placed,\n surface: Surface,\n tag: VersionName,\n accepts: AcceptsTag\n): boolean {\n return (\n onMap(p) &&\n rejectsTag(p, tag, accepts) &&\n Object.keys(p.copy.entries).some(s => surface.get(s) === tag)\n );\n}\n\nconst rejectsTag = ({ row, copy }: Placed, tag: VersionName, accepts: AcceptsTag): boolean =>\n copy.strictVersion && !accepts(tag, row.tag, copy.requiredVersion);\n\n// The host serves every tag it ships; any other remote shipping two tags has no one build to serve or follow.\nconst shipsTwoTags = (placed: Placed[]): boolean =>\n !placed.some(p => p.row.host && p.row.remotes[0] === p.copy) &&\n placed.some(p => p.row.tag !== placed[0]!.row.tag);\n\nfunction runsOffMap(placed: Placed[], tag: VersionName, accepts: AcceptsTag): boolean {\n return placed.some(p => !onMap(p) || rejectsTag(p, tag, accepts));\n}\n", "import type { ForDecidingServingBuilds } from '../driver-ports/init/for-deciding-serving-builds.port';\nimport type { ExternalName, RemoteName, SharedExternal, SharedVersion } from 'lib/core/1.domain';\nimport { type AcceptsTag, createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport {\n followServingBuild,\n isPooled,\n packagesOf,\n scopeFallbacks,\n servingBuildOf,\n shareServingCopies,\n strictObjectorOf,\n type ServingBuild,\n} from 'lib/core/1.domain/externals/serving';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport { rejectIncompatible } from './apply-winner';\n\ntype StoredPackage = (readonly [ExternalName, SharedExternal])[];\n\n// See docs/version-resolver.md \u00A7\"One build per package\".\nexport function createDecideServingBuilds(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'versionCheck' | 'sharedExternalsRepo'>\n): ForDecidingServingBuilds {\n return () => {\n const accepts = createAcceptsTag(ports.versionCheck.isCompatible, ports.versionCheck.compare);\n const repo = ports.sharedExternalsRepo;\n // Taken before deciding writes. A scope nothing wrote since its last decide would decide the same again.\n const written = new Set(repo.uncommittedScopes());\n const needsDeciding = (shareScope: string) =>\n written.has(shareScope) || repo.isUndecided(shareScope);\n\n try {\n for (const shareScope of repo.getScopes()) {\n if (repo.scopeType(shareScope) === 'strict' || !needsDeciding(shareScope)) continue;\n const sharedExternals = repo.getFromScope(shareScope);\n for (const [pkg, names] of packagesOf(sharedExternals)) {\n const externals = names.map(name => [name, sharedExternals[name]!] as const);\n decidePackage(shareScope, pkg, externals, accepts);\n }\n repo.markDecided(shareScope);\n }\n return Promise.resolve();\n } catch (e) {\n return Promise.reject(e);\n }\n };\n\n function decidePackage(\n shareScope: string,\n pkg: ExternalName,\n externals: StoredPackage,\n accepts: AcceptsTag\n ): void {\n const serving = servingBuildOf(pkg, externals, accepts);\n // Taken before falling back and following rewrite the stored externals in place.\n const before = externals.map(([, external]) => shapeOf(external));\n // The election already placed a pooled package's rows.\n const pooled = isPooled(externals);\n const toFollow = pooled ? undefined : serving;\n if (!pooled) fallBack(pkg, externals, accepts, serving);\n\n externals.forEach(([name, external], i) => {\n const decided = withServingBuild(\n toFollow ? follow(pkg, name, external, toFollow, accepts) : external,\n serving?.remote\n );\n if (!sameShape(before[i]!, decided))\n ports.sharedExternalsRepo.addOrUpdate(name, decided, shareScope);\n });\n }\n\n function follow(\n pkg: ExternalName,\n name: ExternalName,\n external: SharedExternal,\n serving: ServingBuild,\n accepts: AcceptsTag\n ): SharedExternal {\n const { external: followed, objector } = followServingBuild(external, serving, accepts);\n if (objector && config.strict.strictExternalCompatibility)\n rejectIncompatible(config, objector.copy, `${name}@${objector.tag}`, `${pkg}@${serving.tag}`);\n return followed;\n }\n\n // The serving copy publishes first, so a remote it covers stays; one it does not runs the package from its own\n // build.\n function fallBack(\n pkg: ExternalName,\n externals: StoredPackage,\n accepts: AcceptsTag,\n serving?: ServingBuild\n ): void {\n if (serving) {\n for (const [, external] of externals) shareServingCopies(external, serving);\n const objector =\n config.strict.strictExternalCompatibility && strictObjectorOf(externals, serving, accepts);\n if (objector)\n rejectIncompatible(\n config,\n objector.copy,\n `${objector.external}@${objector.tag}`,\n `${pkg}@${serving.tag}`\n );\n }\n scopeFallbacks(externals, serving, accepts);\n }\n}\n\nfunction withServingBuild(external: SharedExternal, servingBuild?: RemoteName): SharedExternal {\n if (external.servingBuild === servingBuild) return external;\n const { servingBuild: _, ...rest } = external;\n return servingBuild ? { ...rest, servingBuild } : rest;\n}\n\n// What deciding can change: the serving build, and every field of each row. The helpers reorder, move and merge\n// copies but never edit one, so copies compare by identity.\ntype Shape = { servingBuild?: RemoteName; rows: SharedVersion[] };\n\nconst shapeOf = (external: SharedExternal): Shape => ({\n servingBuild: external.servingBuild,\n rows: external.versions.map(\n ({ tag, action, host, remotes }) =>\n ({ tag, action, host, remotes: [...remotes] }) satisfies Required<SharedVersion>\n ),\n});\n\nconst sameRow = (was: SharedVersion, row: SharedVersion): boolean =>\n (Object.keys(was) as (keyof SharedVersion)[]).every(key =>\n key === 'remotes'\n ? was.remotes.length === row.remotes.length &&\n row.remotes.every((copy, j) => copy === was.remotes[j])\n : was[key] === row[key]\n );\n\nconst sameShape = (shape: Shape, external: SharedExternal): boolean =>\n shape.servingBuild === external.servingBuild &&\n shape.rows.length === external.versions.length &&\n external.versions.every((row, i) => sameRow(shape.rows[i]!, row));\n", "import type { DeepReadonly } from 'lib/utils/deep-readonly';\nimport type { RemoteName } from '../remote/remote-info.contract';\nimport { type ExternalName, GLOBAL_SCOPE, type SharedExternal } from './external.contract';\nimport type { SharedVersion, SharedVersionMeta, VersionName } from './version.contract';\nimport type { Specifier } from './specifier';\nimport { forEachVersionEntry } from './basis';\n\nexport type Claim = {\n external: ExternalName;\n tag: VersionName;\n copy: SharedVersionMeta;\n};\n\nexport type ClaimTable = {\n // What `imports` serves: an external with a serving build claims that build's copy alone, one without claims its\n // share rows in record order; the first claim per specifier wins. A skip copy claims nothing.\n claims: Map<Specifier, Claim>;\n // Share rows reached after their external's name was claimed at another tag. A row whose name another row\n // claimed claims nothing, duplicate or not.\n duplicates: Set<DeepReadonly<SharedVersion>>;\n // What a named scope serves: the same rule over every share row, duplicates included.\n shareClaims: Map<Specifier, Claim>;\n};\n\nexport function claimTable(\n externals: Iterable<readonly [ExternalName, DeepReadonly<SharedExternal>]>,\n publishes?: (copy: SharedVersionMeta) => boolean\n): ClaimTable {\n const table: ClaimTable = { claims: new Map(), duplicates: new Set(), shareClaims: new Map() };\n const ordered = [...externals];\n\n const claim = (\n into: Map<Specifier, Claim>,\n external: ExternalName,\n version: DeepReadonly<SharedVersion>,\n accepts = publishes\n ) =>\n forEachVersionEntry(version, accepts, (specifier, copy) => {\n if (!into.has(specifier)) into.set(specifier, { external, tag: version.tag, copy });\n });\n\n const seedServingBuild = (name: ExternalName, external: DeepReadonly<SharedExternal>) => {\n const isServing = (copy: SharedVersionMeta) =>\n copy.name === external.servingBuild && (!publishes || publishes(copy));\n for (const version of external.versions) {\n if (version.action !== 'share') continue;\n claim(table.shareClaims, name, version, isServing);\n claim(table.claims, name, version, isServing);\n }\n };\n\n const claimShareRow = (\n name: ExternalName,\n external: DeepReadonly<SharedExternal>,\n version: DeepReadonly<SharedVersion>\n ) => {\n const prior = table.claims.get(name);\n const duplicate = prior !== undefined && prior.tag !== version.tag;\n // A row the serving host leads is never a duplicate: it ships that tag beside the one claimed first.\n if (duplicate && !(version.host && version.remotes[0]!.name === external.servingBuild))\n table.duplicates.add(version);\n // The seed already claimed an external with a serving build.\n if (external.servingBuild) return;\n claim(table.shareClaims, name, version);\n if (!duplicate && (!prior || prior.external === name)) claim(table.claims, name, version);\n };\n\n for (const [name, external] of ordered)\n if (external.servingBuild) seedServingBuild(name, external);\n for (const [name, external] of ordered)\n for (const version of external.versions)\n if (version.action === 'share') claimShareRow(name, external, version);\n\n return table;\n}\n\n// What a committed map serves in one scope, from externals in record order: `imports` holds only the copies\n// marked cached, a named scope's override may name any copy. `without` is a loaded remote whose copies the\n// record already holds but the committed map does not.\nexport function committedClaims(\n externals: Iterable<readonly [ExternalName, DeepReadonly<SharedExternal>]>,\n { shareScope, without }: { shareScope: string; without?: RemoteName }\n): Map<Specifier, Claim> {\n const publishes = (copy: SharedVersionMeta) =>\n copy.name !== without && (shareScope !== GLOBAL_SCOPE || copy.cached);\n return claimTable(externals, publishes).claims;\n}\n\n// One version's claims as `claimTable` makes them: the serving copy alone when there is one, else every copy in\n// record order.\nexport function versionClaims(\n version: DeepReadonly<SharedVersion>,\n servingBuild: RemoteName | undefined\n): Map<Specifier, SharedVersionMeta> {\n const claims = new Map<Specifier, SharedVersionMeta>();\n const claim = (specifier: Specifier, copy: SharedVersionMeta) => {\n if (!claims.has(specifier)) claims.set(specifier, copy);\n };\n const accepts = servingBuild\n ? (copy: SharedVersionMeta) => copy.name === servingBuild\n : undefined;\n forEachVersionEntry(version, accepts, claim);\n return claims;\n}\n", "import type { ForGeneratingImportMap } from '../driver-ports/init/for-generating-import-map';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ImportMap, Imports } from 'lib/core/1.domain/import-map/import-map.contract';\nimport {\n GLOBAL_SCOPE,\n type RemoteName,\n type ScopedExternal,\n type RemoteInfo,\n type SharedExternal,\n type SharedVersion,\n type SharedVersionMeta,\n} from 'lib/core/1.domain';\nimport { forEachVersionEntry } from 'lib/core/1.domain/externals/basis';\nimport { claimTable, versionClaims, type Claim } from 'lib/core/1.domain/externals/claims';\nimport { servedScopes } from 'lib/core/1.domain/externals/serving';\nimport type { Specifier } from 'lib/core/1.domain/externals/specifier';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport * as _path from 'lib/utils/path';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { toChunkImport } from '@softarc/native-federation/domain';\n\nexport function createGenerateImportMap(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedChunksRepo' | 'sharedExternalsRepo'\n >\n): ForGeneratingImportMap {\n /**\n * Step 4: Generate an importMap from the cached remoteEntries\n *\n * The processed externals in the storage/cache (step 2 & 3) are used\n * to generate an importMap. The step returns the generated importMap object.\n */\n return () => {\n const importMap: ImportMap = { imports: {} };\n const chunkBundles: Record<string, Set<string>> = {};\n try {\n addScopedExternals(importMap, chunkBundles);\n addNamedShareScopes(importMap, chunkBundles);\n addGlobalShareScope(importMap, chunkBundles);\n addRemoteInfos(importMap, chunkBundles);\n\n addChunkImports(importMap, chunkBundles);\n\n return Promise.resolve(importMap);\n } catch (e) {\n return Promise.reject(e);\n }\n };\n\n /**\n * Step 4.1: Begin with appending smallest scope of shared dependencies\n * @param importMap\n * @returns\n */\n function addScopedExternals(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>\n ): ImportMap {\n const scopedExternals = ports.scopedExternalsRepo.getAll();\n\n for (const [remoteName, externals] of Object.entries(scopedExternals)) {\n const remote = ports.remoteInfoRepo.tryGet(remoteName).orThrow(() => {\n config.log.error(4, `[scoped][${remoteName}] Remote name not found in cache.`);\n return new NFError('Could not create ImportMap.');\n });\n addToScope(importMap, remote.scopeUrl, createScopeModules(externals, remote.scopeUrl));\n\n for (const version of Object.values(externals)) {\n for (const file of Object.values(version.entries)) {\n addIntegrity(importMap, _path.join(remote.scopeUrl, file), remoteName, file);\n }\n }\n\n Object.values(externals)\n .filter(e => !!e.bundle)\n .forEach(e => registerBundleChunks(chunkBundles, remoteName, e.bundle));\n }\n\n return importMap;\n }\n\n function createScopeModules(externals: ScopedExternal, scope: string): Imports {\n const modules: Imports = {};\n\n for (const version of Object.values(externals)) {\n for (const [packageName, file] of Object.entries(version.entries)) {\n modules[packageName] = _path.join(scope, file);\n }\n }\n\n return modules;\n }\n\n // Runs after the scoped externals, so a remote's shared mappings overwrite its scoped ones in its scope.\n function addNamedShareScopes(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>\n ): ImportMap {\n const shareScopes = ports.sharedExternalsRepo.getScopes({ includeGlobal: false });\n\n for (const shareScope of shareScopes) {\n const sharedExternals = ports.sharedExternalsRepo.getFromScope(shareScope);\n const cachedBefore = new Map<string, string>();\n for (const [externalName, external] of Object.entries(sharedExternals))\n cachedBefore.set(externalName, cachedFingerprint(external));\n\n const strict = ports.sharedExternalsRepo.scopeType(shareScope) === 'strict';\n for (const served of servedScopes(sharedExternals, strict))\n addShareScope(importMap, shareScope, served, chunkBundles);\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n if (cachedFingerprint(external) !== cachedBefore.get(externalName)) {\n ports.sharedExternalsRepo.addOrUpdate(externalName, external, shareScope);\n }\n }\n }\n\n return importMap;\n }\n\n function addShareScope(\n importMap: ImportMap,\n shareScope: string,\n sharedExternals: Record<string, SharedExternal>,\n chunkBundles: Record<string, Set<string>>\n ): void {\n const index = buildServedIndex(sharedExternals);\n\n const claims = shareRowMappings(sharedExternals, shareScope);\n const claimedElsewhere = (externalName: string, specifier: string): Mapping | undefined => {\n const claim = claims.get(specifier);\n return claim?.external === externalName ? undefined : claim;\n };\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n let override: SharedVersion | undefined | 'NOT_AVAILABLE' = undefined;\n\n for (const version of external.versions) {\n if (version.action === 'scope') {\n addScopeRow(importMap, chunkBundles, shareScope, externalName, version);\n continue;\n }\n\n // Serve every entrypoint from one version: this one, or the override version when a\n // 'skip' is redirected elsewhere.\n let serving = version;\n\n if (version.action === 'skip') {\n if (!override) {\n override =\n findOverride(external, shareScope, externalName, s =>\n Boolean(claimedElsewhere(externalName, s))\n ) ?? 'NOT_AVAILABLE';\n }\n if (override !== 'NOT_AVAILABLE') {\n serving = override;\n version.remotes[0]!.cached = false;\n }\n }\n\n const provided = versionClaims(serving, external.servingBuild);\n const mappings: (Mapping & { packageName: string })[] = [];\n\n for (const [packageName, provider] of provided) {\n // The claiming external maps, marks and registers that copy; this one only points at it.\n const claim = claimedElsewhere(externalName, packageName);\n if (claim) {\n mappings.push({ packageName, ...claim });\n continue;\n }\n const file = provider.entries[packageName]!;\n mappings.push({\n packageName,\n url: _path.join(getScope(shareScope, provider.name, externalName), file),\n name: provider.name,\n file,\n });\n provider.cached = true;\n if (version.action === 'share') {\n registerBundleChunks(chunkBundles, provider.name, provider.bundle);\n }\n }\n\n version.remotes.forEach(consumer => {\n const consumerScope = getScope(shareScope, consumer.name, externalName);\n // Pooling placed this remote in a subpool, so its scope names that subpool's build's files for\n // everything it imports rather than the shared source's.\n if (index && consumer.servedBy) {\n const files = index.get(consumer.servedBy);\n const servedScope = getScope(shareScope, consumer.servedBy, externalName);\n for (const specifier of Object.keys(consumer.entries)) {\n const source = files?.get(specifier);\n if (!source) continue;\n const url = _path.join(servedScope, source.file);\n addToScope(importMap, consumerScope, { [specifier]: url });\n addIntegrity(importMap, url, consumer.servedBy, source.file);\n registerBundleChunks(chunkBundles, consumer.servedBy, source.bundle);\n source.meta.cached = true;\n }\n return;\n }\n for (const m of mappings) {\n addToScope(importMap, consumerScope, { [m.packageName]: m.url });\n }\n for (const packageName of Object.keys(consumer.entries)) {\n if (provided.has(packageName)) continue;\n const claim = claimedElsewhere(externalName, packageName);\n if (claim) addToScope(importMap, consumerScope, { [packageName]: claim.url });\n }\n });\n for (const m of mappings) {\n addIntegrity(importMap, m.url, m.name, m.file);\n }\n }\n }\n }\n\n function addScopeRow(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>,\n shareScope: string,\n externalName: string,\n version: SharedVersion\n ): void {\n for (const remote of version.remotes) {\n const remoteScope = getScope(shareScope, remote.name, externalName);\n for (const [packageName, file] of Object.entries(remote.entries)) {\n const url = _path.join(remoteScope, file);\n addToScope(importMap, remoteScope, { [packageName]: url });\n addIntegrity(importMap, url, remote.name, file);\n }\n registerBundleChunks(chunkBundles, remote.name, remote.bundle);\n remote.cached = true;\n }\n }\n\n function cachedFingerprint(external: SharedExternal): string {\n return external.versions.map(v => v.remotes.map(r => (r.cached ? 1 : 0)).join('')).join('|');\n }\n\n // A skip-only external whose specifiers another external's shared version maps is served all the same.\n function findOverride(\n external: SharedExternal,\n shareScope: string,\n externalName: string,\n servedElsewhere: (specifier: string) => boolean\n ): SharedVersion | undefined {\n const sharedVersions = external.versions.filter(v => v.action === 'share');\n const scopedExternalName = `${shareScope}.${externalName}`;\n\n if (sharedVersions.length > 1) {\n handleMultipleSharedVersions(scopedExternalName);\n }\n\n const servedByClaims = () =>\n external.versions.filter(v => v.action === 'skip').every(v => shipsOnly(v, servedElsewhere));\n\n if (sharedVersions.length < 1 && !servedByClaims()) {\n if (config.strict.strictImportMap) {\n config.log.error(4, `[${shareScope}][${externalName}] shareScope has no override version.`);\n throw new NFError('Could not create ImportMap.');\n }\n config.log.debug(\n 4,\n `[${shareScope}][${externalName}] shareScope has no override version, scoping override versions.`\n );\n }\n\n return sharedVersions[0];\n }\n\n function handleMultipleSharedVersions(scopedExternalName: string): void {\n if (config.strict.strictImportMap) {\n config.log.error(\n 4,\n `[${scopedExternalName}] ShareScope external has multiple shared versions.`\n );\n throw new NFError('Could not create ImportMap.');\n }\n\n config.log.warn(4, `ShareScope external ${scopedExternalName} has multiple shared versions.`);\n }\n\n /**\n * Where a build serves a specifier from, per remote \u2014 built only when some copy carries a `servedBy`,\n * so an unpooled portfolio allocates nothing. Pool-wide rather than per-external on purpose: the\n * specifier a subpool member runs may be an *entry* of a different external of the serving build,\n * which is the whole reason coverage is keyed by specifier (see docs/version-resolver.md \u00A7\"How pooling\n * resolves\", \"Coverage is keyed by specifier\").\n */\n type ServedSource = { file: string; bundle?: string; meta: SharedVersionMeta };\n\n function buildServedIndex(\n externals: Record<string, SharedExternal>\n ): Map<RemoteName, Map<string, ServedSource>> | undefined {\n let anyServed = false;\n for (const external of Object.values(externals)) {\n for (const version of external.versions) {\n if (version.remotes.some(r => r.servedBy)) anyServed = true;\n }\n }\n if (!anyServed) return undefined;\n\n const index = new Map<RemoteName, Map<string, ServedSource>>();\n for (const external of Object.values(externals)) {\n for (const version of external.versions) {\n for (const remote of version.remotes) {\n let own = index.get(remote.name);\n if (!own) index.set(remote.name, (own = new Map()));\n for (const [specifier, file] of Object.entries(remote.entries)) {\n if (!own.has(specifier))\n own.set(specifier, { file, bundle: remote.bundle, meta: remote });\n }\n }\n }\n }\n return index;\n }\n\n type Mapping = { url: string; name: RemoteName; file: string };\n\n // A specifier can be an entry of one external and a package of its own in another (flat vs dense), and the\n // first shared version listing it serves every remote of the scope.\n function shareRowMappings(\n externals: Record<string, SharedExternal>,\n shareScope: string\n ): Map<Specifier, Mapping & { external: string }> {\n const mappings = new Map<Specifier, Mapping & { external: string }>();\n for (const [specifier, { external, copy }] of claimTable(Object.entries(externals))\n .shareClaims) {\n const file = copy.entries[specifier]!;\n mappings.set(specifier, {\n url: _path.join(getScope(shareScope, copy.name, external), file),\n name: copy.name,\n file,\n external,\n });\n }\n return mappings;\n }\n\n // A cross-build scope entry, held back until every global mapping is in place so that a scope which\n // would merely repeat `imports` can be dropped.\n type ServedScope = { scope: string; specifier: string; source: ServedSource; from: RemoteName };\n\n function collectServed(\n into: ServedScope[],\n index: Map<RemoteName, Map<string, ServedSource>>,\n shareScope: string,\n externalName: string,\n version: SharedVersion\n ): void {\n for (const consumer of version.remotes) {\n if (!consumer.servedBy) continue;\n const files = index.get(consumer.servedBy);\n const scope = getScope(shareScope, consumer.name, externalName);\n for (const specifier of Object.keys(consumer.entries)) {\n const source = files?.get(specifier);\n if (!source) {\n config.log.warn(\n 4,\n `[${shareScope}][${externalName}][${consumer.name}] '${consumer.servedBy}' does not serve '${specifier}'.`\n );\n continue;\n }\n into.push({ scope, specifier, source, from: consumer.servedBy });\n }\n }\n }\n\n function flushServed(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>,\n served: ServedScope[]\n ): void {\n for (const { scope, specifier, source, from } of served) {\n const url = _path.join(getScope(GLOBAL_SCOPE, from), source.file);\n if (importMap.imports[specifier] === url) continue;\n addToScope(importMap, scope, { [specifier]: url });\n addIntegrity(importMap, url, from, source.file);\n registerBundleChunks(chunkBundles, from, source.bundle);\n source.meta.cached = true;\n }\n }\n\n function addGlobalShareScope(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>\n ): ImportMap {\n const sharedExternals = ports.sharedExternalsRepo.getFromScope();\n const index = buildServedIndex(sharedExternals);\n const { claims, duplicates } = claimTable(Object.entries(sharedExternals));\n const claimed = claimsByCopy(claims);\n const served: ServedScope[] = [];\n const cachedBefore = new Map<string, string>();\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n cachedBefore.set(externalName, cachedFingerprint(external));\n\n for (const version of external.versions) {\n if (index && version.action !== 'scope') {\n collectServed(served, index, GLOBAL_SCOPE, externalName, version);\n }\n if (version.action === 'skip') continue;\n if (version.action === 'scope') {\n addScopeRow(importMap, chunkBundles, GLOBAL_SCOPE, externalName, version);\n continue;\n }\n\n if (duplicates.has(version)) {\n notifyDuplicateGlobalExternal(externalName);\n continue;\n }\n\n publishClaims(importMap, chunkBundles, externalName, version, claimed);\n }\n }\n\n flushServed(importMap, chunkBundles, served);\n\n for (const [externalName, external] of Object.entries(sharedExternals)) {\n if (cachedFingerprint(external) !== cachedBefore.get(externalName)) {\n ports.sharedExternalsRepo.addOrUpdate(externalName, external);\n }\n }\n\n return importMap;\n }\n\n function claimsByCopy(claims: Map<Specifier, Claim>): Map<SharedVersionMeta, Specifier[]> {\n const claimed = new Map<SharedVersionMeta, Specifier[]>();\n for (const [specifier, { copy }] of claims) {\n const specifiers = claimed.get(copy);\n if (specifiers) specifiers.push(specifier);\n else claimed.set(copy, [specifier]);\n }\n return claimed;\n }\n\n // Marks and registers each copy that claims a specifier, so `cached` names the copies this map really\n // publishes, which the dynamic path reads as what it may call covered.\n function publishClaims(\n importMap: ImportMap,\n chunkBundles: Record<string, Set<string>>,\n externalName: string,\n version: SharedVersion,\n claimed: Map<SharedVersionMeta, Specifier[]>\n ): void {\n for (const copy of version.remotes) {\n const specifiers = claimed.get(copy);\n if (!specifiers) continue;\n const scope = getScope(GLOBAL_SCOPE, copy.name, externalName);\n registerBundleChunks(chunkBundles, copy.name, copy.bundle);\n copy.cached = true;\n for (const specifier of specifiers) {\n const file = copy.entries[specifier]!;\n const url = _path.join(scope, file);\n addToGlobal(importMap, { [specifier]: url });\n addIntegrity(importMap, url, copy.name, file);\n }\n }\n }\n\n function notifyDuplicateGlobalExternal(externalName: string): void {\n if (config.strict.strictImportMap) {\n config.log.error(4, `[${externalName}] Shared external has multiple shared versions.`);\n throw new NFError('Could not create ImportMap.');\n }\n\n config.log.warn(4, `Singleton external ${externalName} has multiple shared versions.`);\n }\n\n function addToScope(importMap: ImportMap, scope: string, imports: Imports): void {\n if (!importMap.scopes) importMap.scopes = {};\n if (!importMap.scopes[scope]) importMap.scopes[scope] = {};\n importMap.scopes[scope] = Object.assign(importMap.scopes[scope], imports);\n }\n function addToGlobal(importMap: ImportMap, imports: Imports): void {\n importMap.imports = Object.assign(importMap.imports, imports);\n }\n\n /**\n * Step 4.4: Added the remote-modules (into the global scope).\n * @param importMap\n * @returns\n */\n function addRemoteInfos(importMap: ImportMap, chunkBundles: Record<string, Set<string>>): void {\n const remotes = ports.remoteInfoRepo.getAll();\n\n for (const [remoteName, remote] of Object.entries(remotes)) {\n addRemoteExposedModules(importMap, remoteName, remote);\n registerBundleChunks(chunkBundles, remoteName, 'mapping-or-exposed');\n }\n }\n\n function addRemoteExposedModules(\n importMap: ImportMap,\n remoteName: string,\n remote: RemoteInfo\n ): void {\n for (const exposed of remote.exposes) {\n const moduleName = _path.join(remoteName, exposed.moduleName);\n const moduleUrl = _path.join(remote.scopeUrl, exposed.file);\n importMap.imports[moduleName] = moduleUrl;\n addIntegrity(importMap, moduleUrl, remoteName, exposed.file);\n }\n }\n\n function registerBundleChunks(\n chunkBundles: Record<string, Set<string>>,\n remoteName: string,\n bundleName?: string\n ) {\n if (!bundleName) return chunkBundles;\n if (!chunkBundles[remoteName]) chunkBundles[remoteName] = new Set();\n chunkBundles[remoteName].add(bundleName);\n return chunkBundles;\n }\n\n function addChunkImports(importMap: ImportMap, chunkBundles: Record<string, Set<string>>) {\n Object.entries(chunkBundles).forEach(([remoteName, bundles]) => {\n const baseUrl = getScope('CHUNKS', remoteName);\n\n const imports = Array.from(bundles).reduce((_imports, bundleName) => {\n ports.sharedChunksRepo.tryGet(remoteName, bundleName).ifPresent(files => {\n files.forEach(file => {\n const url = _path.join(baseUrl, file);\n _imports[toChunkImport(file)] = url;\n addIntegrity(importMap, url, remoteName, file);\n });\n });\n return _imports;\n }, {} as Imports);\n\n if (Object.keys(imports).length > 0) addToScope(importMap, baseUrl, imports);\n });\n\n return importMap;\n }\n\n function addIntegrity(\n importMap: ImportMap,\n url: string,\n remoteName: RemoteName,\n file: string\n ): void {\n const hash = ports.remoteInfoRepo.tryGet(remoteName).get()?.integrity?.[file];\n if (!hash) return;\n if (!importMap.integrity) importMap.integrity = {};\n importMap.integrity[url] = hash;\n }\n\n function getScope(ctx: string, remoteName: RemoteName, externalName?: string) {\n return ports.remoteInfoRepo\n .tryGet(remoteName)\n .map(remote => remote.scopeUrl)\n .orThrow(() => {\n if (externalName) {\n config.log.error(\n 4,\n `[${ctx}][${externalName}][${remoteName}] Remote name not found in cache.`\n );\n } else {\n config.log.error(4, `[${ctx}][${remoteName}] Remote name not found in cache.`);\n }\n\n return new NFError('Could not create ImportMap.');\n });\n }\n}\n\nfunction shipsOnly(version: SharedVersion, served: (specifier: Specifier) => boolean): boolean {\n let only = true;\n forEachVersionEntry(version, undefined, specifier => {\n only &&= served(specifier);\n });\n return only;\n}\n", "import type { Logger } from '../config/log.contract';\nimport type { ForBrowserTasks } from '../driving-ports/for-browser-tasks';\n\nexport type PreloadHint = (collectUrls: () => string[]) => void;\n\n// Collecting runs inside the guard too: a hint never fails the load or commit that sends it.\nexport function createPreloadHint(\n log: Logger,\n browser: Pick<ForBrowserTasks, 'preloadModules'>,\n logStep: number\n): PreloadHint {\n const ignore = (error: unknown) => log.debug(logStep, 'Ignored a failing preload hint.', error);\n\n return collectUrls => {\n if (!browser.preloadModules) return;\n try {\n const urls = collectUrls();\n if (urls.length === 0) return;\n // A host's async preloadModulesFn may reject, which this try cannot catch.\n void Promise.resolve(browser.preloadModules(urls)).catch(ignore);\n } catch (error) {\n ignore(error);\n }\n };\n}\n", "import type { ImportMap } from './import-map.contract';\nimport * as _path from 'lib/utils/path';\n\nexport type PreloadCandidate = {\n scopeUrl: string;\n entryFiles: string[];\n bundle?: { name: string; chunkFiles: string[] };\n};\n\n// Only a copy the map serves whole counts: a flag on a copy that lost version resolution does nothing, and a\n// copy served in part would preload chunks of entries another copy serves.\nexport function eagerPreloadUrls(\n importMap: ImportMap,\n candidates: Iterable<PreloadCandidate>\n): string[] {\n let mapped: Set<string> | undefined;\n const urls = new Set<string>();\n const bundlesAdded = new Set<string>();\n for (const { scopeUrl, entryFiles, bundle } of candidates) {\n mapped ??= mappedUrls(importMap);\n const entryUrls = entryFiles.map(file => _path.join(scopeUrl, file));\n const served = entryUrls.length > 0 && entryUrls.every(url => mapped!.has(url));\n if (!served) continue;\n entryUrls.forEach(url => urls.add(url));\n if (!bundle) continue;\n // Several copies of one remote share a bundle, so its chunks are joined once.\n const bundleKey = `${scopeUrl}\\n${bundle.name}`;\n if (bundlesAdded.has(bundleKey)) continue;\n bundlesAdded.add(bundleKey);\n bundle.chunkFiles.forEach(file => urls.add(_path.join(scopeUrl, file)));\n }\n return [...urls];\n}\n\nconst mappedUrls = (importMap: ImportMap) =>\n new Set([\n ...Object.values(importMap.imports),\n ...Object.values(importMap.scopes ?? {}).flatMap(scope => Object.values(scope)),\n ]);\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ImportMap, RemoteName, ScopedVersion } from 'lib/core/1.domain';\nimport {\n eagerPreloadUrls,\n type PreloadCandidate,\n} from 'lib/core/1.domain/import-map/eager-preloads';\n\nexport type CollectEagerPreloads = (importMap: ImportMap) => string[];\n\ntype Copy = Pick<ScopedVersion, 'preload' | 'bundle' | 'entries'>;\n\nexport function createCollectEagerPreloads(\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedExternalsRepo' | 'sharedChunksRepo'\n >\n): CollectEagerPreloads {\n return importMap => eagerPreloadUrls(importMap, candidates());\n\n // A copy brings every chunk of its own bundle, as the map's CHUNKS scope of its remote lists them.\n function* candidates(): Generator<PreloadCandidate> {\n for (const [remoteName, copy] of storedCopies()) {\n if (!copy.preload) continue;\n const scopeUrl = ports.remoteInfoRepo.tryGet(remoteName).get()?.scopeUrl;\n if (!scopeUrl) continue;\n yield {\n scopeUrl,\n entryFiles: Object.values(copy.entries),\n ...(copy.bundle && {\n bundle: {\n name: copy.bundle,\n chunkFiles: ports.sharedChunksRepo.tryGet(remoteName, copy.bundle).orElse([]),\n },\n }),\n };\n }\n }\n\n function* storedCopies(): Generator<[RemoteName, Copy]> {\n const shared = ports.sharedExternalsRepo;\n for (const shareScope of shared.getScopes())\n for (const external of Object.values(shared.getFromScope(shareScope)))\n for (const version of external.versions)\n for (const copy of version.remotes) yield [copy.name, copy];\n for (const [remoteName, externals] of Object.entries(ports.scopedExternalsRepo.getAll()))\n for (const copy of Object.values(externals)) yield [remoteName, copy];\n }\n}\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type {\n CommitOptions,\n ForCommittingChanges,\n} from '../driver-ports/init/for-committing-changes.port';\nimport type { ImportMap } from 'lib/core/1.domain/import-map/import-map.contract';\nimport type { LoggingConfig } from 'lib/core/2.app/config';\nimport { createPreloadHint } from './preload-hint';\nimport { createCollectEagerPreloads } from './collect-eager-preloads';\n\nexport function createCommitChanges(\n config: LoggingConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'scopedExternalsRepo'\n | 'sharedExternalsRepo'\n | 'sharedChunksRepo'\n | 'browser'\n >\n): ForCommittingChanges {\n const preload = createPreloadHint(config.log, ports.browser, 5);\n const collectEagerPreloads = createCollectEagerPreloads(ports);\n\n // Runs only after every earlier step succeeded: stored changes are shared with the host's other pages.\n // Preloads wait for the map, since the browser fixes a preloaded file's resolution when it fetches it.\n return (importMap: ImportMap, { markUndecided = false, ...browserOpts }: CommitOptions = {}) =>\n Promise.resolve(importMap)\n .then(map => addToBrowser(map, browserOpts))\n .then(added => {\n if (markUndecided) markUndecidedScopes();\n persistRepositoryChanges();\n preloadOnceAdded(added, importMap);\n });\n\n function addToBrowser(importMap: ImportMap, opts: Pick<CommitOptions, 'override'>) {\n const added = ports.browser.setImportMapFn(importMap, opts);\n config.log.debug(5, 'Added import map to browser.', importMap);\n // Wrapped: a promise returned bare from a .then would make the commit wait for it.\n return { added };\n }\n\n // Not awaited by the commit: a slow setter, such as the node loader's acknowledgement, must not hold up init.\n // A rejection is logged, then left unhandled so error trackers still see it.\n function preloadOnceAdded({ added }: { added: Promise<unknown> }, importMap: ImportMap) {\n Promise.resolve(added).then(\n () => preload(() => collectEagerPreloads(importMap)),\n error => {\n config.log.error(5, 'Could not add the import map.', error);\n return Promise.reject(error);\n }\n );\n }\n\n // A runtime load decides no serving build, so the next init decides one in each non-strict scope it wrote.\n function markUndecidedScopes() {\n const repo = ports.sharedExternalsRepo;\n for (const shareScope of repo.uncommittedScopes())\n if (repo.scopeType(shareScope) !== 'strict') repo.markUndecided(shareScope);\n }\n\n function persistRepositoryChanges() {\n ports.remoteInfoRepo.commit();\n ports.scopedExternalsRepo.commit();\n ports.sharedExternalsRepo.commit();\n ports.sharedChunksRepo.commit();\n return;\n }\n}\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ForRollingBackChanges } from '../driver-ports/init/for-rolling-back-changes.port';\nimport type { LoggingConfig } from '../config/log.contract';\n\nexport const createStateDump =\n (\n config: LoggingConfig,\n ports: Pick<DrivingContract, 'remoteInfoRepo' | 'sharedExternalsRepo' | 'scopedExternalsRepo'>\n ) =>\n (msg: string): void =>\n config.log.debug(0, msg, {\n remotes: { ...ports.remoteInfoRepo.getAll() },\n 'shared-externals': ports.sharedExternalsRepo\n .getScopes({ includeGlobal: true })\n .reduce(\n (acc, scope) => ({ ...acc, [scope]: ports.sharedExternalsRepo.getFromScope(scope) }),\n {}\n ),\n 'scoped-externals': ports.scopedExternalsRepo.getAll(),\n });\n\nexport function createRollbackChanges(\n config: LoggingConfig,\n ports: Pick<\n DrivingContract,\n 'remoteInfoRepo' | 'scopedExternalsRepo' | 'sharedExternalsRepo' | 'sharedChunksRepo'\n >\n): ForRollingBackChanges {\n const stateDump = createStateDump(config, ports);\n\n // The repositories outlive a failed load, so its half-written records would otherwise reach the next commit.\n return label =>\n Promise.resolve().then(() => {\n // The logger is user-supplied: if it throws, the rollback must still run.\n try {\n stateDump(`${label} STATE DUMP`);\n } finally {\n ports.remoteInfoRepo.rollback();\n ports.scopedExternalsRepo.rollback();\n ports.sharedExternalsRepo.rollback();\n ports.sharedChunksRepo.rollback();\n }\n });\n}\n", "import type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { ForExposingModuleLoader } from '../driver-ports/init/for-exposing-module-loader.port';\nimport type { LoadRemoteModule, PreloadRemoteModule } from 'lib/core/init-federation.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { LoggingConfig } from '../config/log.contract';\nimport * as _path from 'lib/utils/path';\nimport { createPreloadHint } from './preload-hint';\n\nexport function createExposeModuleLoader(\n config: LoggingConfig,\n ports: Pick<DrivingContract, 'remoteInfoRepo' | 'browser'>\n): ForExposingModuleLoader {\n const preload = createPreloadHint(config.log, ports.browser, 6);\n\n const loadRemoteModule: LoadRemoteModule = <TModule = unknown>(\n remoteName: string,\n exposedModule: string\n ): Promise<TModule> => {\n try {\n if (!ports.remoteInfoRepo.contains(remoteName)) {\n throw new NFError(`Remote '${remoteName}' is not initialized.`);\n }\n\n const remoteModuleUrl = ports.remoteInfoRepo\n .tryGetModule(remoteName, exposedModule)\n .orThrow(\n new NFError(\n `Exposed module '${exposedModule}' from remote '${remoteName}' not found in storage.`\n )\n );\n\n config.log.debug(6, `Loading initialized module '${remoteModuleUrl}'`);\n\n // The import fetches the module itself in the same tick; listing it again would only add a link.\n preload(() => ports.remoteInfoRepo.getModuleChunkUrls(remoteName, exposedModule));\n return ports.browser.importModule(remoteModuleUrl) as Promise<TModule>;\n } catch (error) {\n config.log.error(6, `Failed to load module ${_path.join(remoteName, exposedModule)}: `, {\n error,\n });\n\n return Promise.reject(\n new NFError(`Failed to load module ${_path.join(remoteName, exposedModule)}`)\n );\n }\n };\n\n // Apps call this speculatively, on hover or with route data of any shape, so even the lookup runs inside the\n // hint's guard, and an unknown module is a debug line rather than a warning.\n const preloadRemoteModule: PreloadRemoteModule = (remoteName, exposedModule) =>\n preload(() => {\n const url = ports.remoteInfoRepo.tryGetModule(remoteName, exposedModule);\n if (!url.isPresent()) {\n config.log.debug(6, `Nothing to preload for '${remoteName}/${exposedModule}'.`);\n return [];\n }\n return [url.get()!, ...ports.remoteInfoRepo.getModuleChunkUrls(remoteName, exposedModule)];\n });\n\n return () => Promise.resolve({ loadRemoteModule, preloadRemoteModule });\n}\n", "import type { RemoteEntryUrl } from 'lib/core/1.domain/remote-entry/manifest.contract';\nimport type { RemoteName } from 'lib/core/1.domain/remote/remote-info.contract';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { ModeConfig } from '../config/mode.contract';\nimport type { ForGettingRemoteEntry } from '../driver-ports/init/for-getting-remote-entry.port';\nimport type { RemoteRef } from '../driver-ports/init/flow.contract';\nimport { Optional } from 'lib/utils/optional';\nimport type { RemoteEntry } from 'lib/core/1.domain';\nimport * as _path from 'lib/utils/path';\n\nconst normalizeRemoteRef = (remote?: RemoteRef): { name?: RemoteName; integrity?: string } => {\n if (!remote) return {};\n if (typeof remote === 'string') return { name: remote };\n return remote;\n};\n\nexport function createGetRemoteEntry(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'remoteEntryProvider' | 'remoteInfoRepo' | 'sse'>\n): ForGettingRemoteEntry {\n return async (remoteEntryUrl: RemoteEntryUrl, remote?: RemoteRef) => {\n const { name: remoteName, integrity } = normalizeRemoteRef(remote);\n\n // The committed import map cannot drop a remote's imports, so a dynamic init never replaces a known remote.\n const knownAtUrl = findCachedRemoteAt(remoteEntryUrl);\n if (knownAtUrl) {\n config.log.debug(\n 7,\n `Found remote '${knownAtUrl}' at '${remoteEntryUrl}' in storage, omitting fetch.`\n );\n return Optional.empty<RemoteEntry>();\n }\n if (!!remoteName && ports.remoteInfoRepo.contains(remoteName))\n return warnInitialized(remoteName, remoteEntryUrl);\n\n try {\n const remoteEntry = integrity\n ? await ports.remoteEntryProvider.provide(remoteEntryUrl, { integrity })\n : await ports.remoteEntryProvider.provide(remoteEntryUrl);\n\n config.log.debug(\n 7,\n `[${remoteEntry.name}] Fetched from '${remoteEntry.url}', exposing: ${JSON.stringify(remoteEntry.exposes)}`\n );\n\n if (!!remoteName && remoteEntry.name !== remoteName) {\n const errorMsg = `Fetched remote '${remoteEntry.name}' does not match requested '${remoteName}'.`;\n if (config.strict.strictRemoteEntry) {\n config.log.error(7, errorMsg);\n throw new NFError('Could not fetch remote entry');\n }\n config.log.warn(7, errorMsg + ' Omitting expected name.');\n }\n\n if (ports.remoteInfoRepo.contains(remoteEntry.name))\n return warnInitialized(remoteEntry.name, remoteEntryUrl);\n return Optional.of(checkForSSE(remoteEntry));\n } catch (error) {\n config.log.error(\n 7,\n `[${remoteName ?? 'unknown'}] Could not fetch remoteEntry from ${remoteEntryUrl}.`,\n error\n );\n return Promise.reject(\n new NFError(`[${remoteName ?? remoteEntryUrl}] Could not fetch remoteEntry.`)\n );\n }\n };\n\n function warnInitialized(name: RemoteName, remoteEntryUrl: string): Optional<RemoteEntry> {\n const initializedFrom = ports.remoteInfoRepo\n .tryGet(name)\n .map(info => _path.join(info.scopeUrl, 'remoteEntry.json'))\n .get();\n config.log.warn(\n 7,\n `[${name}] Already initialized from '${initializedFrom}', ignoring '${remoteEntryUrl}'.`\n );\n return Optional.empty<RemoteEntry>();\n }\n\n function findCachedRemoteAt(remoteEntryUrl: string): RemoteName | undefined {\n return Object.entries(ports.remoteInfoRepo.getAll()).find(\n ([, info]) => _path.join(info.scopeUrl, 'remoteEntry.json') === remoteEntryUrl\n )?.[0];\n }\n\n function checkForSSE(entry: RemoteEntry): RemoteEntry {\n if (config.sse) {\n if (entry.buildNotificationsEndpoint) {\n ports.sse.watchRemoteBuilds(\n _path.join(_path.getScope(entry.url), entry.buildNotificationsEndpoint)\n );\n config.log.debug(7, `Registered SSE endpoint of remote '${entry.name}' `);\n } else {\n config.log.debug(7, `Remote ${entry.name} has no defined 'buildNotificationsEndpoint'`);\n }\n }\n return entry;\n }\n}\n", "import type { ForUpdatingCache } from '../driver-ports/init/for-updating-cache';\nimport {\n type RemoteEntry,\n type DenseSharedInfo,\n type ExternalName,\n type RemoteName,\n type SharedVersionAction,\n type SharedVersionMeta,\n GLOBAL_SCOPE,\n} from 'lib/core/1.domain';\nimport type { LoadActions } from 'lib/core/1.domain/remote-entry/load-actions.contract';\nimport { createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport { addRemoteToVersion } from 'lib/core/1.domain/externals/basis';\nimport { loadSplitsPackage } from 'lib/core/1.domain/externals/serving';\nimport { type Claim, committedClaims } from 'lib/core/1.domain/externals/claims';\nimport {\n groupByPackage,\n type PackageOf,\n packageOfIn,\n type Specifier,\n} from 'lib/core/1.domain/externals/specifier';\nimport { type LabelledCopy, pooledPackagesWith } from 'lib/core/1.domain/pooling/membership';\nimport type { DrivingContract } from '../driving-ports/driving.contract';\nimport type { LoggingConfig } from '../config/log.contract';\nimport * as _path from 'lib/utils/path';\nimport { NFError } from 'lib/core/native-federation.error';\nimport type { ModeConfig } from 'lib/core/2.app/config/mode.contract';\nimport { createStoreRemoteEntry, type SharedExternalContext } from './store-remote-entry';\n\ntype Pending = { external: DenseSharedInfo; ctx: SharedExternalContext };\n\ntype CommittedClaims = Map<Specifier, Claim>;\n\ntype PackageClaims = readonly [Specifier, Claim][];\n\n// Indexes the record as decidePackages reads it, so it must not outlive it: applyDecision writes that record.\ntype LoadView = {\n packageOf: PackageOf;\n claims: CommittedClaims;\n claimsOf(pkg: ExternalName): PackageClaims;\n inPool(pkg: ExternalName): boolean;\n};\n\ntype Rejection = { item: Pending; specifier: Specifier; claim: Claim };\n\n// share: the remote's build opens the package; skip: it runs the build the map serves it from; scope: its own\n// build beside the map (partlyServed: the map serves some of it, or all of it from two builds).\ntype Decision =\n | { action: 'share' }\n | { action: 'scope'; partlyServed: boolean }\n | { action: 'skip'; files: Map<Specifier, SharedVersionMeta> };\n\nexport function createUpdateCache(\n config: LoggingConfig & ModeConfig,\n ports: Pick<\n DrivingContract,\n | 'remoteInfoRepo'\n | 'sharedExternalsRepo'\n | 'scopedExternalsRepo'\n | 'sharedChunksRepo'\n | 'versionCheck'\n >\n): ForUpdatingCache {\n const storeRemoteEntry = createStoreRemoteEntry(config, ports, 8);\n // Read per call so a port swapped after wiring is honoured.\n const accepts = createAcceptsTag(\n (tag, range) => ports.versionCheck.isCompatible(tag, range),\n (a, b) => ports.versionCheck.compare(a, b)\n );\n\n // The import map is committed, so each package the remote shares runs wholly from one build; see\n // docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n return remoteEntry => {\n try {\n // Collected before any copy is stored, so every decision reads the record the committed map came from.\n const pending: Pending[] = [];\n storeRemoteEntry(remoteEntry, (_, external, ctx) => pending.push({ external, ctx }));\n const decisions = decidePackages(remoteEntry, pending);\n\n const actions: LoadActions = {};\n for (const item of pending)\n actions[item.external.packageName] = applyDecision(remoteEntry, item, decisions.get(item)!);\n\n return Promise.resolve({ entry: remoteEntry, actions });\n } catch (error) {\n return Promise.reject(error);\n }\n };\n\n function decidePackages(remoteEntry: RemoteEntry, pending: Pending[]): Map<Pending, Decision> {\n const decisions = new Map<Pending, Decision>();\n const viewOf = loadViewOf(remoteEntry, pending);\n for (const group of pendingPerPackage(pending, viewOf)) {\n // The strict scope shares every version side by side.\n const decision =\n group[0]!.ctx.scopeType === 'strict'\n ? ({ action: 'share' } as const)\n : decidePackage(remoteEntry, group, viewOf(group[0]!.external.shareScope));\n for (const item of group) decisions.set(item, decision);\n }\n scopeOpenedPackages(decisions);\n return decisions;\n }\n\n function pendingPerPackage(\n pending: Pending[],\n viewOf: (shareScope: string | undefined) => LoadView\n ): Pending[][] {\n const packages = new Map<string, Pending[]>();\n for (const item of pending) {\n const { shareScope, packageName } = item.external;\n // The strict scope shares each external whatever its package, so it needs no view.\n const pkg =\n item.ctx.scopeType === 'strict' ? packageName : viewOf(shareScope).packageOf(packageName);\n const key = `${shareScope ?? GLOBAL_SCOPE}\\0${pkg}`;\n const group = packages.get(key);\n if (group) group.push(item);\n else packages.set(key, [item]);\n }\n return [...packages.values()];\n }\n\n function loadViewOf(\n remoteEntry: RemoteEntry,\n pending: Pending[]\n ): (shareScope: string | undefined) => LoadView {\n const views = new Map<string, LoadView>();\n return shareScope => {\n const scope = shareScope ?? GLOBAL_SCOPE;\n let view = views.get(scope);\n if (!view) {\n const record = ports.sharedExternalsRepo.getFromScope(shareScope);\n const claims = committedClaims(Object.entries(record), {\n shareScope: scope,\n without: remoteEntry.name,\n });\n // The load's copies count as stored: they can only merge packages the committed map serves apart.\n const packageOf = packageOfIn(record, loadingIn(pending, scope));\n const claimsIn = groupByPackage(claims, ([specifier]) => specifier, packageOf);\n let pooled: Set<ExternalName> | undefined;\n view = {\n packageOf,\n claims,\n claimsOf: pkg => claimsIn.get(pkg) ?? [],\n inPool: pkg => {\n pooled ??= pooledPackagesWith(record, labelledCopiesIn(pending, scope), packageOf);\n return pooled.has(pkg);\n },\n };\n views.set(scope, view);\n }\n return view;\n };\n }\n\n function inScope(pending: Pending[], scope: string): Pending[] {\n return pending.filter(({ external }) => (external.shareScope ?? GLOBAL_SCOPE) === scope);\n }\n\n function loadingIn(pending: Pending[], scope: string): [ExternalName, SharedVersionMeta][] {\n return inScope(pending, scope).map(({ external, ctx }) => [external.packageName, ctx.remote]);\n }\n\n // The load's copies count as stored, so a pool only their labels form is judged as the gate will see it.\n function labelledCopiesIn(pending: Pending[], scope: string): LabelledCopy[] {\n return inScope(pending, scope).map(({ external, ctx }) => ({\n name: external.packageName,\n pool: ctx.remote.pool,\n }));\n }\n\n function scopeOpenedPackages(decisions: Map<Pending, Decision>): void {\n // An opened package's files resolve through the loader's scope, so its consumers would reach that build.\n if (![...decisions.values()].some(d => d.action === 'scope' && d.partlyServed)) return;\n for (const [item, decision] of decisions)\n if (decision.action === 'share' && item.ctx.scopeType !== 'strict')\n decisions.set(item, { action: 'scope', partlyServed: false });\n }\n\n function decidePackage(remoteEntry: RemoteEntry, group: Pending[], view: LoadView): Decision {\n const pkg = view.packageOf(group[0]!.external.packageName);\n const claims = view.claimsOf(pkg);\n if (claims.length === 0) return { action: 'share' };\n\n const specifiers = group.flatMap(({ external }) => Object.keys(external.entries));\n const builds = specifiers.every(specifier => view.claims.has(specifier))\n ? new Set(specifiers.map(specifier => view.claims.get(specifier)!.copy.name))\n : undefined;\n\n const rejections = group.flatMap(item => rejectionsOf(item, view.claims));\n if (rejections.length > 0) {\n const copies = group.map(({ ctx }) => ({ tag: ctx.tag, copy: ctx.remote }));\n const splits =\n (builds !== undefined && builds.size > 1) ||\n loadSplitsPackage(pkg, copies, claims, accepts);\n for (const rejection of refused(rejections, splits, view.inPool(pkg)))\n reportIncompatible(remoteEntry, rejection);\n return { action: 'scope', partlyServed: false };\n }\n\n if (!builds || builds.size > 1) return { action: 'scope', partlyServed: true };\n return { action: 'skip', files: servingFiles(claims, builds) };\n }\n\n // What the map serves of the package from the build the remote follows; a named scope maps all of it, as init\n // maps a skip copy's serving version.\n function servingFiles(\n claims: PackageClaims,\n builds: ReadonlySet<RemoteName>\n ): Map<Specifier, SharedVersionMeta> {\n const files = new Map<Specifier, SharedVersionMeta>();\n for (const [specifier, { copy }] of claims)\n if (builds.has(copy.name)) files.set(specifier, copy);\n return files;\n }\n\n // A non-strict range follows the map's tag all the same, as at init.\n function rejectionsOf(item: Pending, claims: CommittedClaims): Rejection[] {\n const { external, ctx } = item;\n if (!ctx.remote.strictVersion) return [];\n return Object.keys(external.entries).flatMap(specifier => {\n const claim = claims.get(specifier);\n return claim && !accepts(claim.tag, ctx.tag, ctx.remote.requiredVersion)\n ? [{ item, specifier, claim }]\n : [];\n });\n }\n\n // The first rejection of each copy that a cold init keeping the committed builds refuses too; see\n // docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n function refused(rejections: Rejection[], splits: boolean, pooled: boolean): Rejection[] {\n const first = new Map<Pending, Rejection>();\n for (const rejection of rejections)\n if (!first.has(rejection.item) && (pooled || !splits || electionKeeps(rejection)))\n first.set(rejection.item, rejection);\n return [...first.values()];\n }\n\n // A cold election with the loader refuses the claimed tag where no tag pleases every strict copy, and otherwise\n // keeps it only on a host row, or the newest with latestSharedExternal.\n function electionKeeps({ item: { external, ctx }, claim }: Rejection): boolean {\n if (claim.external !== external.packageName) return false;\n const versions =\n ports.sharedExternalsRepo.tryGet(claim.external, external.shareScope).get()?.versions ?? [];\n const strict = [\n { tag: ctx.tag, copy: ctx.remote },\n ...versions.flatMap(v =>\n v.remotes.filter(r => r.strictVersion).map(copy => ({ tag: v.tag, copy }))\n ),\n ];\n const tags = [ctx.tag, ...versions.map(v => v.tag)];\n if (!tags.some(tag => strict.every(s => accepts(tag, s.tag, s.copy.requiredVersion))))\n return true;\n const host = versions.find(v => v.host);\n if (host) return host.tag === claim.tag;\n if (!config.profile.latestSharedExternal) return false;\n return tags.every(tag => ports.versionCheck.compare(claim.tag, tag) >= 0);\n }\n\n function reportIncompatible(\n remoteEntry: RemoteEntry,\n { item: { external, ctx }, specifier, claim }: Rejection\n ) {\n const errorMsg = `[${external.shareScope ?? GLOBAL_SCOPE}][${remoteEntry.name}] ${specifier}@${\n ctx.tag\n } Is not compatible with existing ${specifier}@${claim.tag} requiredRange '${\n ctx.remote.requiredVersion\n }'`;\n\n if (config.strict.strictExternalCompatibility) {\n config.log.error(8, errorMsg);\n throw new NFError(`Could not process remote '${remoteEntry.name}'`);\n }\n config.log.warn(8, errorMsg);\n }\n\n function applyDecision(\n remoteEntry: RemoteEntry,\n { external, ctx }: Pending,\n decision: Decision\n ): LoadActions[string] {\n storeCopy(ctx, decision.action);\n if (decision.action !== 'skip') return { action: decision.action };\n\n const covered = Object.keys(external.entries);\n if (!external.shareScope) return { action: 'skip', covered };\n return {\n action: 'skip',\n covered,\n override: overrideFrom(remoteEntry, external, decision.files),\n };\n }\n\n // A skip copy keeps out of the share row, where it would claim on the next page what the map serves from the\n // build it follows. A scoped one stays inside a shareable version, where a later import-map build would\n // redirect it to the basis.\n function storeCopy(ctx: SharedExternalContext, action: SharedVersionAction): void {\n const { tag, remote } = ctx;\n const cached = ctx.readRecord();\n const shared = cached.versions.find(v => v.tag === tag && v.action === 'share');\n if (shared && action !== 'scope') ctx.assertSameVersionCompatibility(shared);\n\n remote.cached = action !== 'skip';\n const row =\n action === 'share' ? shared : cached.versions.find(v => v.tag === tag && v.action === action);\n // Only a package the map doesn't serve is shared, so the loader serves it. The strict scope serves every version\n // side by side: a strict row keeps the basis the committed map and getShared serve it from.\n const loaderServes = action === 'share' && ctx.scopeType !== 'strict';\n if (!row) cached.versions.push({ tag, action, host: false, remotes: [remote] });\n else if (loaderServes) addRemoteToVersion(row, remote);\n else row.remotes.push(remote);\n if (loaderServes) cached.servingBuild = remote.name;\n ctx.write();\n }\n\n // A named scope has no `imports` to inherit: each entrypoint maps to the file the committed map serves it from.\n function overrideFrom(\n remoteEntry: RemoteEntry,\n external: DenseSharedInfo,\n files: Map<Specifier, SharedVersionMeta>\n ): Record<string, string> {\n return Object.fromEntries(\n Array.from(files, ([specifier, copy]) => [\n specifier,\n _path.join(providerScopeUrl(remoteEntry, external, copy.name), copy.entries[specifier]!),\n ])\n );\n }\n\n function providerScopeUrl(\n remoteEntry: RemoteEntry,\n external: DenseSharedInfo,\n providerName: string\n ): string {\n return ports.remoteInfoRepo\n .tryGet(providerName)\n .map(remote => remote.scopeUrl)\n .orThrow(() => {\n config.log.error(\n 8,\n `[${external.shareScope ?? GLOBAL_SCOPE}][${remoteEntry.name}][${\n external.packageName\n }@${external.version}][override] Remote name not found in cache.`\n );\n return new NFError(`Could not find override url from remote ${providerName}`);\n });\n }\n}\n", "import {\n type ExternalName,\n GLOBAL_SCOPE,\n type RemoteName,\n type VersionName,\n} from 'lib/core/1.domain';\nimport type { LoadActions } from 'lib/core/1.domain/remote-entry/load-actions.contract';\nimport { committedClaims } from 'lib/core/1.domain/externals/claims';\nimport type { AcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport {\n type PackageOf,\n type Specifier,\n SpecifierTags,\n} from 'lib/core/1.domain/externals/specifier';\nimport * as _path from 'lib/utils/path';\nimport { type Build, buildOf, type Copy, recordsByRemote } from './builds';\nimport type { PoolMember } from './membership';\nimport { agrees, unwitnessedGap } from './rules';\n\n// See docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n\n// One file: the remote whose scope URL it lives under, and its name there.\ntype Served = { tag: VersionName; remote: RemoteName; file: string };\n\ntype CommittedView = {\n packageOf: PackageOf;\n builds: Map<RemoteName, Build>;\n // What the committed global map serves per specifier: `imports`, or the shareScope's scopes.\n global: Map<Specifier, Served>;\n // Per build, the specifiers it runs from its own or a subpool's files, at the tag it runs.\n runsOffMap: Map<RemoteName, Map<Specifier, Served>>;\n};\n\nexport type GateMiss =\n | { cause: 'incompatible'; specifier: Specifier; tag: VersionName }\n | { cause: 'uncovered'; specifier: Specifier }\n | { cause: 'uncovered'; unshipped: true }\n | { cause: 'uncovered'; owner: RemoteName; specifier: Specifier; tag: VersionName };\n\n// `toSkip`: the copy moves out of a share row (opened or joined) or a resolver scope into a skip row.\ntype MapCover = {\n name: ExternalName;\n toSkip: boolean;\n override: Record<Specifier, string>;\n};\n\ntype MappedFiles = { covered: Set<Specifier>; override: Record<Specifier, string> };\n\n// One member the remote ships, with its action and what the map would serve of it. A build split across\n// bundles ships the member in several records at one tag, so `entries` joins them (#133).\ntype Coverable = MappedFiles & {\n member: PoolMember;\n action: LoadActions[string];\n entries: Record<Specifier, string>;\n inShareRow: boolean;\n};\n\n// Where the remote resolves a specifier it ships: the map's file, or its own.\ntype Reach = { remote: RemoteName; file: string };\n\ntype MapPolicy = {\n shareScope: string;\n scopeUrlOf: (remote: RemoteName) => string | undefined;\n};\n\n// A `scope` copy counts as served by its build: its files are already in the map under its own scope.\n// `without`'s build is left out of `builds` too.\nexport function committedView(\n members: PoolMember[],\n shipped: ReadonlyMap<RemoteName, readonly Copy[]>,\n recordOrder: ExternalName[],\n {\n shareScope,\n without,\n packageOf,\n }: { shareScope: string; without?: RemoteName; packageOf: PackageOf }\n): CommittedView {\n const global: CommittedView['global'] = new Map();\n\n // Mirrors what `generate-import-map` emitted, so `global` is what the committed map really serves.\n const claims = committedClaims(inRecordOrder(members, recordOrder), { shareScope, without });\n for (const [specifier, { tag, copy }] of claims)\n global.set(specifier, { tag, remote: copy.name, file: copy.entries[specifier]! });\n\n const builds = new Map<RemoteName, Build>();\n for (const [owner, copies] of shipped)\n if (owner !== without) builds.set(owner, buildOf(owner, copies, packageOf));\n\n const fileOf = subpoolFilesOf(members);\n return {\n packageOf,\n builds,\n global,\n runsOffMap: runsOffMapOf(members, global, builds, fileOf),\n };\n}\n\nfunction subpoolFilesOf(members: PoolMember[]): Map<RemoteName, Map<Specifier, string>> {\n const subpoolOwners = new Set<RemoteName>();\n for (const member of members)\n for (const version of member.external.versions)\n for (const { servedBy } of version.remotes) if (servedBy) subpoolOwners.add(servedBy);\n const fileOf = new Map<RemoteName, Map<Specifier, string>>();\n for (const member of members)\n for (const version of member.external.versions)\n for (const { name, entries } of version.remotes) {\n if (!subpoolOwners.has(name)) continue;\n let files = fileOf.get(name);\n if (!files) fileOf.set(name, (files = new Map()));\n // Per specifier, earlier rows first.\n for (const specifier in entries)\n if (!files.has(specifier)) files.set(specifier, entries[specifier]!);\n }\n return fileOf;\n}\n\nfunction runsOffMapOf(\n members: PoolMember[],\n global: CommittedView['global'],\n builds: CommittedView['builds'],\n fileOf: ReadonlyMap<RemoteName, ReadonlyMap<Specifier, string>>\n): CommittedView['runsOffMap'] {\n const runsOffMap: CommittedView['runsOffMap'] = new Map();\n for (const member of members)\n for (const version of member.external.versions)\n for (const meta of version.remotes) {\n const { servedBy } = meta;\n // A share copy runs the map's files; only the loader's may ship more, and no reader looks it up.\n if (version.action === 'share' && !servedBy) continue;\n let runs = runsOffMap.get(meta.name);\n if (!runs) runsOffMap.set(meta.name, (runs = new Map()));\n for (const specifier in meta.entries) {\n // A skip copy runs its own file only for an entrypoint the map lacks.\n if (version.action === 'skip' && !servedBy && global.has(specifier)) continue;\n // A subpool member's copy keeps its own tag in the record but runs its build's files.\n const tag =\n (servedBy ? builds.get(servedBy)?.tags.pinnedTag(specifier) : undefined) ?? version.tag;\n const file = servedBy && fileOf.get(servedBy)?.get(specifier);\n runs.set(\n specifier,\n file\n ? { tag, remote: servedBy, file }\n : { tag, remote: meta.name, file: meta.entries[specifier]! }\n );\n }\n }\n return runsOffMap;\n}\n\n// See docs/version-resolver.md \u00A7\"Scope and dynamic init\", step 1. A resolver scope needs no rule of its own:\n// a range that rejects the map's tag is a miss here too.\nexport function judgeRemote(\n copies: readonly Copy[],\n view: CommittedView,\n accepts: AcceptsTag\n): 'global' | GateMiss {\n const { rejected, missing } = scan(copies, view, accepts);\n if (rejected) return { cause: 'incompatible', ...rejected };\n const globalTags = new SpecifierTags(\n view.packageOf,\n [...view.global].map(([s, { tag }]) => [s, tag] as const)\n );\n const binding = offMapBinding(copies, view, globalTags);\n if (binding) return { cause: 'uncovered', ...binding };\n // A package the map serves from two builds is a combination no build shipped, whatever the tags say: the\n // load's own copies can merge libraries the committed builds keep apart.\n if (servedSplit(copies, view)) return { cause: 'uncovered', unshipped: true };\n // The map's tags must be a combination one build shipped: agreeing is its own witness, otherwise one\n // committed build must be.\n if (agrees(copies, globalTags)) return 'global';\n if (missing !== undefined) return { cause: 'uncovered', specifier: missing };\n if (unwitnessedGap(copies, globalTags, view.builds.values()) === undefined) return 'global';\n return { cause: 'uncovered', unshipped: true };\n}\n\nfunction servedSplit(copies: readonly Copy[], view: CommittedView): boolean {\n const loaded = new Set(copies.flatMap(copy => copy.specifiers.map(view.packageOf)));\n const servedBy = new Map<ExternalName, RemoteName>();\n for (const [specifier, { remote }] of view.global) {\n const pkg = view.packageOf(specifier);\n if (!loaded.has(pkg)) continue;\n const first = servedBy.get(pkg);\n if (first === undefined) servedBy.set(pkg, remote);\n else if (first !== remote) return true;\n }\n return false;\n}\n\ntype Binding = { owner: RemoteName; specifier: Specifier; tag: VersionName };\n\nexport type CoverResult =\n { covers: MapCover[] } | { unmapped: RemoteName } | { gap: Specifier } | { bound: Binding };\n\n// `covered` is per external, but the map serves by specifier: an entrypoint another member ships as a package\n// of its own (flat vs dense) is served all the same. A named scope has no `imports` to inherit, so the remote's\n// own scope maps each such specifier to the file the committed map serves it from, replacing the resolver's\n// override. Covering fails, and the remote serves the pool itself, when it would reach one specifier at two\n// files (`bound`) or take a copy whose package the map serves only in part (`gap`).\nexport function coverFromMap(\n remote: RemoteName,\n mine: readonly PoolMember[],\n view: CommittedView,\n actions: Readonly<LoadActions>,\n policy: MapPolicy\n): CoverResult {\n const files: Coverable[] = [];\n for (const member of mine) {\n const action = actions[member.name]!;\n const copies = recordsByRemote(member).get(remote);\n if (!copies) continue;\n\n // First record wins, as in the import map.\n const entries: Record<Specifier, string> = {};\n for (const { meta } of copies)\n for (const [specifier, file] of Object.entries(meta.entries)) entries[specifier] ??= file;\n const inShareRow = copies.some(({ version }) => version.action === 'share');\n const mapped = mapFiles(entries, view, policy, action);\n if ('unmapped' in mapped) return mapped;\n files.push({ member, action, entries, inShareRow, ...mapped });\n }\n\n const reaches = reachesOf(remote, files, view);\n const bound = boundByFile(reaches, view);\n if (bound !== undefined) return { bound };\n const servedPackages = new Set([...view.global.keys()].map(view.packageOf));\n const gap = files\n .map(file => gapOf(file, servedPackages, view.packageOf))\n .find(specifier => specifier !== undefined);\n if (gap !== undefined) return { gap };\n return { covers: files.filter(covering).map(coverOf) };\n}\n\n// The first entrypoint a copy ships that the map lacks, when the map serves another entrypoint of its package.\nfunction gapOf(\n { entries, covered }: Coverable,\n servedPackages: ReadonlySet<string>,\n packageOf: PackageOf\n): Specifier | undefined {\n const entrypoints = Object.keys(entries);\n const missing = entrypoints.filter(specifier => !covered.has(specifier));\n if (missing.length < entrypoints.length) return missing[0];\n return missing.find(specifier => servedPackages.has(packageOf(specifier)));\n}\n\nfunction covering({ action, entries, covered }: Coverable): boolean {\n if (action.action === 'skip') return true;\n const entrypoints = Object.keys(entries);\n return entrypoints.length > 0 && entrypoints.every(specifier => covered.has(specifier));\n}\n\nfunction coverOf({ member, action, inShareRow, covered, override }: Coverable): MapCover {\n // A copy that joined a share row would claim, on the next page, what the map serves from another member.\n const toSkip = action.action !== 'skip' || (covered.size > action.covered!.length && inShareRow);\n return { name: member.name, toSkip, override };\n}\n\n// Where the remote resolves each specifier it ships once the covers apply: the map's file, else its own.\nfunction reachesOf(\n remote: RemoteName,\n files: readonly Coverable[],\n view: CommittedView\n): Map<Specifier, Reach> {\n const reaches = new Map<Specifier, Reach>();\n const fromMap = (specifier: Specifier): Reach | undefined => {\n const served = view.global.get(specifier);\n return served && { remote: served.remote, file: served.file };\n };\n for (const file of files) {\n const takesMap = covering(file);\n for (const [specifier, own] of Object.entries(file.entries)) {\n if (!takesMap || !file.covered.has(specifier)) reaches.set(specifier, { remote, file: own });\n else {\n const reach = fromMap(specifier);\n if (reach) reaches.set(specifier, reach);\n }\n }\n }\n return reaches;\n}\n\n// `offMapBinding` by file rather than tag: a committed file binds its pool-mates where its build resolves them\n// (off the map where it runs them so, else the map), so every build whose file the remote reaches, directly or\n// through another such file, must resolve each specifier it ships to the file the remote does, or the one the\n// first such build does.\nfunction boundByFile(\n reaches: ReadonlyMap<Specifier, Reach>,\n view: CommittedView\n): Binding | undefined {\n const servers = new Set<RemoteName>();\n for (const { remote } of reaches.values()) if (view.builds.has(remote)) servers.add(remote);\n\n const firstRun = new Map<Specifier, { remote: RemoteName; file: string }>();\n // A Set iterates what is added during the loop, so a build first reached through another's file is judged too.\n for (const build of servers)\n for (const specifier of view.builds.get(build)!.tags.keys()) {\n const served = view.runsOffMap.get(build)?.get(specifier) ?? view.global.get(specifier);\n if (served === undefined) continue;\n const reached = reaches.get(specifier) ?? firstRun.get(specifier);\n if (reached === undefined) {\n firstRun.set(specifier, served);\n if (view.builds.has(served.remote)) servers.add(served.remote);\n } else if (reached.remote !== served.remote || reached.file !== served.file)\n return { owner: build, specifier, tag: served.tag };\n }\n return undefined;\n}\n\nfunction mapFiles(\n entries: Record<Specifier, string>,\n view: CommittedView,\n policy: MapPolicy,\n action: LoadActions[string]\n): MappedFiles | { unmapped: RemoteName } {\n const covered = new Set(action.covered);\n const override = { ...action.override };\n for (const specifier in entries) {\n const source = view.global.get(specifier);\n if (!source) continue;\n if (policy.shareScope !== GLOBAL_SCOPE) {\n const scopeUrl = policy.scopeUrlOf(source.remote);\n if (!scopeUrl) return { unmapped: source.remote };\n override[specifier] = _path.join(scopeUrl, source.file);\n }\n covered.add(specifier);\n }\n return { covered, override };\n}\n\nfunction scan(copies: readonly Copy[], view: CommittedView, accepts: AcceptsTag) {\n let rejected: { specifier: Specifier; tag: VersionName } | undefined;\n let missing: Specifier | undefined;\n for (const copy of copies)\n for (const s of copy.specifiers) {\n const global = view.global.get(s);\n if (global === undefined) missing ??= s;\n else if (!accepts(global.tag, copy.tag, copy.requiredVersion))\n rejected ??= { specifier: s, tag: global.tag };\n }\n return { rejected, missing };\n}\n\n// A committed file binds its pool-mates where its build runs them, so a build serving the remote that runs one\n// off the map at another tag than the remote reaches elsewhere would split it. That tag is the map's, else the\n// remote's own, else the first serving build's.\nfunction offMapBinding(copies: readonly Copy[], view: CommittedView, globalTags: SpecifierTags) {\n const own = new SpecifierTags(\n view.packageOf,\n copies.flatMap(c => c.specifiers.map(s => [s, c.tag] as const))\n );\n const servers = new Set<RemoteName>();\n for (const copy of copies)\n for (const specifier of copy.specifiers) {\n const build = view.global.get(specifier)?.remote;\n if (build !== undefined) servers.add(build);\n }\n\n const firstRun = new SpecifierTags(view.packageOf);\n for (const build of servers)\n for (const [specifier, { tag }] of view.runsOffMap.get(build) ?? []) {\n const reached =\n globalTags.pinnedTag(specifier) ??\n own.pinnedTag(specifier) ??\n firstRun.pinnedTag(specifier);\n if (reached === undefined) firstRun.set(specifier, tag);\n else if (reached !== tag) return { owner: build, specifier, tag };\n }\n return undefined;\n}\n\nfunction inRecordOrder(members: PoolMember[], recordOrder: ExternalName[]) {\n const rank = new Map(recordOrder.map((name, i) => [name, i]));\n return [...members]\n .sort((a, b) => rank.get(a.name)! - rank.get(b.name)!)\n .map(m => [m.name, m.external] as const);\n}\n", "import type { ForPoolingDynamicExternals } from '../../driver-ports/init/for-pooling-dynamic-externals.port';\nimport type { ModeConfig } from '../../config/mode.contract';\nimport type { LoggingConfig } from '../../config/log.contract';\nimport type { DrivingContract } from '../../driving-ports/driving.contract';\nimport {\n type ExternalName,\n GLOBAL_SCOPE,\n type PoolCause,\n type RemoteEntry,\n type RemoteName,\n STRICT_SCOPE,\n type SharedExternal,\n type SharedInfoActions,\n type shareScope,\n} from 'lib/core/1.domain';\nimport type { LoadActions } from 'lib/core/1.domain/remote-entry/load-actions.contract';\nimport { copiesByRemote, specifierCount } from 'lib/core/1.domain/pooling/builds';\nimport { buildPools, type PoolMember, type PoolName } from 'lib/core/1.domain/pooling/membership';\nimport { scopeHasPoolState } from 'lib/core/1.domain/pooling/pool-state';\nimport {\n committedView,\n coverFromMap,\n type CoverResult,\n type GateMiss,\n judgeRemote,\n} from 'lib/core/1.domain/pooling/gate';\nimport { type CopyMove, movedRecord, renamedRecords } from 'lib/core/1.domain/pooling/records';\nimport { createAcceptsTag } from 'lib/core/1.domain/externals/compatibility';\nimport type { PackageOf } from 'lib/core/1.domain/externals/specifier';\n\nexport function createPoolDynamicExternals(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'sharedExternalsRepo' | 'remoteInfoRepo' | 'versionCheck'>\n): ForPoolingDynamicExternals {\n // Read per call so a port swapped after wiring is honoured.\n const accepts = createAcceptsTag(\n (tag, range) => ports.versionCheck.isCompatible(tag, range),\n (a, b) => ports.versionCheck.compare(a, b)\n );\n const scopeUrlOf = (remote: RemoteName) => ports.remoteInfoRepo.tryGet(remote).get()?.scopeUrl;\n\n // The committed map is immutable, so this only rewrites the loaded remote's own actions and copies, never\n // another remote's. See docs/version-resolver.md \u00A7\"Scope and dynamic init\".\n return ({ entry, actions }) => {\n for (const [scope, names] of poolableNames(entry, actions)) {\n // A label anywhere in the committed scope forms pools this entry is subject to \u2014 its own label is not\n // required, and the pool covers the whole external, this entry's copies included.\n const committed = ports.sharedExternalsRepo.getFromScope(scope);\n if (!scopeHasPoolState(committed)) continue;\n\n const { pools, packageOf } = buildPools(committed);\n const moves = judgeScope(\n entry.name,\n names,\n actions,\n pools,\n packageOf,\n Object.keys(committed),\n scope\n );\n writeMoves(entry.name, names, moves, committed, pools, scope);\n }\n\n return Promise.resolve({ entry, actions: publicActions(actions) });\n };\n\n function judgeScope(\n remote: RemoteName,\n names: ReadonlySet<ExternalName>,\n actions: LoadActions,\n pools: ReadonlyMap<PoolName, PoolMember[]>,\n packageOf: PackageOf,\n recordOrder: ExternalName[],\n scope: string\n ): Map<ExternalName, CopyMove> {\n const policy = { shareScope: scope, scopeUrlOf };\n const moves = new Map<ExternalName, CopyMove>();\n const selfServe = (members: PoolMember[], cause: PoolCause) => {\n for (const { name } of members) {\n actions[name]!.action = 'scope';\n delete actions[name]!.override;\n moves.set(name, { cause });\n }\n };\n\n for (const pool of pools.values()) {\n // Only the members this entry declares have an action to rewrite; the rest of the pool is context:\n // its committed tags are what the gate reads.\n const mine = pool.filter(member => names.has(member.name));\n if (mine.length === 0) continue;\n\n const shipped = copiesByRemote(pool);\n const view = committedView(pool, shipped, recordOrder, {\n shareScope: scope,\n without: remote,\n packageOf,\n });\n const own = shipped.get(remote) ?? [];\n const verdict = judgeRemote(own, view, accepts);\n if (verdict !== 'global') {\n config.log.warn(8, `[${scope}] ${selfServeWarning(remote, verdict, specifierCount(own))}`);\n selfServe(mine, verdict.cause);\n continue;\n }\n\n const cover = coverFromMap(remote, mine, view, actions, policy);\n if (!('covers' in cover)) {\n if ('unmapped' in cover) warnUnmapped(scope, remote, cover.unmapped);\n else\n config.log.warn(\n 8,\n `[${scope}] ${selfServeWarning(remote, coverMiss(cover), specifierCount(own))}`\n );\n // Half its family on the map's files and half on its own build would tear it.\n selfServe(mine, 'uncovered');\n continue;\n }\n for (const { name, toSkip, override } of cover.covers) {\n const action = actions[name]!;\n if (toSkip) {\n action.action = 'skip';\n moves.set(name, { fromMap: true });\n }\n if (Object.keys(override).length > 0) action.override = override;\n }\n }\n\n return moves;\n }\n\n // Writes the moves back so a reload rebuilds the map this delta publishes, not the one `update-cache`\n // recorded. The loaded remote's members are left dirty: the gate judged it against a map it could not\n // change, so the next init re-elects the scope with it, as a cold init of this record would.\n function writeMoves(\n remote: RemoteName,\n names: ReadonlySet<ExternalName>,\n moves: ReadonlyMap<ExternalName, CopyMove>,\n committed: shareScope,\n pools: ReadonlyMap<PoolName, PoolMember[]>,\n scope: string\n ): void {\n const written: Record<string, SharedExternal> = {};\n for (const [name, move] of moves)\n written[name] = movedRecord(committed[name]!, remote, move, ports.versionCheck.compare);\n for (const [name, record] of renamedRecords({ ...committed, ...written }, pools))\n written[name] = record;\n // A strict re-election throws on a pool the config refuses, so a strict page keeps the gate's verdicts.\n if (!config.strict.strictExternalCompatibility)\n for (const { name } of [...pools.values()].flat().filter(m => names.has(m.name)))\n written[name] = { ...(written[name] ?? committed[name]!), dirty: true };\n for (const [name, record] of Object.entries(written))\n ports.sharedExternalsRepo.addOrUpdate(name, record, scope);\n }\n\n function warnUnmapped(scope: string, remote: RemoteName, build: RemoteName): void {\n config.log.warn(\n 8,\n `[${scope}][${remote}] '${build}' is not in the cache, so its files cannot be mapped.`\n );\n }\n}\n\n// `covered` only carries a skip from the cache update into the gate.\nfunction publicActions(actions: LoadActions): SharedInfoActions {\n for (const action of Object.values(actions)) delete action.covered;\n return actions;\n}\n\nfunction poolableNames(entry: RemoteEntry, actions: LoadActions): Map<string, Set<ExternalName>> {\n const declared = new Map<string, Set<ExternalName>>();\n for (const external of entry.shared ?? []) {\n const name = external.packageName;\n if (!external.singleton || !actions[name]) continue;\n if (external.shareScope === STRICT_SCOPE) continue;\n\n const scope = external.shareScope ?? GLOBAL_SCOPE;\n let names = declared.get(scope);\n if (!names) declared.set(scope, (names = new Set()));\n names.add(name);\n }\n return declared;\n}\n\nfunction coverMiss(\n cover: Exclude<CoverResult, { covers: unknown } | { unmapped: unknown }>\n): GateMiss {\n if ('gap' in cover) return { cause: 'uncovered', specifier: cover.gap };\n return { cause: 'uncovered', ...cover.bound };\n}\n\n// Wording is pinned in `island-warnings.contract.spec.ts` alone; tools read islands from the record.\nfunction selfServeWarning(remote: RemoteName, miss: GateMiss, imports: number): string {\n const where = `All ${imports} of its entrypoints are scoped for it.`;\n if (miss.cause === 'incompatible')\n return `'${remote}' is islanded: its range rejects '${miss.specifier}@${miss.tag}' of the committed map. ${where}`;\n if ('owner' in miss)\n return `'${remote}' serves its own family: committed build '${miss.owner}', whose files it would reach, resolves '${miss.specifier}' to another file than it would. ${where}`;\n if ('unshipped' in miss)\n return `'${remote}' serves its own family: no committed build shipped the map's combination for it. ${where}`;\n return `'${remote}' serves its own family: no committed build offers every entrypoint it imports at a version it accepts (gap '${miss.specifier}'). ${where}`;\n}\n", "import type { ImportMap } from 'lib/core/1.domain/import-map/import-map.contract';\nimport { type RemoteEntry, type SharedInfoActions } from 'lib/core/1.domain';\nimport type { LoggingConfig } from '../config/log.contract';\nimport type { ModeConfig } from '../config/mode.contract';\nimport * as _path from 'lib/utils/path';\nimport type { ForConvertingToImportMap } from 'lib/core/2.app/driver-ports/init/for-converting-to-import-map';\nimport type { DrivingContract } from 'lib/core/2.app/driving-ports/driving.contract';\nimport { NFError } from 'lib/core/native-federation.error';\nimport { toChunkImport } from '@softarc/native-federation/domain';\n\nexport function createConvertToImportMap(\n config: LoggingConfig & ModeConfig,\n ports: Pick<DrivingContract, 'sharedChunksRepo'>\n): ForConvertingToImportMap {\n const { log } = config;\n return async ({ entry, actions }) => {\n const importMap: ImportMap = { imports: {} };\n\n addExternals(entry, actions, importMap);\n addRemoteInfos(entry, importMap);\n log.debug(9, `[${entry.name}] Processed actions:`, actions);\n return importMap;\n };\n\n function addExternals(\n remoteEntry: RemoteEntry,\n actions: SharedInfoActions,\n importMap: ImportMap\n ): void {\n if (!remoteEntry.shared) {\n return;\n }\n\n const remoteEntryScope = _path.getScope(remoteEntry.url);\n const integrityMap = remoteEntry.integrity;\n\n const chunkBundles = new Set<string>(['mapping-or-exposed']);\n remoteEntry.shared.forEach(external => {\n // Scoped externals\n if (!external.singleton) {\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n\n if (external?.bundle) chunkBundles.add(external?.bundle);\n return;\n }\n\n if (!actions[external.packageName]) {\n log.warn(\n 9,\n `[${remoteEntry.name}] No action defined for shared external '${external.packageName}', skipping.`\n );\n return;\n }\n\n // Skipped externals are provided by another remote. An override \u2014 from a shareScope skip, or from\n // pooling having placed this remote in a committed build's subpool \u2014 names whose files, per\n // consumer. A global skip without one inherits the committed global mapping and needs no entry of\n // its own.\n if (actions[external.packageName]!.action === 'skip') {\n const { override } = actions[external.packageName]!;\n if (override) {\n Object.entries(override).forEach(([packageName, url]) => {\n addToScopes(remoteEntryScope, packageName, url, importMap);\n });\n return;\n }\n if (!external.shareScope) return;\n // Reaching here means the resolver failed to produce the expected override.\n log.error(\n 9,\n `[${remoteEntry.name}][${external.packageName}] shareScope skip has no override.`\n );\n if (config.strict.strictImportMap) throw new NFError('Could not create ImportMap.');\n // Non-strict fallback: serve from the remote's own scope (matches init).\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n return;\n }\n\n // Chunks for shared externals\n if (external?.bundle) chunkBundles.add(external?.bundle);\n\n // Scoped shared externals\n if (actions[external.packageName]!.action === 'scope') {\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n return;\n }\n\n // Shared externals with shareScope\n if (external.shareScope) {\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n addToScopes(remoteEntryScope, packageName, url, importMap);\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n return;\n }\n\n // Default case: shared globally\n Object.entries(external.entries).forEach(([packageName, fileName]) => {\n const url = _path.join(remoteEntryScope, fileName);\n importMap.imports[packageName] = url;\n\n addIntegrity(importMap, url, integrityMap, fileName);\n });\n });\n\n addChunkImports(importMap, remoteEntry, remoteEntryScope, chunkBundles);\n }\n\n function addToScopes(\n scope: string,\n packageName: string,\n url: string,\n importMap: ImportMap\n ): void {\n if (!importMap.scopes) importMap.scopes = {};\n if (!importMap.scopes[scope]) importMap.scopes[scope] = {};\n importMap.scopes[scope][packageName] = url;\n }\n\n function addRemoteInfos(remoteEntry: RemoteEntry, importMap: ImportMap): void {\n if (!remoteEntry.exposes) return;\n const scope = _path.getScope(remoteEntry.url);\n\n remoteEntry.exposes.forEach(exposed => {\n const moduleName = _path.join(remoteEntry.name, exposed.key);\n const moduleUrl = _path.join(scope, exposed.outFileName);\n importMap.imports[moduleName] = moduleUrl;\n addIntegrity(importMap, moduleUrl, remoteEntry.integrity, exposed.outFileName);\n });\n }\n\n function addChunkImports(\n importMap: ImportMap,\n remoteEntry: RemoteEntry,\n remoteEntryScope: string,\n chunkBundles: Set<string>\n ) {\n Array.from(chunkBundles).forEach(bundleName => {\n ports.sharedChunksRepo.tryGet(remoteEntry.name, bundleName).ifPresent(files => {\n files.forEach(file => {\n const url = _path.join(remoteEntryScope, file);\n addToScopes(remoteEntryScope, toChunkImport(file), url, importMap);\n addIntegrity(importMap, url, remoteEntry.integrity, file);\n });\n });\n });\n return importMap;\n }\n\n function addIntegrity(\n importMap: ImportMap,\n url: string,\n integrityMap: Record<string, string> | undefined,\n file: string\n ): void {\n const hash = integrityMap?.[file];\n if (!hash) return;\n if (!importMap.integrity) importMap.integrity = {};\n importMap.integrity[url] = hash;\n }\n}\n", "import type { FLOW_FACTORY } from 'lib/core/2.app/driver-ports/flow-factory.contract';\nimport type { InitDriversContract } from 'lib/core/2.app/driver-ports/init/drivers.contract';\nimport { createGetRemoteEntries } from '../2.app/steps/get-remote-entries';\nimport { createProcessRemoteEntries } from '../2.app/steps/process-remote-entries';\nimport { createDetermineSharedExternals } from '../2.app/steps/determine-shared-externals';\nimport { createPoolSharedExternals } from '../2.app/steps/pooling/pool-shared-externals';\nimport { createDecideServingBuilds } from '../2.app/steps/decide-serving-builds';\nimport { createGenerateImportMap } from '../2.app/steps/generate-import-map';\nimport { createCommitChanges } from '../2.app/steps/commit-changes';\nimport { createRollbackChanges } from '../2.app/steps/rollback-changes';\nimport { createExposeModuleLoader } from '../2.app/steps/expose-module-loader';\nimport { createGetRemoteEntry } from '../2.app/steps/get-remote-entry';\nimport { createUpdateCache } from '../2.app/steps/update-cache';\nimport { createPoolDynamicExternals } from '../2.app/steps/pooling/pool-dynamic-externals';\nimport { createConvertToImportMap } from '../2.app/steps/convert-to-import-map';\nimport type { DrivingContract } from '../2.app/driving-ports/driving.contract';\nimport type { ConfigContract } from '../2.app/config/config.contract';\n\nexport const createInitDrivers = ({\n config,\n adapters,\n}: {\n config: ConfigContract;\n adapters: DrivingContract;\n}): InitDriversContract => ({\n getRemoteEntries: createGetRemoteEntries(config, adapters),\n processRemoteEntries: createProcessRemoteEntries(config, adapters),\n determineSharedExternals: createDetermineSharedExternals(config, adapters),\n poolSharedExternals: createPoolSharedExternals(config, adapters),\n decideServingBuilds: createDecideServingBuilds(config, adapters),\n generateImportMap: createGenerateImportMap(config, adapters),\n commitChanges: createCommitChanges(config, adapters),\n rollbackChanges: createRollbackChanges(config, adapters),\n exposeModuleLoader: createExposeModuleLoader(config, adapters),\n getRemoteEntry: createGetRemoteEntry(config, adapters),\n updateCache: createUpdateCache(config, adapters),\n poolDynamicExternals: createPoolDynamicExternals(config, adapters),\n convertToImportMap: createConvertToImportMap(config, adapters),\n});\n\nexport const INIT_FLOW_FACTORY = ({\n config,\n adapters,\n}: {\n config: ConfigContract;\n adapters: DrivingContract;\n}): FLOW_FACTORY<InitDriversContract> => {\n const flow = createInitDrivers({ config, adapters });\n\n return {\n flow,\n adapters,\n config,\n };\n};\n", "import type { ConfigContract } from '../2.app/config/config.contract';\nimport type { DrivingContract } from '../2.app/driving-ports/driving.contract';\nimport type { InitRemoteEntryFlow, RemoteRef } from '../2.app/driver-ports/init/flow.contract';\nimport type {\n LoadRemoteModule,\n LoadRemoteModuleOf,\n NativeFederationResult,\n PreloadRemoteModule,\n} from '../init-federation.contract';\n\nexport { createStateDump } from '../2.app/steps/rollback-changes';\n\nexport const createFederationResult = ({\n config,\n adapters,\n loadRemoteModule,\n // A host composing init by hand may not pass it.\n preloadRemoteModule = () => {},\n initRemoteEntryFlow,\n afterInitRemoteEntry,\n}: {\n config: ConfigContract;\n adapters: DrivingContract;\n loadRemoteModule: LoadRemoteModule;\n preloadRemoteModule?: PreloadRemoteModule;\n initRemoteEntryFlow: InitRemoteEntryFlow;\n afterInitRemoteEntry?: () => Promise<unknown>;\n}): NativeFederationResult => {\n const initRemoteEntry = async (\n remoteEntryUrl: string,\n remote?: RemoteRef\n ): Promise<NativeFederationResult> => {\n return initRemoteEntryFlow(remoteEntryUrl, remote)\n .catch(e => {\n if (config.strict.strictRemoteEntry) return Promise.reject(e);\n else console.warn('Failed to initialize remote entry, continuing anyway.');\n return Promise.resolve();\n })\n .then(() => afterInitRemoteEntry?.())\n .then(() => result);\n };\n\n const result: NativeFederationResult = {\n config,\n adapters,\n loadRemoteModule,\n load: loadRemoteModule,\n preloadRemoteModule,\n as: <TModule = unknown>() => ({\n loadRemoteModule: loadRemoteModule as LoadRemoteModuleOf<TModule>,\n load: loadRemoteModule as LoadRemoteModuleOf<TModule>,\n }),\n initRemoteEntry,\n };\n\n return result;\n};\n", "import { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\nimport type { ImportMap } from 'lib/core/1.domain';\nimport { getLoaderUrl } from './loader-url';\n\n/** Per-specifier list of export names to bridge from the host's instances. */\nexport type HostInstanceKeys = Record<string, string[]>;\n\ntype IncomingMessage = { type: 'import-map-applied' } | { type: 'host-instances-applied' };\ntype OutgoingMessage =\n | { type: 'set-import-map'; map: ImportMap }\n | { type: 'set-host-instances'; keys: HostInstanceKeys };\n\nexport type NodeLoaderClient = {\n setMap: (map: ImportMap) => Promise<void>;\n setHostInstances: (keys: HostInstanceKeys) => Promise<void>;\n ready: () => Promise<void>;\n};\n\nexport const NODE_LOADER_CLIENT_ACK_TIMEOUT_MS = 10_000;\n\nlet cached: NodeLoaderClient | null = null;\n\nconst createClient = (): NodeLoaderClient => {\n const { port1, port2 } = new MessageChannel();\n register(getLoaderUrl(), {\n data: { port: port2 },\n transferList: [port2],\n });\n\n // Don't let the client keep the process alive on its own.\n port1.unref();\n\n let pending: Promise<void> = Promise.resolve();\n\n // Specifiers bridged to host instances. The loader resolves these ahead of\n // the import map, so we strip them from the map we post \u2014 no dead entries.\n const bridged = new Set<string>();\n const omitBridged = (map: ImportMap): ImportMap => {\n if (bridged.size === 0) return map;\n const drop = (imports: ImportMap['imports']): ImportMap['imports'] =>\n Object.fromEntries(Object.entries(imports).filter(([specifier]) => !bridged.has(specifier)));\n const scopes = map.scopes\n ? Object.fromEntries(\n Object.entries(map.scopes).map(([scope, imports]) => [scope, drop(imports)])\n )\n : map.scopes;\n return { ...map, imports: drop(map.imports), ...(scopes ? { scopes } : {}) };\n };\n\n const postAndAwaitAck = (\n message: OutgoingMessage,\n ackType: IncomingMessage['type']\n ): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n const cleanup = (): void => {\n port1.off('message', onMessage);\n if (timer !== null) clearTimeout(timer);\n };\n const onMessage = (msg: IncomingMessage): void => {\n if (msg?.type === ackType) {\n cleanup();\n resolve();\n }\n };\n port1.on('message', onMessage);\n timer = setTimeout(() => {\n cleanup();\n reject(\n new Error(\n `node-loader.client: loader did not acknowledge ${message.type} within ${NODE_LOADER_CLIENT_ACK_TIMEOUT_MS}ms`\n )\n );\n }, NODE_LOADER_CLIENT_ACK_TIMEOUT_MS);\n (timer as { unref?: () => void }).unref?.();\n try {\n port1.postMessage(message);\n } catch (err) {\n cleanup();\n reject(err);\n }\n });\n\n // Serialize every post on a single chain so set-import-map and\n // set-host-instances can never race each other on the loader thread.\n const enqueue = (message: OutgoingMessage, ackType: IncomingMessage['type']): Promise<void> => {\n const next = pending.catch(() => undefined).then(() => postAndAwaitAck(message, ackType));\n pending = next;\n return next;\n };\n\n const setMap = (map: ImportMap): Promise<void> =>\n enqueue({ type: 'set-import-map', map: omitBridged(map) }, 'import-map-applied');\n\n const setHostInstances = (keys: HostInstanceKeys): Promise<void> => {\n Object.keys(keys).forEach(specifier => bridged.add(specifier));\n return enqueue({ type: 'set-host-instances', keys }, 'host-instances-applied');\n };\n\n return {\n setMap,\n setHostInstances,\n ready: () => pending,\n };\n};\n\nexport const getNodeLoaderClient = (): NodeLoaderClient => {\n if (!cached) cached = createClient();\n return cached;\n};\n\n/** Only used by tests. */\nexport const _resetNodeLoaderClient = (): void => {\n cached = null;\n};\n", "import { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport { NFError } from 'lib/core/native-federation.error';\n\n/**\n * Resolves the bundled Node loader (`dist/node-loader/loader.mjs`) via the\n * package's own `exports` map. Self-resolving by name (rather than a relative\n * URL from `import.meta.url`) keeps this working under bundlers, pnpm, Yarn\n * PnP, and monorepo symlinks where the on-disk layout of the installed package\n * is not predictable.\n */\nexport const getLoaderUrl = () => {\n try {\n const require = createRequire(import.meta.url);\n return pathToFileURL(\n require.resolve('@softarc/native-federation-orchestrator/node-loader/loader.mjs')\n );\n } catch (err) {\n const cause = err instanceof Error ? err : new Error(String(err));\n throw new NFError(\n `Could not locate the bundled node-loader at '@softarc/native-federation-orchestrator/node-loader/loader.mjs'. Ensure it is installed, and that its 'exports' map exposes this subpath: ${cause.message}`,\n cause\n );\n }\n};\n", "import type { ImportMap } from 'lib/core/1.domain';\nimport type { ImportMapConfig } from 'lib/core/2.app/config/import-map.contract';\nimport { noPreload } from 'lib/core/4.config/import-map/no-preload';\nimport {\n getNodeLoaderClient,\n type NodeLoaderClient,\n type HostInstanceKeys,\n} from 'lib/node/adapters/node-loader.client';\n\ntype NodeImportMapConfig = ImportMapConfig & {\n nodeLoader: NodeLoaderClient;\n setHostInstancesFn: (keys: HostInstanceKeys) => Promise<HostInstanceKeys>;\n};\n\nconst useNodeImportMap = (): NodeImportMapConfig => {\n const nodeLoader = getNodeLoaderClient();\n return {\n nodeLoader,\n loadModuleFn: (url: string) => import(/* @vite-ignore */ url),\n setImportMapFn: (importMap: ImportMap) => nodeLoader.setMap(importMap).then(() => importMap),\n setHostInstancesFn: (keys: HostInstanceKeys) =>\n nodeLoader.setHostInstances(keys).then(() => keys),\n reloadBrowserFn: () => {\n /* no-op */\n },\n // import() would evaluate the module, and the loader thread reads a module only once it is imported.\n preloadModulesFn: noPreload,\n };\n};\n\nexport { useNodeImportMap };\n", "import type { HostOptions } from 'lib/core/2.app/config/host.contract';\nimport type { LogHandler } from 'lib/core/2.app/config/log.contract';\nimport type { ForProvidingRemoteEntries } from 'lib/core/2.app/driving-ports/for-providing-remote-entries.port';\n\n/** Specifier \u2192 module namespace object to bridge into remotes (the host's own instances). */\nexport type HostInstanceMap = Record<string, object>;\n\n/**\n * Auto-derive the bridged specifiers from the host remoteEntry's shared\n * singletons instead of listing them by hand. Each derived specifier is loaded\n * in the host realm (so the captured instance is the host's) and published.\n */\nexport type HostInstancesAuto = {\n /** Only bridge specifiers matching one of these (exact or prefix, e.g. `'@angular/'`). */\n include?: string[];\n /** Never bridge specifiers matching one of these (exact or prefix). */\n exclude?: string[];\n /**\n * How to load each instance. Default: `(s) => import(s)`.\n *\n * The default resolves wherever this library runs. Under a bundler-driven dev\n * server (e.g. Vite SSR) that may NOT be the realm holding the host's running\n * instance \u2014 pass a `load` defined in your own host entry so the import\n * resolves through the host's module graph and captures the real instance.\n */\n load?: (specifier: string) => Promise<object>;\n};\n\nexport type HostInstancesOption =\n /** Explicit map of specifier \u2192 already-loaded namespace. */\n | HostInstanceMap\n /** Auto-derive every shared singleton from the host remoteEntry. */\n | 'all'\n /** Auto-derive, filtered. */\n | HostInstancesAuto;\n\ntype Deps = {\n remoteEntryProvider: ForProvidingRemoteEntries;\n hostRemoteEntry: HostOptions['hostRemoteEntry'];\n log: LogHandler;\n};\n\n/** A pattern matches a specifier on exact equality or as a prefix. */\nconst matches = (specifier: string, patterns: string[]): boolean =>\n patterns.some(p => specifier === p || specifier.startsWith(p));\n\n/** Distinguish the auto forms (`'all'` / filter object) from an explicit map. */\nconst isAuto = (option: HostInstancesOption): option is 'all' | HostInstancesAuto =>\n option === 'all' ||\n (typeof option === 'object' &&\n option !== null &&\n ('include' in option || 'exclude' in option || 'load' in option));\n\n/**\n * Turn the `hostInstances` option into a concrete `{ specifier: namespace }` map.\n *\n * - Explicit map \u2192 returned as-is.\n * - `'all'` / `{ include, exclude }` \u2192 read the host remoteEntry's shared\n * singletons, apply the filter, and import each in the host realm.\n *\n * A specifier that fails to load is skipped with a warning rather than aborting\n * init \u2014 the remote falls back to import-map resolution for it (which is the\n * pre-bridge behaviour).\n */\nexport const resolveHostInstances = async (\n option: HostInstancesOption | undefined,\n deps: Deps\n): Promise<HostInstanceMap | undefined> => {\n if (!option) return undefined;\n if (!isAuto(option)) return option;\n\n const auto: HostInstancesAuto = option === 'all' ? {} : option;\n\n const { hostRemoteEntry } = deps;\n if (!hostRemoteEntry) {\n deps.log.warn(\n 0,\n '[native-federation] hostInstances auto mode needs a hostRemoteEntry to derive shared singletons from; skipping.'\n );\n return undefined;\n }\n\n const url = typeof hostRemoteEntry === 'string' ? hostRemoteEntry : hostRemoteEntry.url;\n const integrity = typeof hostRemoteEntry === 'string' ? undefined : hostRemoteEntry.integrity;\n const entry = await deps.remoteEntryProvider.provide(url, { integrity });\n\n const load = auto.load ?? ((specifier: string) => import(specifier));\n\n const specifiers = [\n ...new Set(\n (entry.shared ?? []).filter(s => s.singleton).flatMap(s => Object.keys(s.entries))\n ),\n ]\n .filter(s => (auto.include ? matches(s, auto.include) : true))\n .filter(s => (auto.exclude ? !matches(s, auto.exclude) : true));\n\n const map: HostInstanceMap = {};\n for (const specifier of specifiers) {\n try {\n map[specifier] = (await load(specifier)) as object;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n deps.log.warn(\n 0,\n `[native-federation] hostInstances: could not load '${specifier}' from the host realm; skipping (${msg})`\n );\n }\n }\n\n deps.log.debug(\n 0,\n `[native-federation] hostInstances bridged: ${Object.keys(map).join(', ') || '(none)'}`\n );\n return map;\n};\n", "import { pathToFileURL } from 'node:url';\nimport type { HostOptions } from 'lib/core/2.app/config/host.contract';\n\n/**\n * Coerce a Node-side string into a URL string. Anything that already starts\n * with a scheme (`http:`, `https:`, `file:`, `node:`, \u2026) passes through; a bare\n * filesystem path is converted to a `file://` URL via `pathToFileURL`.\n */\nconst URL_SCHEME = /^[a-z][a-z0-9+\\-.]*:/i;\n\nexport const toUrl = (pathOrUrl: string): string =>\n URL_SCHEME.test(pathOrUrl) ? pathOrUrl : pathToFileURL(pathOrUrl).href;\n\nexport const normalizeHostRemoteEntry = (\n hostRemoteEntry: HostOptions['hostRemoteEntry']\n): HostOptions['hostRemoteEntry'] => {\n if (!hostRemoteEntry) return hostRemoteEntry;\n if (typeof hostRemoteEntry === 'string') return toUrl(hostRemoteEntry);\n return { ...hostRemoteEntry, url: toUrl(hostRemoteEntry.url) };\n};\n", "import type { FederationManifest } from 'lib/core/1.domain';\nimport type { NFOptions, ConfigContract } from 'lib/core/2.app/config/config.contract';\nimport type { DrivingContract } from 'lib/core/2.app/driving-ports/driving.contract';\nimport type { NativeFederationResult } from 'lib/core/init-federation.contract';\n\nimport { createBrowser } from 'lib/core/3.adapters/browser/browser';\nimport { createVersionCheck } from 'lib/core/3.adapters/checks/version.check';\nimport { createFsManifestProvider } from './adapters/fs-manifest-provider';\nimport { createFsRemoteEntryProvider } from './adapters/fs-remote-entry-provider';\nimport { createNoopSSE } from './adapters/noop-sse';\nimport { createRemoteInfoRepository } from 'lib/core/3.adapters/storage/remote-info.repository';\nimport { createScopedExternalsRepository } from 'lib/core/3.adapters/storage/scoped-externals.repository';\nimport { createSharedExternalsRepository } from 'lib/core/3.adapters/storage/shared-externals.repository';\nimport { createChunkRepository } from 'lib/core/3.adapters/storage/chunk.repository';\n\nimport { createConfigHandlers } from 'lib/core/5.di/config.factory';\nimport { createInitFlow } from 'lib/core/2.app/flows/init.flow';\nimport { createInitRemoteEntryFlow } from 'lib/core/2.app/flows/init-remote-entry.flow';\nimport { INIT_FLOW_FACTORY } from 'lib/core/5.di/init.factory';\nimport {\n createFederationResult,\n createStateDump,\n} from 'lib/core/5.di/federation-result.factory';\nimport { useNodeImportMap } from './use-node';\nimport { resolveHostInstances, type HostInstancesOption } from './resolve-host-instances';\nimport { normalizeHostRemoteEntry } from './utils/to-url';\n\nexport type { HostInstancesOption, HostInstancesAuto } from './resolve-host-instances';\n\nexport type InitNodeFederationOptions = NFOptions & {\n /**\n * Bridge specifiers to instances already loaded in the host process (dev).\n *\n * The host's instances are published on `globalThis.__NF_HOST_INSTANCES__`\n * and the node loader synthesizes a re-export module for each specifier\n * instead of resolving it through the import map, so remotes share the host's\n * singletons. Three forms:\n *\n * - **Explicit map** \u2014 `{ '@angular/core': await import('@angular/core') }`.\n * - **`'all'`** \u2014 auto-derive every shared singleton from the host remoteEntry\n * and import each in the host realm. Needs `hostRemoteEntry`.\n * - **`{ include, exclude }`** \u2014 auto-derive, filtered by exact/prefix match,\n * e.g. `{ include: ['@angular/', 'rxjs', 'zone.js'] }`.\n *\n * Bypasses the version resolver, the import map and integrity checks. Exports are value snapshots, not\n * live bindings, so not for packages that reassign their exports after init. Omit in production.\n */\n hostInstances?: HostInstancesOption;\n};\n\nconst HOST_INSTANCES_GLOBAL = '__NF_HOST_INSTANCES__';\n\nconst buildNodeAdapters = (config: ConfigContract): DrivingContract => ({\n versionCheck: createVersionCheck(),\n manifestProvider: createFsManifestProvider(),\n remoteEntryProvider: createFsRemoteEntryProvider(config),\n remoteInfoRepo: createRemoteInfoRepository(config),\n scopedExternalsRepo: createScopedExternalsRepository(config),\n sharedExternalsRepo: createSharedExternalsRepository(config),\n sharedChunksRepo: createChunkRepository(config),\n browser: createBrowser(config),\n sse: createNoopSSE(),\n});\n\nconst initNodeFederation = (\n remotesOrManifestUrl: string | FederationManifest,\n options: InitNodeFederationOptions = {}\n): Promise<NativeFederationResult> => {\n const nodeConfig = useNodeImportMap();\n\n const hostRemoteEntry = normalizeHostRemoteEntry(options.hostRemoteEntry);\n\n const config = createConfigHandlers({\n ...options,\n hostRemoteEntry,\n loadModuleFn: options.loadModuleFn ?? nodeConfig.loadModuleFn,\n setImportMapFn: options.setImportMapFn ?? nodeConfig.setImportMapFn,\n reloadBrowserFn: options.reloadBrowserFn ?? nodeConfig.reloadBrowserFn,\n preloadModulesFn: options.preloadModulesFn ?? nodeConfig.preloadModulesFn,\n sse: false,\n });\n\n const adapters = buildNodeAdapters(config);\n\n const hostInstancesReady = (async () => {\n const instances = await resolveHostInstances(options.hostInstances, {\n remoteEntryProvider: adapters.remoteEntryProvider,\n hostRemoteEntry,\n log: config.log,\n });\n if (!instances || Object.keys(instances).length === 0) return;\n\n const globals = globalThis as Record<string, unknown>;\n globals[HOST_INSTANCES_GLOBAL] = {\n ...((globals[HOST_INSTANCES_GLOBAL] as Record<string, object> | undefined) ?? {}),\n ...instances,\n };\n const keys = Object.fromEntries(\n Object.entries(instances).map(([specifier, ns]) => [specifier, Object.keys(ns)])\n );\n await nodeConfig.setHostInstancesFn(keys);\n })();\n\n const factory = INIT_FLOW_FACTORY({ adapters, config });\n const initFlow = createInitFlow(factory);\n const initRemoteEntryFlow = createInitRemoteEntryFlow(factory);\n\n return hostInstancesReady\n .then(() => initFlow(remotesOrManifestUrl))\n .then(access => nodeConfig.nodeLoader.ready().then(() => access))\n .then(access =>\n createFederationResult({\n config,\n adapters,\n ...access,\n initRemoteEntryFlow,\n afterInitRemoteEntry: () => nodeConfig.nodeLoader.ready(),\n })\n )\n .catch(e => {\n createStateDump(config, adapters)(`[init] STATE DUMP`);\n return Promise.reject(e);\n });\n};\n\nexport { initNodeFederation };\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,QACJ,OAAO,YAAY,YACnB,QAAQ,OACR,QAAQ,IAAI,cACZ,cAAc,KAAK,QAAQ,IAAI,UAAU,IACvC,IAAI,SAAS,QAAQ,MAAM,UAAU,GAAG,IAAI,IAC5C,MAAM;AAAA,IAAC;AAEX,WAAO,UAAU;AAAA;AAAA;;;ACVjB;AAAA;AAAA;AAIA,QAAM,sBAAsB;AAE5B,QAAM,aAAa;AACnB,QAAM,mBAAmB,OAAO;AAAA,IACL;AAG3B,QAAM,4BAA4B;AAIlC,QAAM,wBAAwB,aAAa;AAG3C,QAAM,wBAAwB;AAAA,MAC5B;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,QAAM,gBAAgB;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,WAAO,UAAU;AAAA,MACf;A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CAAC,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,OAAO,KAAK,EAAE,CAAC,CAAC;AAAA,IACjF;AACA,UAAM,WAAW,mBAAmB,IAAI;AAAA,EAC1C,GAAG;AAEH,QAAM,UAAU,kBAAkB,EAAE,UAAU,OAAO,CAAC;AACtD,QAAM,WAAW,eAAe,OAAO;AACvC,QAAM,sBAAsB,0BAA0B,OAAO;AAE7D,SAAO,mBACJ,KAAK,MAAM,SAAS,oBAAoB,CAAC,EACzC,KAAK,YAAU,WAAW,WAAW,MAAM,EAAE,KAAK,MAAM,MAAM,CAAC,EAC/D;AAAA,IAAK,YACJ,uBAAuB;AAAA,MACrB;AAAA,MACA;AAAA,MACA,GAAG;AAAA,MACH;AAAA,MACA,sBAAsB,MAAM,WAAW,WAAW,MAAM;AAAA,IAC1D,CAAC;AAAA,EACH,EACC,MAAM,OAAK;AACV,oBAAgB,QAAQ,QAAQ,EAAE,mBAAmB;AACrD,WAAO,QAAQ,OAAO,CAAC;AAAA,EACzB,CAAC;AACL;",
6
+ "names": ["SemVer", "SemVer", "SemVer", "SemVer", "cached", "SemVer", "SemVer", "require_valid", "import_valid", "SemVer", "semverValid", "semverSatisfies", "semverValidRange", "semverMinVersion", "importMap", "cached", "missOf", "rank", "byTag", "toll", "getScope", "cached", "runsOffMap", "rank", "require", "pathToFileURL"]
7
7
  }