Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

21
node_modules/@module-federation/enhanced/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 ScriptedAlchemy LLC (Zack Jackson) Zhou Shaw (zhouxiao)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

213
node_modules/@module-federation/enhanced/README.md generated vendored Normal file
View File

@@ -0,0 +1,213 @@
# `@module-federation/enhanced`
This package provides enhanced features for module federation.
The following items are exported:
- ModuleFederationPlugin
- ContainerPlugin
- ContainerReferencePlugin
- SharePlugin
- ConsumeSharedPlugin
- ProvideSharedPlugin
- FederationRuntimePlugin
- AsyncBoundaryPlugin
- HoistContainerReferencesPlugin
## Documentation
See [https://module-federation.io/guide/build-plugins/plugins.html](https://module-federation.io/guide/build-plugins/plugins.html) for details.
## ModuleFederationPlugin
### Configuration
### name
- Type: `string`
- Required: No
The name of the container.
### exposes
- Type: `Exposes`
- Required: No
- Default: `undefined`
Used to specify the modules and file entry points that are exposed via Module Federation. After configuration, the exposed modules will be extracted into a separate chunk, and if there are async chunks, they will also be extracted into a separate chunk (the specific splitting behavior depends on the chunk splitting rules).
The `Exposes` type is defined as follows:
```tsx
type Exposes = (ExposesItem | ExposesObject)[] | ExposesObject;
type ExposesItem = string;
type ExposesItems = ExposesItem[];
interface ExposesObject {
[exposeKey: string]: ExposesConfig | ExposesItem | ExposesItems;
}
```
Here, `exposeKey` is essentially the same as the [Package Entry Points](https://nodejs.org/api/packages.html#package-entry-points) specification (except that regular expression matching is not supported).
For example:
```jsx
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'mfButton',
exposes: {
// Note: "./" is not supported
'.': './src/index.tsx',
'./add': './src/utils/add.ts',
'./Button': './src/components/Button.tsx',
},
}),
],
};
```
### remotes
> This is a consumer-specific parameter. If remotes is set, it can be considered as a consumer.
- Type: `Remotes`
- Required: No
- Default: `undefined`
This is used to specify how Module Federation consumes remote modules.
The `Remotes` type is defined as follows:
```tsx
type Remotes = (RemotesItem | RemotesObject)[] | RemotesObject;
type RemotesItem = string;
type RemotesItems = RemotesItem[];
interface RemotesObject {
[remoteAlias: string]: RemotesConfig | RemotesItem | RemotesItems;
}
```
Here, `remoteAlias` is the name actually used by the user and can be configured arbitrarily. For example, if `remoteAlias` is set to `demo`, the consumption method is `import xx from 'demo'`.
### shared
- Type: `Shared`
- Required: No
- Default: `undefined`
`shared` is used to share common dependencies between consumers and producers, reducing runtime download size and thus improving performance.
The `Shared` type is defined as follows:
```tsx
type Shared = (SharedItem | SharedObject)[] | SharedObject;
type SharedItem = string;
interface SharedObject {
[k: string]: SharedConfig | SharedItem;
}
```
#### singleton
- Type: `boolean`
- Required: No
- Default: `false`
Determines whether only one version of the shared module is allowed in the shared scope (singleton mode).
- If the value is true, singleton mode is enabled; if the value is false, singleton mode is not enabled.
- If singleton mode is enabled, the shared dependencies of the remote application components and host application are loaded only once, and a higher version is loaded when the versions are not consistent. At this time, a warning will be given to the lower version side:
- If singleton mode is not enabled, if the versions of shared dependencies between the remote application and host application are not consistent, the remote application and host application load their own dependencies
#### requiredVersion
- Type: `string`
- Required: False
- Default: `require('project/package.json')[devDeps | dep]['depName']`
The required version can be a version range. The default value is the dependency version of the current application.
- When using shared dependencies, it will be judged whether the dependency version meets requiredVersion. If it does, it will be used normally. If it is less than requiredVersion, a warning will be issued in the console, and the smallest version in the current shared dependency will be used.
- When one side sets requiredVersion and the other side sets singleton, the dependency of requiredVersion will be loaded, and the singleton side will directly use the dependency of requiredVersion, regardless of the version.
#### eager
:::warning
When `eager` is set to true, the shared dependencies will be packaged into the entry file, which will cause the entry file to be too large. Please open with caution.
`eager: true` is rarely recommended
:::
- Type: `boolean`
- Required: False
- Default: `false`
Determines whether to load shared modules immediately.
Under normal circumstances, you need to open the asynchronous entry, and then load shared asynchronously on demand. If you want to use shared but don't want to enable asynchronous entry, you can set `eager` to true .
### runtimePlugins
- Type: `string[] | Array<[string, Record<string, unknown>]>`
- Required: False
- Default: `undefined`
Used to add additional plug-ins required at runtime. The value is the path of the specific plug-in. It supports absolute/relative paths and package names.
Once set, the runtime plugin is automatically injected and used at build time.
### implementation
- Type: `string`
- Required: False
- Default: `undefined`
Used to modify the actual bundler runtime version. Path with value `@module-federation/runtime-tools`.
## CLI
To view all available CLI commands, run the following command in the project directory:
```bash
npx mf -h
```
The output is shown below:
```bash
Usage: mf <command> [options]
Options:
-V, --version output the version number
-h, --help display help for command
Commands:
dts [options] generate or fetch the mf types
help [command] display help for command
```
### mf dts
The mf dts command is used to generate or fetch remote types.
```bash
Usage: mf dts [options]
generate or fetch the mf types
Options:
--root <root> specify the project root directory
--output <output> specify the generated dts output directory
--fetch <boolean> fetch types from remote, default is true (default: true)
--generate <boolean> generate types, default is true (default: true)
-c --config <config> specify the configuration file, can be a relative or absolute path
-h, --help display help for command
```

4
node_modules/@module-federation/enhanced/bin/mf.js generated vendored Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env node
const { runCli } = require('@module-federation/cli');
runCli();

File diff suppressed because it is too large Load Diff

213
node_modules/@module-federation/enhanced/dist/README.md generated vendored Normal file
View File

@@ -0,0 +1,213 @@
# `@module-federation/enhanced`
This package provides enhanced features for module federation.
The following items are exported:
- ModuleFederationPlugin
- ContainerPlugin
- ContainerReferencePlugin
- SharePlugin
- ConsumeSharedPlugin
- ProvideSharedPlugin
- FederationRuntimePlugin
- AsyncBoundaryPlugin
- HoistContainerReferencesPlugin
## Documentation
See [https://module-federation.io/guide/build-plugins/plugins.html](https://module-federation.io/guide/build-plugins/plugins.html) for details.
## ModuleFederationPlugin
### Configuration
### name
- Type: `string`
- Required: No
The name of the container.
### exposes
- Type: `Exposes`
- Required: No
- Default: `undefined`
Used to specify the modules and file entry points that are exposed via Module Federation. After configuration, the exposed modules will be extracted into a separate chunk, and if there are async chunks, they will also be extracted into a separate chunk (the specific splitting behavior depends on the chunk splitting rules).
The `Exposes` type is defined as follows:
```tsx
type Exposes = (ExposesItem | ExposesObject)[] | ExposesObject;
type ExposesItem = string;
type ExposesItems = ExposesItem[];
interface ExposesObject {
[exposeKey: string]: ExposesConfig | ExposesItem | ExposesItems;
}
```
Here, `exposeKey` is essentially the same as the [Package Entry Points](https://nodejs.org/api/packages.html#package-entry-points) specification (except that regular expression matching is not supported).
For example:
```jsx
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'mfButton',
exposes: {
// Note: "./" is not supported
'.': './src/index.tsx',
'./add': './src/utils/add.ts',
'./Button': './src/components/Button.tsx',
},
}),
],
};
```
### remotes
> This is a consumer-specific parameter. If remotes is set, it can be considered as a consumer.
- Type: `Remotes`
- Required: No
- Default: `undefined`
This is used to specify how Module Federation consumes remote modules.
The `Remotes` type is defined as follows:
```tsx
type Remotes = (RemotesItem | RemotesObject)[] | RemotesObject;
type RemotesItem = string;
type RemotesItems = RemotesItem[];
interface RemotesObject {
[remoteAlias: string]: RemotesConfig | RemotesItem | RemotesItems;
}
```
Here, `remoteAlias` is the name actually used by the user and can be configured arbitrarily. For example, if `remoteAlias` is set to `demo`, the consumption method is `import xx from 'demo'`.
### shared
- Type: `Shared`
- Required: No
- Default: `undefined`
`shared` is used to share common dependencies between consumers and producers, reducing runtime download size and thus improving performance.
The `Shared` type is defined as follows:
```tsx
type Shared = (SharedItem | SharedObject)[] | SharedObject;
type SharedItem = string;
interface SharedObject {
[k: string]: SharedConfig | SharedItem;
}
```
#### singleton
- Type: `boolean`
- Required: No
- Default: `false`
Determines whether only one version of the shared module is allowed in the shared scope (singleton mode).
- If the value is true, singleton mode is enabled; if the value is false, singleton mode is not enabled.
- If singleton mode is enabled, the shared dependencies of the remote application components and host application are loaded only once, and a higher version is loaded when the versions are not consistent. At this time, a warning will be given to the lower version side:
- If singleton mode is not enabled, if the versions of shared dependencies between the remote application and host application are not consistent, the remote application and host application load their own dependencies
#### requiredVersion
- Type: `string`
- Required: False
- Default: `require('project/package.json')[devDeps | dep]['depName']`
The required version can be a version range. The default value is the dependency version of the current application.
- When using shared dependencies, it will be judged whether the dependency version meets requiredVersion. If it does, it will be used normally. If it is less than requiredVersion, a warning will be issued in the console, and the smallest version in the current shared dependency will be used.
- When one side sets requiredVersion and the other side sets singleton, the dependency of requiredVersion will be loaded, and the singleton side will directly use the dependency of requiredVersion, regardless of the version.
#### eager
:::warning
When `eager` is set to true, the shared dependencies will be packaged into the entry file, which will cause the entry file to be too large. Please open with caution.
`eager: true` is rarely recommended
:::
- Type: `boolean`
- Required: False
- Default: `false`
Determines whether to load shared modules immediately.
Under normal circumstances, you need to open the asynchronous entry, and then load shared asynchronously on demand. If you want to use shared but don't want to enable asynchronous entry, you can set `eager` to true .
### runtimePlugins
- Type: `string[] | Array<[string, Record<string, unknown>]>`
- Required: False
- Default: `undefined`
Used to add additional plug-ins required at runtime. The value is the path of the specific plug-in. It supports absolute/relative paths and package names.
Once set, the runtime plugin is automatically injected and used at build time.
### implementation
- Type: `string`
- Required: False
- Default: `undefined`
Used to modify the actual bundler runtime version. Path with value `@module-federation/runtime-tools`.
## CLI
To view all available CLI commands, run the following command in the project directory:
```bash
npx mf -h
```
The output is shown below:
```bash
Usage: mf <command> [options]
Options:
-V, --version output the version number
-h, --help display help for command
Commands:
dts [options] generate or fetch the mf types
help [command] display help for command
```
### mf dts
The mf dts command is used to generate or fetch remote types.
```bash
Usage: mf dts [options]
generate or fetch the mf types
Options:
--root <root> specify the project root directory
--output <output> specify the generated dts output directory
--fetch <boolean> fetch types from remote, default is true (default: true)
--generate <boolean> generate types, default is true (default: true)
-c --config <config> specify the configuration file, can be a relative or absolute path
-h, --help display help for command
```

View File

@@ -0,0 +1,140 @@
# Rstest migration plan for packages/enhanced
This document captures the work needed to migrate the enhanced package tests
from Jest to Rstest. It is written against the current repo state and the
Rstest docs listed in the references section.
## Current state
- Jest configs are in `packages/enhanced/jest.config.ts` and
`packages/enhanced/jest.embed.ts`, with Nx targets `test:jest` and
`test:experiments` in `packages/enhanced/project.json`.
- The default `enhanced:test` target runs Vitest via
`packages/enhanced/vitest.config.ts`.
- Rstest is already wired in `packages/enhanced/rstest.config.ts`, but only
includes `test/ConfigTestCases.*.rstest.ts` files.
- Many unit and compiler tests under `packages/enhanced/test/**` are Jest-only
(global `jest`, `jest.mock`, `jest.fn`, callback-style `done`, etc).
## Target state
- All enhanced package tests run under Rstest via `enhanced:rstest`.
- Nx target `enhanced:test` uses Rstest and no longer depends on Jest/Vitest.
- Jest-only helpers/configs in `packages/enhanced` are removed or unused.
## Work items
### 1) Update scripts and Nx targets
- Switch `packages/enhanced/project.json` `test` target to Rstest:
`rstest run -c packages/enhanced/rstest.config.ts` (match CLI usage).
- Replace or remove `test:jest` and `test:experiments` targets, or rewrite
them as Rstest equivalents (for example, separate includes/projects).
- Keep `enhanced:rstest` in the root `package.json` as the user-facing entry
point and ensure it uses `rstest run` (or `rstest`) consistently.
### 2) Expand `rstest.config.ts` coverage
- Include unit and compiler tests (not just ConfigTestCases):
- `test/**/*.test.ts`
- `test/**/*.spec.ts`
- `test/**/*.rstest.ts` (keep existing Rstest cases)
- Exclude non-Rstest variants to prevent duplicate runs:
- `test/**/*.vitest.ts`
- `test/**/*.basictest.js` (Jest-only)
- `test/**/*.embedruntime.js` (Jest-only)
- Consider Rstest `projects` to separate long-running config-case tests from
fast unit tests (different `testTimeout`, `include`, etc).
- Add `setupFiles` to reapply `test/setupTestFramework.js` logic (custom
matchers and debug hooks).
- If cleaning `packages/enhanced/test/js` is still required, move it to
`globalSetup` or a pretest script instead of Jest config.
### 3) Replace Jest APIs in tests
Map Jest-only APIs to Rstest equivalents and update imports where needed.
Core mappings:
- `jest.fn` -> `rs.fn` (from `@rstest/core`)
- `jest.spyOn` -> `rs.spyOn`
- `jest.mock` -> `rs.mock`
- `jest.doMock` -> `rs.doMock`
- `jest.dontMock` -> `rs.unmock` or `rs.doUnmock`
- `jest.resetModules` -> `rs.resetModules` (note: does not clear mocks)
- `jest.clearAllMocks` -> `rs.clearAllMocks`
- `jest.resetAllMocks` -> `rs.resetAllMocks`
- `jest.restoreAllMocks` -> `rs.restoreAllMocks`
- `jest.setTimeout` -> `rs.setConfig({ testTimeout })` or config `testTimeout`
- `jest.requireActual` -> `await rs.importActual(...)` or
`import ... with { rstest: 'importActual' }`
Known gaps to rework:
- `jest.isolateModules` has no direct Rstest equivalent; use
`rs.resetModules` + dynamic `import()` and refactor those tests.
Files to review specifically (non-exhaustive):
- `packages/enhanced/test/helpers/webpackMocks.ts`
- `packages/enhanced/test/compiler-unit/**/*.test.ts`
- `packages/enhanced/test/unit/**/*.test.ts`
- `packages/enhanced/test/ConfigTestCases.template.js`
- `packages/enhanced/test/ConfigTestCases.embedruntime.js`
- `packages/enhanced/test/ConfigTestCases.basictest.js`
### 4) Remove callback-style `done` usage
Rstest does not support `done` callbacks in tests. Convert to async/Promise
style (return a Promise or `async` function). Key files include:
- `packages/enhanced/test/warmup-webpack.js`
- `packages/enhanced/test/helpers/expectWarningFactory.js`
- `packages/enhanced/test/compiler-unit/container/HoistContainerReferencesPlugin.test.ts`
- `packages/enhanced/test/ConfigTestCases.template.js` (if still used)
Note: callback-style functions inside config-case bundles are already wrapped
in `packages/enhanced/test/ConfigTestCases.rstest.ts` and do not require
Rstest to support `done`.
### 5) TypeScript types and globals
- Decide between explicit imports (`import { describe, it, expect, rs }`)
vs `globals: true`. The current `rstest.config.ts` uses `globals: true`.
- If keeping globals, update `packages/enhanced/tsconfig.spec.json` to include
`@rstest/core/globals` and remove `jest` types.
- Replace `jest.Mock`, `jest.MockedFunction`, etc. with Rstest types
(`Mock`, `MockInstance`) from `@rstest/core`.
### 6) Remove Jest-only infra
- Drop or ignore `packages/enhanced/jest.config.ts`,
`packages/enhanced/jest.embed.ts`, and `packages/enhanced/test/patch-node-env.js`
once no tests rely on them.
- Rework `packages/enhanced/test/helpers/createLazyTestEnv.js`, which depends on
`JEST_STATE_SYMBOL`. Prefer avoiding this helper under Rstest or implement a
Rstest-native alternative if still needed.
### 7) Verify behavior and parity
- Run `pnpm enhanced:rstest` and check for parity with the old Jest suite.
- Use `rstest list --filesOnly -c packages/enhanced/rstest.config.ts` to verify
include/exclude patterns.
- Validate that custom matchers in `test/setupTestFramework.js` still work with
Rstest's `expect.extend`.
## Suggested file-level checklist
- `packages/enhanced/project.json`: update `test` target and pre-release steps.
- `packages/enhanced/rstest.config.ts`: include patterns, setupFiles,
globalSetup, timeouts.
- `packages/enhanced/tsconfig.spec.json`: replace Jest types with Rstest types.
- `packages/enhanced/test/setupTestFramework.js`: ensure compatibility with
Rstest (no `done` usage).
- `packages/enhanced/test/helpers/webpackMocks.ts`: replace Jest mocks.
- `packages/enhanced/test/unit/**`: replace Jest APIs and types.
- `packages/enhanced/test/compiler-unit/**`: replace Jest APIs and types.
## References (Rstest docs)
- https://rstest.rs/llms.txt
- https://rstest.rs/guide/migration/jest.md
- https://rstest.rs/guide/basic/cli.md
- https://rstest.rs/guide/basic/configure-rstest.md
- https://rstest.rs/guide/basic/projects.md
- https://rstest.rs/config/test/include.md
- https://rstest.rs/config/test/setup-files.md
- https://rstest.rs/config/test/global-setup.md
- https://rstest.rs/config/test/globals.md
- https://rstest.rs/config/test/test-environment.md
- https://rstest.rs/api/runtime-api/test-api/expect.md
- https://rstest.rs/api/runtime-api/rstest/mock-modules.md
- https://rstest.rs/api/runtime-api/rstest/mock-functions.md
- https://rstest.rs/api/runtime-api/rstest/mock-instance.md
- https://rstest.rs/api/runtime-api/rstest/utilities.md
- https://rstest.rs/api/javascript-api/rstest-core.md

View File

@@ -0,0 +1,47 @@
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) {
__defProp(target, name, {
get: all[name],
enumerable: true
});
}
if (!no_symbols) {
__defProp(target, Symbol.toStringTag, { value: "Module" });
}
return target;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) {
__defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
}
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
//#endregion
exports.__esmMin = __esmMin;
exports.__exportAll = __exportAll;
exports.__toCommonJS = __toCommonJS;
exports.__toESM = __toESM;

View File

@@ -0,0 +1,24 @@
import ModuleFederationPlugin, { PLUGIN_NAME } from "./wrapper/ModuleFederationPlugin.js";
import ContainerReferencePlugin from "./wrapper/ContainerReferencePlugin.js";
import SharePlugin from "./wrapper/SharePlugin.js";
import ContainerPlugin from "./wrapper/ContainerPlugin.js";
import ConsumeSharedPlugin from "./wrapper/ConsumeSharedPlugin.js";
import ProvideSharedPlugin from "./wrapper/ProvideSharedPlugin.js";
import FederationModulesPlugin from "./wrapper/FederationModulesPlugin.js";
import FederationRuntimePlugin from "./wrapper/FederationRuntimePlugin.js";
import AsyncBoundaryPlugin from "./wrapper/AsyncBoundaryPlugin.js";
import HoistContainerReferencesPlugin from "./wrapper/HoistContainerReferencesPlugin.js";
import TreeShakingSharedPlugin from "./wrapper/TreeShakingSharedPlugin.js";
import { parseOptions } from "./lib/container/options.js";
import { createModuleFederationConfig, moduleFederationPlugin } from "@module-federation/sdk";
//#region src/index.d.ts
declare const dependencies: {
readonly ContainerEntryDependency: any;
};
declare const container: {
readonly ContainerEntryModule: any;
};
//#endregion
export { AsyncBoundaryPlugin, ConsumeSharedPlugin, ContainerPlugin, ContainerReferencePlugin, FederationModulesPlugin, FederationRuntimePlugin, HoistContainerReferencesPlugin, ModuleFederationPlugin, PLUGIN_NAME, ProvideSharedPlugin, SharePlugin, TreeShakingSharedPlugin, container, createModuleFederationConfig, dependencies, type moduleFederationPlugin, parseOptions };
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,48 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('./_virtual/_rolldown/runtime.js');
const require_wrapper_ModuleFederationPlugin = require('./wrapper/ModuleFederationPlugin.js');
const require_wrapper_ContainerReferencePlugin = require('./wrapper/ContainerReferencePlugin.js');
const require_wrapper_SharePlugin = require('./wrapper/SharePlugin.js');
const require_wrapper_ContainerPlugin = require('./wrapper/ContainerPlugin.js');
const require_wrapper_ConsumeSharedPlugin = require('./wrapper/ConsumeSharedPlugin.js');
const require_wrapper_ProvideSharedPlugin = require('./wrapper/ProvideSharedPlugin.js');
const require_wrapper_FederationModulesPlugin = require('./wrapper/FederationModulesPlugin.js');
const require_wrapper_FederationRuntimePlugin = require('./wrapper/FederationRuntimePlugin.js');
const require_wrapper_AsyncBoundaryPlugin = require('./wrapper/AsyncBoundaryPlugin.js');
const require_wrapper_HoistContainerReferencesPlugin = require('./wrapper/HoistContainerReferencesPlugin.js');
const require_wrapper_TreeShakingSharedPlugin = require('./wrapper/TreeShakingSharedPlugin.js');
const require_lib_container_options = require('./lib/container/options.js');
let _module_federation_sdk = require("@module-federation/sdk");
//#region src/index.ts
const lazyRequire = (id) => module.require(id);
const dependencies = { get ContainerEntryDependency() {
return lazyRequire("./lib/container/ContainerEntryDependency").default;
} };
const container = { get ContainerEntryModule() {
return lazyRequire("./lib/container/ContainerEntryModule").default;
} };
//#endregion
exports.AsyncBoundaryPlugin = require_wrapper_AsyncBoundaryPlugin.default;
exports.ConsumeSharedPlugin = require_wrapper_ConsumeSharedPlugin.default;
exports.ContainerPlugin = require_wrapper_ContainerPlugin.default;
exports.ContainerReferencePlugin = require_wrapper_ContainerReferencePlugin.default;
exports.FederationModulesPlugin = require_wrapper_FederationModulesPlugin.default;
exports.FederationRuntimePlugin = require_wrapper_FederationRuntimePlugin.default;
exports.HoistContainerReferencesPlugin = require_wrapper_HoistContainerReferencesPlugin.default;
exports.ModuleFederationPlugin = require_wrapper_ModuleFederationPlugin.default;
exports.PLUGIN_NAME = require_wrapper_ModuleFederationPlugin.PLUGIN_NAME;
exports.ProvideSharedPlugin = require_wrapper_ProvideSharedPlugin.default;
exports.SharePlugin = require_wrapper_SharePlugin.default;
exports.TreeShakingSharedPlugin = require_wrapper_TreeShakingSharedPlugin.default;
exports.container = container;
Object.defineProperty(exports, 'createModuleFederationConfig', {
enumerable: true,
get: function () {
return _module_federation_sdk.createModuleFederationConfig;
}
});
exports.dependencies = dependencies;
exports.parseOptions = require_lib_container_options.parseOptions;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import type { moduleFederationPlugin } from '@module-federation/sdk';\nexport {\n default as ModuleFederationPlugin,\n PLUGIN_NAME,\n} from './wrapper/ModuleFederationPlugin';\nexport { default as ContainerReferencePlugin } from './wrapper/ContainerReferencePlugin';\nexport { default as SharePlugin } from './wrapper/SharePlugin';\nexport { default as ContainerPlugin } from './wrapper/ContainerPlugin';\nexport { default as ConsumeSharedPlugin } from './wrapper/ConsumeSharedPlugin';\nexport { default as ProvideSharedPlugin } from './wrapper/ProvideSharedPlugin';\nexport { default as FederationModulesPlugin } from './wrapper/FederationModulesPlugin';\nexport { default as FederationRuntimePlugin } from './wrapper/FederationRuntimePlugin';\nexport { default as AsyncBoundaryPlugin } from './wrapper/AsyncBoundaryPlugin';\nexport { default as HoistContainerReferencesPlugin } from './wrapper/HoistContainerReferencesPlugin';\nexport { default as TreeShakingSharedPlugin } from './wrapper/TreeShakingSharedPlugin';\n\nconst lazyRequire = (id: string): any => module.require(id);\n\nexport const dependencies = {\n get ContainerEntryDependency() {\n return lazyRequire('./lib/container/ContainerEntryDependency').default;\n },\n};\n\nexport { parseOptions } from './lib/container/options';\n\nexport const container = {\n get ContainerEntryModule() {\n return lazyRequire('./lib/container/ContainerEntryModule').default;\n },\n};\n\nexport { createModuleFederationConfig } from '@module-federation/sdk';\n\nexport type { moduleFederationPlugin };\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,MAAM,eAAe,OAAoB,OAAO,QAAQ,GAAG;AAE3D,MAAa,eAAe,EAC1B,IAAI,2BAA2B;AAC7B,QAAO,YAAY,2CAA2C,CAAC;GAElE;AAID,MAAa,YAAY,EACvB,IAAI,uBAAuB;AACzB,QAAO,YAAY,uCAAuC,CAAC;GAE9D"}

View File

@@ -0,0 +1,113 @@
//#region src/lib/Constants.d.ts
/**
* @type {Readonly<"javascript/auto">}
*/
declare const JAVASCRIPT_MODULE_TYPE_AUTO: Readonly<'javascript/auto'>;
/**
* @type {Readonly<"javascript/dynamic">}
*/
declare const JAVASCRIPT_MODULE_TYPE_DYNAMIC: Readonly<'javascript/dynamic'>;
/**
* @type {Readonly<"javascript/esm">}
* This is the module type used for _strict_ ES Module syntax. This means that all legacy formats
* that webpack supports (CommonJS, AMD, SystemJS) are not supported.
*/
declare const JAVASCRIPT_MODULE_TYPE_ESM: Readonly<'javascript/esm'>;
/**
* @type {Readonly<"json">}
* This is the module type used for JSON files. JSON files are always parsed as ES Module.
*/
declare const JSON_MODULE_TYPE: Readonly<'json'>;
/**
* @type {Readonly<"webassembly/async">}
* This is the module type used for WebAssembly modules. In webpack 5 they are always treated as async modules.
*
*/
declare const WEBASSEMBLY_MODULE_TYPE_ASYNC: Readonly<'webassembly/async'>;
/**
* @type {Readonly<"webassembly/sync">}
* This is the module type used for WebAssembly modules. In webpack 4 they are always treated as sync modules.
* There is a legacy option to support this usage in webpack 5 and up.
*/
declare const WEBASSEMBLY_MODULE_TYPE_SYNC: Readonly<'webassembly/sync'>;
/**
* @type {Readonly<"css">}
* This is the module type used for CSS files.
*/
declare const CSS_MODULE_TYPE: Readonly<'css'>;
/**
* @type {Readonly<"css/global">}
* This is the module type used for CSS modules files where you need to use `:local` in selector list to hash classes.
*/
declare const CSS_MODULE_TYPE_GLOBAL: Readonly<'css/global'>;
/**
* @type {Readonly<"css/module">}
* This is the module type used for CSS modules files, by default all classes are hashed.
*/
declare const CSS_MODULE_TYPE_MODULE: Readonly<'css/module'>;
/**
* @type {Readonly<"css/auto">}
* This is the module type used for CSS files, the module will be parsed as CSS modules if it's filename contains `.module.` or `.modules.`.
*/
declare const CSS_MODULE_TYPE_AUTO: Readonly<'css/auto'>;
/**
* @type {Readonly<"asset">}
* This is the module type used for automatically choosing between `asset/inline`, `asset/resource` based on asset size limit (8096).
*/
declare const ASSET_MODULE_TYPE: Readonly<'asset'>;
/**
* @type {Readonly<"asset/inline">}
* This is the module type used for assets that are inlined as a data URI. This is the equivalent of `url-loader`.
*/
declare const ASSET_MODULE_TYPE_INLINE: Readonly<'asset/inline'>;
/**
* @type {Readonly<"asset/resource">}
* This is the module type used for assets that are copied to the output directory. This is the equivalent of `file-loader`.
*/
declare const ASSET_MODULE_TYPE_RESOURCE: Readonly<'asset/resource'>;
/**
* @type {Readonly<"asset/source">}
* This is the module type used for assets that are imported as source code. This is the equivalent of `raw-loader`.
*/
declare const ASSET_MODULE_TYPE_SOURCE: Readonly<'asset/source'>;
/**
* @type {Readonly<"asset/raw-data-url">}
* TODO: Document what this asset type is for. See css-loader tests for its usage.
*/
declare const ASSET_MODULE_TYPE_RAW_DATA_URL: Readonly<'asset/raw-data-url'>;
/**
* @type {Readonly<"runtime">}
* This is the module type used for the webpack runtime abstractions.
*/
declare const WEBPACK_MODULE_TYPE_RUNTIME: Readonly<'runtime'>;
/**
* @type {Readonly<"fallback-module">}
* This is the module type used for the ModuleFederation feature's FallbackModule class.
* TODO: Document this better.
*/
declare const WEBPACK_MODULE_TYPE_FALLBACK: Readonly<'fallback-module'>;
/**
* @type {Readonly<"remote-module">}
* This is the module type used for the ModuleFederation feature's RemoteModule class.
* TODO: Document this better.
*/
declare const WEBPACK_MODULE_TYPE_REMOTE: Readonly<'remote-module'>;
/**
* @type {Readonly<"provide-module">}
* This is the module type used for the ModuleFederation feature's ProvideModule class.
* TODO: Document this better.
*/
declare const WEBPACK_MODULE_TYPE_PROVIDE: Readonly<'provide-module'>;
/**
* @type {Readonly<"consume-shared-module">}
* This is the module type used for the ModuleFederation feature's ConsumeSharedModule class.
*/
declare const WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE: Readonly<'consume-shared-module'>;
/**
* @type {Readonly<"lazy-compilation-proxy">}
* Module type used for `experiments.lazyCompilation` feature. See `LazyCompilationPlugin` for more information.
*/
declare const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY: Readonly<'lazy-compilation-proxy'>;
//#endregion
export { ASSET_MODULE_TYPE, ASSET_MODULE_TYPE_INLINE, ASSET_MODULE_TYPE_RAW_DATA_URL, ASSET_MODULE_TYPE_RESOURCE, ASSET_MODULE_TYPE_SOURCE, CSS_MODULE_TYPE, CSS_MODULE_TYPE_AUTO, CSS_MODULE_TYPE_GLOBAL, CSS_MODULE_TYPE_MODULE, JAVASCRIPT_MODULE_TYPE_AUTO, JAVASCRIPT_MODULE_TYPE_DYNAMIC, JAVASCRIPT_MODULE_TYPE_ESM, JSON_MODULE_TYPE, WEBASSEMBLY_MODULE_TYPE_ASYNC, WEBASSEMBLY_MODULE_TYPE_SYNC, WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE, WEBPACK_MODULE_TYPE_FALLBACK, WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY, WEBPACK_MODULE_TYPE_PROVIDE, WEBPACK_MODULE_TYPE_REMOTE, WEBPACK_MODULE_TYPE_RUNTIME };
//# sourceMappingURL=Constants.d.ts.map

View File

@@ -0,0 +1,145 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
//#region src/lib/Constants.ts
/**
* @type {Readonly<"javascript/auto">}
*/
const JAVASCRIPT_MODULE_TYPE_AUTO = "javascript/auto";
/**
* @type {Readonly<"javascript/dynamic">}
*/
const JAVASCRIPT_MODULE_TYPE_DYNAMIC = "javascript/dynamic";
/**
* @type {Readonly<"javascript/esm">}
* This is the module type used for _strict_ ES Module syntax. This means that all legacy formats
* that webpack supports (CommonJS, AMD, SystemJS) are not supported.
*/
const JAVASCRIPT_MODULE_TYPE_ESM = "javascript/esm";
/**
* @type {Readonly<"json">}
* This is the module type used for JSON files. JSON files are always parsed as ES Module.
*/
const JSON_MODULE_TYPE = "json";
/**
* @type {Readonly<"webassembly/async">}
* This is the module type used for WebAssembly modules. In webpack 5 they are always treated as async modules.
*
*/
const WEBASSEMBLY_MODULE_TYPE_ASYNC = "webassembly/async";
/**
* @type {Readonly<"webassembly/sync">}
* This is the module type used for WebAssembly modules. In webpack 4 they are always treated as sync modules.
* There is a legacy option to support this usage in webpack 5 and up.
*/
const WEBASSEMBLY_MODULE_TYPE_SYNC = "webassembly/sync";
/**
* @type {Readonly<"css">}
* This is the module type used for CSS files.
*/
const CSS_MODULE_TYPE = "css";
/**
* @type {Readonly<"css/global">}
* This is the module type used for CSS modules files where you need to use `:local` in selector list to hash classes.
*/
const CSS_MODULE_TYPE_GLOBAL = "css/global";
/**
* @type {Readonly<"css/module">}
* This is the module type used for CSS modules files, by default all classes are hashed.
*/
const CSS_MODULE_TYPE_MODULE = "css/module";
/**
* @type {Readonly<"css/auto">}
* This is the module type used for CSS files, the module will be parsed as CSS modules if it's filename contains `.module.` or `.modules.`.
*/
const CSS_MODULE_TYPE_AUTO = "css/auto";
/**
* @type {Readonly<"asset">}
* This is the module type used for automatically choosing between `asset/inline`, `asset/resource` based on asset size limit (8096).
*/
const ASSET_MODULE_TYPE = "asset";
/**
* @type {Readonly<"asset/inline">}
* This is the module type used for assets that are inlined as a data URI. This is the equivalent of `url-loader`.
*/
const ASSET_MODULE_TYPE_INLINE = "asset/inline";
/**
* @type {Readonly<"asset/resource">}
* This is the module type used for assets that are copied to the output directory. This is the equivalent of `file-loader`.
*/
const ASSET_MODULE_TYPE_RESOURCE = "asset/resource";
/**
* @type {Readonly<"asset/source">}
* This is the module type used for assets that are imported as source code. This is the equivalent of `raw-loader`.
*/
const ASSET_MODULE_TYPE_SOURCE = "asset/source";
/**
* @type {Readonly<"asset/raw-data-url">}
* TODO: Document what this asset type is for. See css-loader tests for its usage.
*/
const ASSET_MODULE_TYPE_RAW_DATA_URL = "asset/raw-data-url";
/**
* @type {Readonly<"runtime">}
* This is the module type used for the webpack runtime abstractions.
*/
const WEBPACK_MODULE_TYPE_RUNTIME = "runtime";
/**
* @type {Readonly<"fallback-module">}
* This is the module type used for the ModuleFederation feature's FallbackModule class.
* TODO: Document this better.
*/
const WEBPACK_MODULE_TYPE_FALLBACK = "fallback-module";
/**
* @type {Readonly<"remote-module">}
* This is the module type used for the ModuleFederation feature's RemoteModule class.
* TODO: Document this better.
*/
const WEBPACK_MODULE_TYPE_REMOTE = "remote-module";
/**
* @type {Readonly<"provide-module">}
* This is the module type used for the ModuleFederation feature's ProvideModule class.
* TODO: Document this better.
*/
const WEBPACK_MODULE_TYPE_PROVIDE = "provide-module";
/**
* @type {Readonly<"consume-shared-module">}
* This is the module type used for the ModuleFederation feature's ConsumeSharedModule class.
*/
const WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE = "consume-shared-module";
/**
* @type {Readonly<"lazy-compilation-proxy">}
* Module type used for `experiments.lazyCompilation` feature. See `LazyCompilationPlugin` for more information.
*/
const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = "lazy-compilation-proxy";
/** @typedef {"javascript/auto" | "javascript/dynamic" | "javascript/esm"} JavaScriptModuleTypes */
/** @typedef {"json"} JSONModuleType */
/** @typedef {"webassembly/async" | "webassembly/sync"} WebAssemblyModuleTypes */
/** @typedef {"css" | "css/global" | "css/module"} CSSModuleTypes */
/** @typedef {"asset" | "asset/inline" | "asset/resource" | "asset/source" | "asset/raw-data-url"} AssetModuleTypes */
/** @typedef {"runtime" | "fallback-module" | "remote-module" | "provide-module" | "consume-shared-module" | "lazy-compilation-proxy"} WebpackModuleTypes */
/** @typedef {string} UnknownModuleTypes */
/** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CSSModuleTypes | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */
//#endregion
exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE;
exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE;
exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL;
exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE;
exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE;
exports.CSS_MODULE_TYPE = CSS_MODULE_TYPE;
exports.CSS_MODULE_TYPE_AUTO = CSS_MODULE_TYPE_AUTO;
exports.CSS_MODULE_TYPE_GLOBAL = CSS_MODULE_TYPE_GLOBAL;
exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE;
exports.JAVASCRIPT_MODULE_TYPE_AUTO = JAVASCRIPT_MODULE_TYPE_AUTO;
exports.JAVASCRIPT_MODULE_TYPE_DYNAMIC = JAVASCRIPT_MODULE_TYPE_DYNAMIC;
exports.JAVASCRIPT_MODULE_TYPE_ESM = JAVASCRIPT_MODULE_TYPE_ESM;
exports.JSON_MODULE_TYPE = JSON_MODULE_TYPE;
exports.WEBASSEMBLY_MODULE_TYPE_ASYNC = WEBASSEMBLY_MODULE_TYPE_ASYNC;
exports.WEBASSEMBLY_MODULE_TYPE_SYNC = WEBASSEMBLY_MODULE_TYPE_SYNC;
exports.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE = WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE;
exports.WEBPACK_MODULE_TYPE_FALLBACK = WEBPACK_MODULE_TYPE_FALLBACK;
exports.WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY;
exports.WEBPACK_MODULE_TYPE_PROVIDE = WEBPACK_MODULE_TYPE_PROVIDE;
exports.WEBPACK_MODULE_TYPE_REMOTE = WEBPACK_MODULE_TYPE_REMOTE;
exports.WEBPACK_MODULE_TYPE_RUNTIME = WEBPACK_MODULE_TYPE_RUNTIME;
//# sourceMappingURL=Constants.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
import { moduleFederationPlugin } from "@module-federation/sdk";
import { Chunk, Compilation, Compiler } from "webpack";
//#region src/lib/container/AsyncBoundaryPlugin.d.ts
type Options = moduleFederationPlugin.AsyncBoundaryOptions;
declare class AsyncEntryStartupPlugin {
private _options;
private _runtimeChunks;
constructor(options?: Options);
apply(compiler: Compiler): void;
private _collectRuntimeChunks;
getChunkByName(compilation: Compilation, dependOn: string[], byname: Set<Chunk>): void;
private _handleRenderStartup;
private _getChunkRuntime;
private _getRemotes;
private _getShared;
private _getInitialEntryModules;
private _getTemplateString;
}
//#endregion
export { Options, AsyncEntryStartupPlugin as default };
//# sourceMappingURL=AsyncBoundaryPlugin.d.ts.map

View File

@@ -0,0 +1,143 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/AsyncBoundaryPlugin.ts
const SortableSet = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/SortableSet"));
var AsyncEntryStartupPlugin = class {
constructor(options) {
this._runtimeChunks = /* @__PURE__ */ new Map();
this._options = options || {};
}
apply(compiler) {
compiler.hooks.thisCompilation.tap("AsyncEntryStartupPlugin", (compilation) => {
this._collectRuntimeChunks(compilation);
this._handleRenderStartup(compiler, compilation);
});
}
_collectRuntimeChunks(compilation) {
compilation.hooks.beforeChunkAssets.tap("AsyncEntryStartupPlugin", () => {
for (const chunk of compilation.chunks) if (chunk.hasRuntime() && chunk.id !== null) {
this._runtimeChunks.set(chunk.id, chunk);
for (const dependentChunk of compilation.chunkGraph.getChunkEntryDependentChunksIterable(chunk)) if (dependentChunk.id !== null) this._runtimeChunks.set(dependentChunk.id, dependentChunk);
}
});
}
getChunkByName(compilation, dependOn, byname) {
for (const name of dependOn) {
const chunk = compilation.namedChunks.get(name);
if (chunk) byname.add(chunk);
}
}
_handleRenderStartup(compiler, compilation) {
compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation).renderStartup.tap("AsyncEntryStartupPlugin", (source, _renderContext, upperContext) => {
const isSingleRuntime = compiler.options?.optimization?.runtimeChunk;
if (upperContext?.chunk.id && isSingleRuntime) {
if (upperContext?.chunk.hasRuntime()) {
this._runtimeChunks.set(upperContext.chunk.id, upperContext.chunk);
return source;
}
}
if (this._options.excludeChunk && this._options.excludeChunk(upperContext.chunk)) return source;
const runtime = this._getChunkRuntime(upperContext);
let remotes = "";
let shared = "";
for (const runtimeItem of runtime) {
if (!runtimeItem) continue;
const requirements = compilation.chunkGraph.getTreeRuntimeRequirements(runtimeItem);
const entryOptions = upperContext.chunk.getEntryOptions();
const chunkInitialsSet = new Set(compilation.chunkGraph.getChunkEntryDependentChunksIterable(upperContext.chunk));
chunkInitialsSet.add(upperContext.chunk);
const dependOn = entryOptions?.dependOn || [];
this.getChunkByName(compilation, dependOn, chunkInitialsSet);
const initialChunks = [];
let hasRemoteModules = false;
let consumeShares = false;
for (const chunk of chunkInitialsSet) {
initialChunks.push(chunk.id);
if (!hasRemoteModules) hasRemoteModules = Boolean(compilation.chunkGraph.getChunkModulesIterableBySourceType(chunk, "remote"));
if (!consumeShares) consumeShares = Boolean(compilation.chunkGraph.getChunkModulesIterableBySourceType(chunk, "consume-shared"));
if (hasRemoteModules && consumeShares) break;
}
remotes = this._getRemotes(compiler.webpack.RuntimeGlobals, requirements, hasRemoteModules, initialChunks, remotes);
shared = this._getShared(compiler.webpack.RuntimeGlobals, requirements, consumeShares, initialChunks, shared);
}
if (!remotes && !shared) return source;
const initialEntryModules = this._getInitialEntryModules(compilation, upperContext);
const templateString = this._getTemplateString(compiler, initialEntryModules, shared, remotes, source);
return new compiler.webpack.sources.ConcatSource(templateString);
});
}
_getChunkRuntime(upperContext) {
const runtime = /* @__PURE__ */ new Set();
const chunkRuntime = upperContext.chunk.runtime;
if (chunkRuntime) {
const runtimeItems = chunkRuntime instanceof SortableSet ? chunkRuntime : [chunkRuntime];
for (const runtimeItem of runtimeItems) {
const chunk = this._runtimeChunks.get(runtimeItem);
if (chunk) runtime.add(chunk);
}
}
if (runtime.size === 0) runtime.add(upperContext.chunk);
return runtime;
}
_getRemotes(runtimeGlobals, requirements, hasRemoteModules, chunksToRef, remotes) {
if (!requirements.has(runtimeGlobals.currentRemoteGetScope) && !hasRemoteModules && !requirements.has("__webpack_require__.vmok")) return remotes;
const remotesParts = remotes.startsWith("if(__webpack_require__.f && __webpack_require__.f.remotes) {") ? [remotes] : [remotes, "if(__webpack_require__.f && __webpack_require__.f.remotes) {"];
for (const chunkId of chunksToRef) if (chunkId !== null && chunkId !== void 0) remotesParts.push(` __webpack_require__.f.remotes(${JSON.stringify(chunkId)}, promiseTrack);`);
remotesParts.push("}");
return remotesParts.join("");
}
_getShared(runtimeGlobals, requirements, consumeShares, chunksToRef, shared) {
if (!requirements.has(runtimeGlobals.shareScopeMap) && !consumeShares && !requirements.has(runtimeGlobals.initializeSharing)) return shared;
const sharedParts = shared.startsWith("if(__webpack_require__.f && __webpack_require__.f.consumes) {") ? [shared] : [shared, "if(__webpack_require__.f && __webpack_require__.f.consumes) {"];
for (const chunkId of chunksToRef) if (chunkId !== null && chunkId !== void 0) sharedParts.push(` __webpack_require__.f.consumes(${JSON.stringify(chunkId)}, promiseTrack);`);
sharedParts.push("}");
return sharedParts.join("");
}
_getInitialEntryModules(compilation, upperContext) {
const entryModules = compilation.chunkGraph.getChunkEntryModulesIterable(upperContext.chunk);
const initialEntryModules = [];
for (const entryModule of entryModules) {
const entryModuleID = compilation.chunkGraph.getModuleId(entryModule);
if (entryModuleID) {
let shouldInclude = false;
if (typeof this._options.eager === "function") shouldInclude = this._options.eager(entryModule);
else if (this._options.eager && this._options.eager.test(entryModule.identifier())) shouldInclude = true;
if (shouldInclude) initialEntryModules.push(`if(__webpack_require__.m[${JSON.stringify(entryModuleID)}]) {
__webpack_require__(${JSON.stringify(entryModuleID)});
} else {
console.warn('Federation Runtime Module not found. In the current runtime');
}`);
}
}
return initialEntryModules;
}
_getTemplateString(compiler, initialEntryModules, shared, remotes, source) {
const { Template } = compiler.webpack;
const experiments = compiler.options?.experiments;
const experimentsRecord = experiments && typeof experiments === "object" ? experiments : null;
if (!!experimentsRecord && !!experimentsRecord["topLevelAwait"] && compiler.options?.experiments?.outputModule) return Template.asString([
"var promiseTrack = [];",
Template.asString(initialEntryModules),
shared,
remotes,
"await Promise.all(promiseTrack)",
Template.indent(source.source().toString())
]);
return Template.asString([
"var promiseTrack = [];",
Template.asString(initialEntryModules),
shared,
remotes,
"var __webpack_exports__ = Promise.all(promiseTrack).then(function() {",
Template.indent(source.source().toString()),
Template.indent("return __webpack_exports__"),
"});"
]);
}
};
//#endregion
exports.default = AsyncEntryStartupPlugin;
//# sourceMappingURL=AsyncBoundaryPlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { ExposeOptions } from "./ContainerEntryModule.js";
import * as webpack$1 from "webpack";
//#region src/lib/container/ContainerEntryDependency.d.ts
declare const Dependency: typeof webpack$1.Dependency;
declare class ContainerEntryDependency extends Dependency {
name: string;
exposes: [string, ExposeOptions][];
shareScope: string | string[];
injectRuntimeEntry: string;
/**
* @param {string} name entry name
* @param {[string, ExposeOptions][]} exposes list of exposed modules
* @param {string|string[]} shareScope name of the share scope
* @param {string[]} injectRuntimeEntry the path of injectRuntime file.
*/
constructor(name: string, exposes: [string, ExposeOptions][], shareScope: string | string[], injectRuntimeEntry: string);
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier(): string | null;
get type(): string;
get category(): string;
}
//#endregion
export { ContainerEntryDependency as default };
//# sourceMappingURL=ContainerEntryDependency.d.ts.map

View File

@@ -0,0 +1,39 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/ContainerEntryDependency.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { Dependency } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var ContainerEntryDependency = class extends Dependency {
/**
* @param {string} name entry name
* @param {[string, ExposeOptions][]} exposes list of exposed modules
* @param {string|string[]} shareScope name of the share scope
* @param {string[]} injectRuntimeEntry the path of injectRuntime file.
*/
constructor(name, exposes, shareScope, injectRuntimeEntry) {
super();
this.name = name;
this.exposes = exposes;
this.shareScope = shareScope;
this.injectRuntimeEntry = injectRuntimeEntry;
}
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier() {
return `container-entry-${this.name}`;
}
get type() {
return "container entry";
}
get category() {
return "esm";
}
};
makeSerializable(ContainerEntryDependency, "enhanced/lib/container/ContainerEntryDependency");
//#endregion
exports.default = ContainerEntryDependency;
//# sourceMappingURL=ContainerEntryDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ContainerEntryDependency.js","names":[],"sources":["../../../../src/lib/container/ContainerEntryDependency.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr\n*/\n\nimport { ExposeOptions } from './ContainerEntryModule';\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst makeSerializable = require(\n normalizeWebpackPath('webpack/lib/util/makeSerializable'),\n);\nconst { Dependency } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass ContainerEntryDependency extends Dependency {\n public name: string;\n public exposes: [string, ExposeOptions][];\n public shareScope: string | string[];\n public injectRuntimeEntry: string;\n\n /**\n * @param {string} name entry name\n * @param {[string, ExposeOptions][]} exposes list of exposed modules\n * @param {string|string[]} shareScope name of the share scope\n * @param {string[]} injectRuntimeEntry the path of injectRuntime file.\n */\n constructor(\n name: string,\n exposes: [string, ExposeOptions][],\n shareScope: string | string[],\n injectRuntimeEntry: string,\n ) {\n super();\n this.name = name;\n this.exposes = exposes;\n this.shareScope = shareScope;\n this.injectRuntimeEntry = injectRuntimeEntry;\n }\n\n /**\n * @returns {string | null} an identifier to merge equal requests\n */\n override getResourceIdentifier(): string | null {\n return `container-entry-${this.name}`;\n }\n\n override get type(): string {\n return 'container entry';\n }\n\n override get category(): string {\n return 'esm';\n }\n}\n\nmakeSerializable(\n ContainerEntryDependency,\n 'enhanced/lib/container/ContainerEntryDependency',\n);\n\nexport default ContainerEntryDependency;\n"],"mappings":";;;;;AAQA,MAAM,mBAAmB,gFACF,oCAAoC,CAC1D;AACD,MAAM,EAAE,eAAe,gFACA,UAAU,CAChC;AAED,IAAM,2BAAN,cAAuC,WAAW;;;;;;;CAYhD,YACE,MACA,SACA,YACA,oBACA;AACA,SAAO;AACP,OAAK,OAAO;AACZ,OAAK,UAAU;AACf,OAAK,aAAa;AAClB,OAAK,qBAAqB;;;;;CAM5B,AAAS,wBAAuC;AAC9C,SAAO,mBAAmB,KAAK;;CAGjC,IAAa,OAAe;AAC1B,SAAO;;CAGT,IAAa,WAAmB;AAC9B,SAAO;;;AAIX,iBACE,0BACA,kDACD"}

View File

@@ -0,0 +1,92 @@
import * as webpack$1 from "webpack";
import { Compilation } from "webpack";
import { InputFileSystem, LibIdentOptions, NeedBuildContext, ObjectDeserializerContext, ObjectSerializerContext, RequestShortener, ResolverWithOptions, WebpackOptions } from "webpack/lib/Module";
import WebpackError$1 from "webpack/lib/WebpackError";
//#region src/lib/container/ContainerEntryModule.d.ts
declare const Module$1: typeof webpack$1.Module;
type ExposeOptions = {
/**
* requests to exposed modules (last one is exported)
*/
import: string[];
/**
* custom chunk name for the exposed module
*/
name: string;
};
declare class ContainerEntryModule extends Module$1 {
private _name;
private _exposes;
private _shareScope;
private _injectRuntimeEntry;
/**
* @param {string} name container entry name
* @param {[string, ExposeOptions][]} exposes list of exposed modules
* @param {string|string[]} shareScope name of the share scope
* @param {string} injectRuntimeEntry the path of injectRuntime file.
*/
constructor(name: string, exposes: [string, ExposeOptions][], shareScope: string | string[], injectRuntimeEntry: string);
/**
* @param {ObjectDeserializerContext} context context
* @returns {ContainerEntryModule} deserialized container entry module
*/
static deserialize(context: ObjectDeserializerContext): ContainerEntryModule;
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes(): Set<string>;
/**
* @returns {string} a unique identifier of the module
*/
identifier(): string;
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener: RequestShortener): string;
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options: LibIdentOptions): string | null;
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context: NeedBuildContext, callback: (arg0: (WebpackError$1 | null) | undefined, arg1: boolean | undefined) => void): void;
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError): void} callback callback function
* @returns {void}
*/
build(options: WebpackOptions, compilation: Compilation, resolver: ResolverWithOptions, fs: InputFileSystem, callback: (err?: WebpackError$1) => void): void;
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({
moduleGraph,
chunkGraph,
runtimeTemplate
}: any): {
sources: Map<any, any>;
runtimeRequirements: Set<"__webpack_require__.d" | "__webpack_require__.o" | "__webpack_exports__">;
};
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type?: string): number;
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context: ObjectSerializerContext): void;
}
//#endregion
export { ExposeOptions, ContainerEntryModule as default };
//# sourceMappingURL=ContainerEntryModule.d.ts.map

View File

@@ -0,0 +1,217 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_Constants = require('../Constants.js');
const require_lib_container_ContainerExposedDependency = require('./ContainerExposedDependency.js');
const require_lib_container_runtime_utils = require('./runtime/utils.js');
let _module_federation_sdk = require("@module-federation/sdk");
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
let _module_federation_error_codes = require("@module-federation/error-codes");
let _module_federation_error_codes_node = require("@module-federation/error-codes/node");
//#region src/lib/container/ContainerEntryModule.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { sources: webpackSources, AsyncDependenciesBlock, Template, Module, RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const StaticExportsDependency = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/dependencies/StaticExportsDependency"));
const EntryDependency = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/dependencies/EntryDependency"));
const SOURCE_TYPES = new Set(["javascript"]);
var ContainerEntryModule = class ContainerEntryModule extends Module {
/**
* @param {string} name container entry name
* @param {[string, ExposeOptions][]} exposes list of exposed modules
* @param {string|string[]} shareScope name of the share scope
* @param {string} injectRuntimeEntry the path of injectRuntime file.
*/
constructor(name, exposes, shareScope, injectRuntimeEntry) {
super(require_lib_Constants.JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
this._name = name;
this._exposes = exposes;
this._shareScope = shareScope;
this._injectRuntimeEntry = injectRuntimeEntry;
}
/**
* @param {ObjectDeserializerContext} context context
* @returns {ContainerEntryModule} deserialized container entry module
*/
static deserialize(context) {
const { read } = context;
const obj = new ContainerEntryModule(read(), read(), read(), read());
obj.deserialize(context);
return obj;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
return SOURCE_TYPES;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return `container entry (${Array.isArray(this._shareScope) ? this._shareScope.join("|") : this._shareScope}) ${JSON.stringify(this._exposes)} ${this._injectRuntimeEntry}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return "container entry";
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${this._name}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
callback(null, !this.buildMeta);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = {
strict: true,
topLevelDeclarations: new Set([
"moduleMap",
"get",
"init"
])
};
this.buildMeta.exportsType = "namespace";
this.clearDependenciesAndBlocks();
for (const [name, options] of this._exposes) {
const block = new AsyncDependenciesBlock({ name: options.name }, { name }, options.import[options.import.length - 1]);
let idx = 0;
for (const request of options.import) {
const dep = new require_lib_container_ContainerExposedDependency.default(name, request);
dep.loc = {
name,
index: idx++
};
block.addDependency(dep);
}
this.addBlock(block);
}
this.addDependency(new StaticExportsDependency(["get", "init"], false));
this.addDependency(new EntryDependency(this._injectRuntimeEntry));
callback();
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) {
const sources = /* @__PURE__ */ new Map();
const runtimeRequirements = new Set([
RuntimeGlobals.definePropertyGetters,
RuntimeGlobals.hasOwnProperty,
RuntimeGlobals.exports
]);
const getters = [];
for (const block of this.blocks) {
const { dependencies } = block;
const modules = dependencies.map((dependency) => {
const dep = dependency;
return {
name: dep.exposedName,
module: moduleGraph.getModule(dep),
request: dep.userRequest
};
});
let str;
if (modules.some((m) => !m.module)) {
(0, _module_federation_error_codes_node.logAndReport)(_module_federation_error_codes.BUILD_001, _module_federation_error_codes.buildDescMap, {
exposeModules: modules.filter((m) => !m.module),
FEDERATION_WEBPACK_PATH: process.env["FEDERATION_WEBPACK_PATH"]
}, _module_federation_sdk.infrastructureLogger.error.bind(_module_federation_sdk.infrastructureLogger), void 0, {
bundler: { name: "webpack" },
mfConfig: {
name: this._name,
exposes: Object.fromEntries(this._exposes.map(([key, opts]) => [key, opts.import[opts.import.length - 1]]))
}
});
process.exit(1);
} else str = `return ${runtimeTemplate.blockPromise({
block,
message: "",
chunkGraph,
runtimeRequirements
})}.then(${runtimeTemplate.returningFunction(runtimeTemplate.returningFunction(`(${modules.map(({ module, request }) => runtimeTemplate.moduleRaw({
module,
chunkGraph,
request,
weak: false,
runtimeRequirements
})).join(", ")})`))});`;
getters.push(`${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction("", str)}`);
}
const federationGlobal = require_lib_container_runtime_utils.getFederationGlobalScope(RuntimeGlobals || {});
const source = Template.asString([
`var moduleMap = {`,
Template.indent(getters.join(",\n")),
"};",
`var get = ${runtimeTemplate.basicFunction("module, getScope", [
`${RuntimeGlobals.currentRemoteGetScope} = getScope;`,
"getScope = (",
Template.indent([`${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`, Template.indent(["? moduleMap[module]()", `: Promise.resolve().then(${runtimeTemplate.basicFunction("", "throw new Error('Module \"' + module + '\" does not exist in container.');")})`])]),
");",
`${RuntimeGlobals.currentRemoteGetScope} = undefined;`,
"return getScope;"
])};`,
`var init = ${runtimeTemplate.basicFunction("shareScope, initScope, remoteEntryInitOptions", [`return ${federationGlobal}.bundlerRuntime.initContainerEntry({${Template.indent([
`webpackRequire: ${RuntimeGlobals.require},`,
`shareScope: shareScope,`,
`initScope: initScope,`,
`remoteEntryInitOptions: remoteEntryInitOptions,`,
`shareScopeKey: ${JSON.stringify(this._shareScope)}`
])}`, "})"])};`,
"// This exports getters to disallow modifications",
`${RuntimeGlobals.definePropertyGetters}(exports, {`,
Template.indent([`get: ${runtimeTemplate.returningFunction("get")},`, `init: ${runtimeTemplate.returningFunction("init")}`]),
"});"
]);
sources.set("javascript", this.useSourceMap || this.useSimpleSourceMap ? new webpackSources.OriginalSource(source, "webpack/container-entry") : new webpackSources.RawSource(source));
return {
sources,
runtimeRequirements
};
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this._name);
write(this._exposes);
write(this._shareScope);
write(this._injectRuntimeEntry);
super.serialize(context);
}
};
makeSerializable(ContainerEntryModule, "enhanced/lib/container/ContainerEntryModule");
//#endregion
exports.default = ContainerEntryModule;
//# sourceMappingURL=ContainerEntryModule.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,16 @@
import * as webpack_lib_ModuleFactory0 from "webpack/lib/ModuleFactory";
import { ModuleFactoryCreateData, ModuleFactoryResult } from "webpack/lib/ModuleFactory";
//#region src/lib/container/ContainerEntryModuleFactory.d.ts
declare const ModuleFactory: typeof webpack_lib_ModuleFactory0;
declare class ContainerEntryModuleFactory extends ModuleFactory {
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data: ModuleFactoryCreateData, callback: (error: Error | null, result: ModuleFactoryResult) => void): void;
}
//#endregion
export { ContainerEntryModuleFactory as default };
//# sourceMappingURL=ContainerEntryModuleFactory.d.ts.map

View File

@@ -0,0 +1,25 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_ContainerEntryModule = require('./ContainerEntryModule.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/ContainerEntryModuleFactory.ts
const ModuleFactory = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/ModuleFactory"));
var ContainerEntryModuleFactory = class extends ModuleFactory {
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
const { dependencies } = data;
const dep = dependencies[0];
callback(null, { module: new require_lib_container_ContainerEntryModule.default(dep.name, dep.exposes, dep.shareScope, dep.injectRuntimeEntry) });
}
};
//#endregion
exports.default = ContainerEntryModuleFactory;
//# sourceMappingURL=ContainerEntryModuleFactory.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ContainerEntryModuleFactory.js","names":["ContainerEntryModule"],"sources":["../../../../src/lib/container/ContainerEntryModuleFactory.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr\n*/\n\n'use strict';\n\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\nimport ContainerEntryModule from './ContainerEntryModule';\nimport ContainerEntryDependency from './ContainerEntryDependency';\n\nconst ModuleFactory = require(\n normalizeWebpackPath('webpack/lib/ModuleFactory'),\n) as typeof import('webpack/lib/ModuleFactory');\nimport type {\n ModuleFactoryCreateData,\n ModuleFactoryResult,\n} from 'webpack/lib/ModuleFactory';\n\nexport default class ContainerEntryModuleFactory extends ModuleFactory {\n /**\n * @param {ModuleFactoryCreateData} data data object\n * @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback\n * @returns {void}\n */\n override create(\n data: ModuleFactoryCreateData,\n callback: (error: Error | null, result: ModuleFactoryResult) => void,\n ): void {\n const { dependencies } = data;\n const containerDependencies =\n dependencies as unknown as ContainerEntryDependency[];\n const dep = containerDependencies[0];\n\n callback(null, {\n module: new ContainerEntryModule(\n dep.name,\n dep.exposes,\n dep.shareScope,\n dep.injectRuntimeEntry,\n ),\n });\n }\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,gBAAgB,gFACC,4BAA4B,CAClD;AAMD,IAAqB,8BAArB,cAAyD,cAAc;;;;;;CAMrE,AAAS,OACP,MACA,UACM;EACN,MAAM,EAAE,iBAAiB;EAGzB,MAAM,MADJ,aACgC;AAElC,WAAS,MAAM,EACb,QAAQ,IAAIA,mDACV,IAAI,MACJ,IAAI,SACJ,IAAI,YACJ,IAAI,mBACL,EACF,CAAC"}

View File

@@ -0,0 +1,31 @@
import * as webpack$1 from "webpack";
import { ObjectDeserializerContext, ObjectSerializerContext } from "webpack/lib/dependencies/ModuleDependency";
//#region src/lib/container/ContainerExposedDependency.d.ts
declare const dependencies: typeof webpack$1.dependencies;
declare class ContainerExposedDependency extends dependencies.ModuleDependency {
exposedName: string;
request: string;
/**
* @param {string} exposedName public name
* @param {string} request request to module
*/
constructor(exposedName: string, request: string);
get type(): string;
get category(): string;
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier(): string | null;
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context: ObjectSerializerContext): void;
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context: ObjectDeserializerContext): void;
}
//#endregion
export { ContainerExposedDependency as default };
//# sourceMappingURL=ContainerExposedDependency.d.ts.map

View File

@@ -0,0 +1,49 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/ContainerExposedDependency.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { dependencies } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var ContainerExposedDependency = class extends dependencies.ModuleDependency {
/**
* @param {string} exposedName public name
* @param {string} request request to module
*/
constructor(exposedName, request) {
super(request);
this.exposedName = exposedName;
this.request = request;
}
get type() {
return "container exposed";
}
get category() {
return "esm";
}
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier() {
return `exposed dependency ${this.exposedName}=${this.request}`;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
context.write(this.exposedName);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
this.exposedName = context.read();
super.deserialize(context);
}
};
makeSerializable(ContainerExposedDependency, "enhanced/lib/container/ContainerExposedDependency");
//#endregion
exports.default = ContainerExposedDependency;
//# sourceMappingURL=ContainerExposedDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ContainerExposedDependency.js","names":[],"sources":["../../../../src/lib/container/ContainerExposedDependency.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr\n*/\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst makeSerializable = require(\n normalizeWebpackPath('webpack/lib/util/makeSerializable'),\n) as typeof import('webpack/lib/util/makeSerializable');\nconst { dependencies } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nimport type {\n ObjectDeserializerContext,\n ObjectSerializerContext,\n} from 'webpack/lib/dependencies/ModuleDependency';\n\nclass ContainerExposedDependency extends dependencies.ModuleDependency {\n exposedName: string;\n override request: string;\n\n /**\n * @param {string} exposedName public name\n * @param {string} request request to module\n */\n constructor(exposedName: string, request: string) {\n super(request);\n this.exposedName = exposedName;\n this.request = request;\n }\n\n override get type(): string {\n return 'container exposed';\n }\n\n override get category(): string {\n return 'esm';\n }\n\n /**\n * @returns {string | null} an identifier to merge equal requests\n */\n override getResourceIdentifier(): string | null {\n return `exposed dependency ${this.exposedName}=${this.request}`;\n }\n\n /**\n * @param {ObjectSerializerContext} context context\n */\n override serialize(context: ObjectSerializerContext): void {\n context.write(this.exposedName);\n super.serialize(context);\n }\n\n /**\n * @param {ObjectDeserializerContext} context context\n */\n override deserialize(context: ObjectDeserializerContext): void {\n this.exposedName = context.read();\n super.deserialize(context);\n }\n}\n\nmakeSerializable(\n ContainerExposedDependency,\n 'enhanced/lib/container/ContainerExposedDependency',\n);\n\nexport default ContainerExposedDependency;\n"],"mappings":";;;;;AAMA,MAAM,mBAAmB,gFACF,oCAAoC,CAC1D;AACD,MAAM,EAAE,iBAAiB,gFACF,UAAU,CAChC;AAOD,IAAM,6BAAN,cAAyC,aAAa,iBAAiB;;;;;CAQrE,YAAY,aAAqB,SAAiB;AAChD,QAAM,QAAQ;AACd,OAAK,cAAc;AACnB,OAAK,UAAU;;CAGjB,IAAa,OAAe;AAC1B,SAAO;;CAGT,IAAa,WAAmB;AAC9B,SAAO;;;;;CAMT,AAAS,wBAAuC;AAC9C,SAAO,sBAAsB,KAAK,YAAY,GAAG,KAAK;;;;;CAMxD,AAAS,UAAU,SAAwC;AACzD,UAAQ,MAAM,KAAK,YAAY;AAC/B,QAAM,UAAU,QAAQ;;;;;CAM1B,AAAS,YAAY,SAA0C;AAC7D,OAAK,cAAc,QAAQ,MAAM;AACjC,QAAM,YAAY,QAAQ;;;AAI9B,iBACE,4BACA,oDACD"}

View File

@@ -0,0 +1,14 @@
import { containerPlugin } from "@module-federation/sdk";
import { Compiler } from "webpack";
//#region src/lib/container/ContainerPlugin.d.ts
declare class ContainerPlugin {
_options: containerPlugin.ContainerPluginOptions;
name: string;
constructor(options: containerPlugin.ContainerPluginOptions);
static patchChunkSplit(compiler: Compiler, name: string): void;
apply(compiler: Compiler): void;
}
//#endregion
export { ContainerPlugin as default };
//# sourceMappingURL=ContainerPlugin.d.ts.map

View File

@@ -0,0 +1,147 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_options = require('./options.js');
const require_lib_container_ContainerEntryDependency = require('./ContainerEntryDependency.js');
const require_lib_container_ContainerExposedDependency = require('./ContainerExposedDependency.js');
const require_lib_container_ContainerEntryModuleFactory = require('./ContainerEntryModuleFactory.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./runtime/FederationModulesPlugin.js');
const require_lib_container_runtime_FederationRuntimeDependency = require('./runtime/FederationRuntimeDependency.js');
const require_lib_container_runtime_FederationRuntimePlugin = require('./runtime/FederationRuntimePlugin.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/ContainerPlugin.ts
const ModuleDependency = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/dependencies/ModuleDependency"));
const EntryDependency = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/dependencies/EntryDependency"));
const PLUGIN_NAME = "ContainerPlugin";
var ContainerPlugin = class ContainerPlugin {
constructor(options) {
this.name = PLUGIN_NAME;
this._options = {
name: options.name,
shareScope: options.shareScope || "default",
library: options.library || {
type: "global",
name: options.name
},
runtime: options.runtime,
filename: options.filename || void 0,
exposes: require_lib_container_options.parseOptions(options.exposes, (item) => ({
import: Array.isArray(item) ? item : [item],
name: void 0
}), (item) => ({
import: Array.isArray(item.import) ? item.import : [item.import],
name: item.name || void 0
})),
runtimePlugins: options.runtimePlugins
};
}
static patchChunkSplit(compiler, name) {
const { splitChunks } = compiler.options.optimization;
const patchChunkSplit = (cacheGroup) => {
switch (typeof cacheGroup) {
case "boolean":
case "string":
case "function": break;
case "object":
if (cacheGroup instanceof RegExp) break;
if (!cacheGroup.chunks) break;
if (typeof cacheGroup.chunks === "function") {
const prevChunks = cacheGroup.chunks;
cacheGroup.chunks = (chunk) => {
if (chunk.name && (chunk.name === name || chunk.name === name + "_partial")) return false;
return prevChunks(chunk);
};
break;
}
if (cacheGroup.chunks === "all") {
cacheGroup.chunks = (chunk) => {
if (chunk.name && (chunk.name === name || chunk.name === name + "_partial")) return false;
return true;
};
break;
}
if (cacheGroup.chunks === "initial") {
cacheGroup.chunks = (chunk) => {
if (chunk.name && (chunk.name === name || chunk.name === name + "_partial")) return false;
return chunk.isOnlyInitial();
};
break;
}
break;
}
};
if (!splitChunks) return;
patchChunkSplit(splitChunks);
const cacheGroups = splitChunks.cacheGroups;
if (!cacheGroups) return;
Object.keys(cacheGroups).forEach((cacheGroupKey) => {
patchChunkSplit(cacheGroups[cacheGroupKey]);
});
}
apply(compiler) {
if (!compiler.options.plugins.find((p) => {
if (typeof p !== "object" || !p) return false;
return p["name"] === "ModuleFederationPlugin";
})) ContainerPlugin.patchChunkSplit(compiler, this._options.name);
const federationRuntimePluginInstance = new require_lib_container_runtime_FederationRuntimePlugin.default();
federationRuntimePluginInstance.apply(compiler);
const { name, exposes, shareScope, filename, library, runtime } = this._options;
if (library && compiler.options.output && compiler.options.output.enabledLibraryTypes && !compiler.options.output.enabledLibraryTypes.includes(library.type)) compiler.options.output.enabledLibraryTypes.push(library.type);
compiler.hooks.make.tapAsync(PLUGIN_NAME, async (compilation, callback) => {
const hooks = require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation);
const federationRuntimeDependency = federationRuntimePluginInstance.getDependency(compiler);
const dep = new require_lib_container_ContainerEntryDependency.default(name, exposes, shareScope, federationRuntimePluginInstance.entryFilePath);
dep.loc = { name };
await new Promise((resolve, reject) => {
compilation.addEntry(compilation.options.context || "", dep, {
name,
filename,
runtime,
library
}, (error) => {
if (error) return reject(error);
hooks.addContainerEntryDependency.call(dep);
resolve(void 0);
});
}).catch(callback);
await new Promise((resolve, reject) => {
compilation.addInclude(compiler.context, federationRuntimeDependency, { name: void 0 }, (err, module) => {
if (err) return reject(err);
hooks.addFederationRuntimeDependency.call(federationRuntimeDependency);
resolve(void 0);
});
}).catch(callback);
callback();
});
compiler.hooks.finishMake.tapAsync(PLUGIN_NAME, (compilation, callback) => {
if (compilation.compiler.parentCompilation && compilation.compiler.parentCompilation !== compilation) return callback();
const hooks = require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation);
const createdRuntimes = /* @__PURE__ */ new Set();
for (const entry of compilation.entries.values()) {
const runtime = entry.options.runtime;
if (runtime) createdRuntimes.add(runtime);
}
if (createdRuntimes.size === 0 && !compilation.options?.optimization?.runtimeChunk) return callback();
const dep = new require_lib_container_ContainerEntryDependency.default(name, exposes, shareScope, federationRuntimePluginInstance.entryFilePath);
dep.loc = { name };
compilation.addInclude(compilation.options.context || "", dep, { name: void 0 }, (error) => {
if (error) return callback(error);
hooks.addContainerEntryDependency.call(dep);
callback();
});
});
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(require_lib_container_ContainerEntryDependency.default, new require_lib_container_ContainerEntryModuleFactory.default());
compilation.dependencyFactories.set(require_lib_container_ContainerExposedDependency.default, normalModuleFactory);
if (!compilation.dependencyFactories.has(EntryDependency)) compilation.dependencyFactories.set(EntryDependency, normalModuleFactory);
});
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(require_lib_container_runtime_FederationRuntimeDependency.default, normalModuleFactory);
compilation.dependencyTemplates.set(require_lib_container_runtime_FederationRuntimeDependency.default, new ModuleDependency.Template());
});
}
};
//#endregion
exports.default = ContainerPlugin;
//# sourceMappingURL=ContainerPlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import { containerReferencePlugin } from "@module-federation/sdk";
import { Compiler } from "webpack";
//#region src/lib/container/ContainerReferencePlugin.d.ts
declare class ContainerReferencePlugin {
private _remoteType;
private _remotes;
constructor(options: containerReferencePlugin.ContainerReferencePluginOptions);
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler: Compiler): void;
}
//#endregion
export { ContainerReferencePlugin as default };
//# sourceMappingURL=ContainerReferencePlugin.d.ts.map

View File

@@ -0,0 +1,75 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_options = require('./options.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./runtime/FederationModulesPlugin.js');
const require_lib_container_runtime_FederationRuntimePlugin = require('./runtime/FederationRuntimePlugin.js');
const require_lib_container_FallbackDependency = require('./FallbackDependency.js');
const require_lib_container_FallbackItemDependency = require('./FallbackItemDependency.js');
const require_lib_container_FallbackModuleFactory = require('./FallbackModuleFactory.js');
const require_lib_container_RemoteToExternalDependency = require('./RemoteToExternalDependency.js');
const require_lib_container_RemoteModule = require('./RemoteModule.js');
const require_lib_container_RemoteRuntimeModule = require('./RemoteRuntimeModule.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/ContainerReferencePlugin.ts
const { ExternalsPlugin } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const slashCode = "/".charCodeAt(0);
var ContainerReferencePlugin = class {
constructor(options) {
this._remoteType = options.remoteType;
this._remotes = require_lib_container_options.parseOptions(options.remotes, (item) => ({
external: Array.isArray(item) ? item : [item],
shareScope: options.shareScope || "default"
}), (item) => ({
external: Array.isArray(item.external) ? item.external : [item.external],
shareScope: item.shareScope || options.shareScope || "default"
}));
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { _remotes: remotes, _remoteType: remoteType } = this;
new require_lib_container_runtime_FederationRuntimePlugin.default().apply(compiler);
/** @type {Record<string, string>} */
const remoteExternals = {};
for (const [key, config] of remotes) {
let i = 0;
for (const external of config.external) {
if (typeof external === "string" && external.startsWith("internal ")) continue;
remoteExternals[`webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}`] = external;
i++;
}
}
new (compiler.webpack.ExternalsPlugin || ExternalsPlugin)(remoteType, remoteExternals).apply(compiler);
compiler.hooks.compilation.tap("ContainerReferencePlugin", (compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(require_lib_container_RemoteToExternalDependency.default, normalModuleFactory);
compilation.dependencyFactories.set(require_lib_container_FallbackItemDependency.default, normalModuleFactory);
compilation.dependencyFactories.set(require_lib_container_FallbackDependency.default, new require_lib_container_FallbackModuleFactory.default());
const hooks = require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation);
normalModuleFactory.hooks.factorize.tap("ContainerReferencePlugin", (data) => {
if (!data.request.includes("!")) {
for (const [key, config] of remotes) if (data.request.startsWith(`${key}`) && (data.request.length === key.length || data.request.charCodeAt(key.length) === slashCode)) {
const remoteModule = new require_lib_container_RemoteModule.default(data.request, config.external.map((external, i) => external.startsWith("internal ") ? external.slice(9) : `webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}`), `.${data.request.slice(key.length)}`, config.shareScope);
hooks.addRemoteDependency.call(remoteModule);
return remoteModule;
}
}
});
compilation.hooks.runtimeRequirementInTree.for(compiler.webpack.RuntimeGlobals.ensureChunkHandlers).tap("ContainerReferencePlugin", (chunk, set) => {
set.add(compiler.webpack.RuntimeGlobals.module);
set.add(compiler.webpack.RuntimeGlobals.moduleFactoriesAddOnly);
set.add(compiler.webpack.RuntimeGlobals.hasOwnProperty);
set.add(compiler.webpack.RuntimeGlobals.initializeSharing);
set.add(compiler.webpack.RuntimeGlobals.shareScopeMap);
compilation.addRuntimeModule(chunk, new require_lib_container_RemoteRuntimeModule.default());
});
});
}
};
//#endregion
exports.default = ContainerReferencePlugin;
//# sourceMappingURL=ContainerReferencePlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
import * as webpack$1 from "webpack";
import { ObjectDeserializerContext, ObjectSerializerContext } from "webpack/lib/Dependency";
//#region src/lib/container/FallbackDependency.d.ts
declare const Dependency: typeof webpack$1.Dependency;
declare class FallbackDependency extends Dependency {
requests: string[];
/**
* @param {string[]} requests requests
*/
constructor(requests: string[]);
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier(): string | null;
get type(): string;
get category(): string;
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context: ObjectSerializerContext): void;
static deserialize(context: ObjectDeserializerContext): FallbackDependency;
}
//#endregion
export { FallbackDependency as default };
//# sourceMappingURL=FallbackDependency.d.ts.map

View File

@@ -0,0 +1,49 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/FallbackDependency.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { Dependency } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var FallbackDependency = class FallbackDependency extends Dependency {
/**
* @param {string[]} requests requests
*/
constructor(requests) {
super();
this.requests = requests;
}
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier() {
return `fallback ${this.requests.join(" ")}`;
}
get type() {
return "fallback";
}
get category() {
return "esm";
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.requests);
super.serialize(context);
}
static deserialize(context) {
const { read } = context;
const obj = new FallbackDependency(read());
obj.deserialize(context);
return obj;
}
};
makeSerializable(FallbackDependency, "enhanced/lib/container/FallbackDependency");
//#endregion
exports.default = FallbackDependency;
//# sourceMappingURL=FallbackDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"FallbackDependency.js","names":[],"sources":["../../../../src/lib/container/FallbackDependency.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy\n*/\n\n'use strict';\n\nimport type {\n ObjectDeserializerContext,\n ObjectSerializerContext,\n} from 'webpack/lib/Dependency';\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst makeSerializable = require(\n normalizeWebpackPath('webpack/lib/util/makeSerializable'),\n);\nconst { Dependency } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass FallbackDependency extends Dependency {\n requests: string[];\n\n /**\n * @param {string[]} requests requests\n */\n constructor(requests: string[]) {\n super();\n this.requests = requests;\n }\n\n /**\n * @returns {string | null} an identifier to merge equal requests\n */\n override getResourceIdentifier(): string | null {\n return `fallback ${this.requests.join(' ')}`;\n }\n\n override get type(): string {\n return 'fallback';\n }\n\n override get category(): string {\n return 'esm';\n }\n\n /**\n * @param {ObjectSerializerContext} context context\n */\n override serialize(context: ObjectSerializerContext): void {\n const { write } = context;\n write(this.requests);\n super.serialize(context);\n }\n\n static deserialize(context: ObjectDeserializerContext): FallbackDependency {\n const { read } = context;\n const obj = new FallbackDependency(read());\n obj.deserialize(context);\n return obj;\n }\n}\n\nmakeSerializable(\n FallbackDependency,\n 'enhanced/lib/container/FallbackDependency',\n);\n\nexport default FallbackDependency;\n"],"mappings":";;;;;;;AAaA,MAAM,mBAAmB,gFACF,oCAAoC,CAC1D;AACD,MAAM,EAAE,eAAe,gFACA,UAAU,CAChC;AAED,IAAM,qBAAN,MAAM,2BAA2B,WAAW;;;;CAM1C,YAAY,UAAoB;AAC9B,SAAO;AACP,OAAK,WAAW;;;;;CAMlB,AAAS,wBAAuC;AAC9C,SAAO,YAAY,KAAK,SAAS,KAAK,IAAI;;CAG5C,IAAa,OAAe;AAC1B,SAAO;;CAGT,IAAa,WAAmB;AAC9B,SAAO;;;;;CAMT,AAAS,UAAU,SAAwC;EACzD,MAAM,EAAE,UAAU;AAClB,QAAM,KAAK,SAAS;AACpB,QAAM,UAAU,QAAQ;;CAG1B,OAAO,YAAY,SAAwD;EACzE,MAAM,EAAE,SAAS;EACjB,MAAM,MAAM,IAAI,mBAAmB,MAAM,CAAC;AAC1C,MAAI,YAAY,QAAQ;AACxB,SAAO;;;AAIX,iBACE,oBACA,4CACD"}

View File

@@ -0,0 +1,15 @@
import * as webpack$1 from "webpack";
//#region src/lib/container/FallbackItemDependency.d.ts
declare const dependencies: typeof webpack$1.dependencies;
declare class FallbackItemDependency extends dependencies.ModuleDependency {
/**
* @param {string} request request
*/
constructor(request: string);
get type(): string;
get category(): string;
}
//#endregion
export { FallbackItemDependency as default };
//# sourceMappingURL=FallbackItemDependency.d.ts.map

View File

@@ -0,0 +1,26 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/FallbackItemDependency.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { dependencies } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var FallbackItemDependency = class extends dependencies.ModuleDependency {
/**
* @param {string} request request
*/
constructor(request) {
super(request);
}
get type() {
return "fallback item";
}
get category() {
return "esm";
}
};
makeSerializable(FallbackItemDependency, "enhanced/lib/container/FallbackItemDependency");
//#endregion
exports.default = FallbackItemDependency;
//# sourceMappingURL=FallbackItemDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"FallbackItemDependency.js","names":[],"sources":["../../../../src/lib/container/FallbackItemDependency.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy\n*/\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst makeSerializable = require(\n normalizeWebpackPath('webpack/lib/util/makeSerializable'),\n) as typeof import('webpack/lib/util/makeSerializable');\nconst { dependencies } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass FallbackItemDependency extends dependencies.ModuleDependency {\n /**\n * @param {string} request request\n */\n constructor(request: string) {\n super(request);\n }\n\n override get type(): string {\n return 'fallback item';\n }\n\n override get category(): string {\n return 'esm';\n }\n}\n\nmakeSerializable(\n FallbackItemDependency,\n 'enhanced/lib/container/FallbackItemDependency',\n);\n\nexport default FallbackItemDependency;\n"],"mappings":";;;;;AAMA,MAAM,mBAAmB,gFACF,oCAAoC,CAC1D;AACD,MAAM,EAAE,iBAAiB,gFACF,UAAU,CAChC;AAED,IAAM,yBAAN,cAAqC,aAAa,iBAAiB;;;;CAIjE,YAAY,SAAiB;AAC3B,QAAM,QAAQ;;CAGhB,IAAa,OAAe;AAC1B,SAAO;;CAGT,IAAa,WAAmB;AAC9B,SAAO;;;AAIX,iBACE,wBACA,gDACD"}

View File

@@ -0,0 +1,83 @@
import * as webpack$1 from "webpack";
import { Chunk, ChunkGraph } from "webpack";
import { CodeGenerationContext, CodeGenerationResult, Compilation as Compilation$1, InputFileSystem, LibIdentOptions, NeedBuildContext, ObjectDeserializerContext, ObjectSerializerContext, RequestShortener, ResolverWithOptions, WebpackError, WebpackOptions } from "webpack/lib/Module";
//#region src/lib/container/FallbackModule.d.ts
declare const Module$1: typeof webpack$1.Module;
declare class FallbackModule extends Module$1 {
requests: string[];
private _identifier;
/**
* @param {string[]} requests list of requests to choose one
*/
constructor(requests: string[]);
/**
* @returns {string} a unique identifier of the module
*/
identifier(): string;
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener: RequestShortener): string;
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options: LibIdentOptions): string | null;
/**
* @param {Chunk} chunk the chunk which condition should be checked
* @param {Compilation} compilation the compilation
* @returns {boolean} true, if the chunk is ok for the module
*/
chunkCondition(chunk: Chunk, {
chunkGraph
}: {
chunkGraph: ChunkGraph;
}): boolean;
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context: NeedBuildContext, callback: (error: WebpackError | null, result?: boolean) => void): void;
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options: WebpackOptions, compilation: Compilation$1, resolver: ResolverWithOptions, fs: InputFileSystem, callback: (error?: WebpackError) => void): void;
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type?: string): number;
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes(): Set<string>;
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({
runtimeTemplate,
moduleGraph,
chunkGraph
}: CodeGenerationContext): CodeGenerationResult;
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context: ObjectSerializerContext): void;
/**
* @param {ObjectDeserializerContext} context context
* @returns {FallbackModule} deserialized fallback module
*/
static deserialize(context: ObjectDeserializerContext): FallbackModule;
}
//#endregion
export { FallbackModule as default };
//# sourceMappingURL=FallbackModule.d.ts.map

View File

@@ -0,0 +1,137 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_Constants = require('../Constants.js');
const require_lib_container_FallbackItemDependency = require('./FallbackItemDependency.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/FallbackModule.ts
const { sources: webpackSources } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const { Template, Module, RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
var FallbackModule = class FallbackModule extends Module {
/**
* @param {string[]} requests list of requests to choose one
*/
constructor(requests) {
super(require_lib_Constants.WEBPACK_MODULE_TYPE_FALLBACK);
this.requests = requests;
this._identifier = `fallback ${this.requests.join(" ")}`;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return this._identifier;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return this._identifier;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${this.requests[0]}/and ${this.requests.length - 1} more`;
}
/**
* @param {Chunk} chunk the chunk which condition should be checked
* @param {Compilation} compilation the compilation
* @returns {boolean} true, if the chunk is ok for the module
*/
chunkCondition(chunk, { chunkGraph }) {
return chunkGraph.getNumberOfEntryModules(chunk) > 0;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
callback(null, !this.buildInfo);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = { strict: true };
this.clearDependenciesAndBlocks();
for (const request of this.requests) this.addDependency(new require_lib_container_FallbackItemDependency.default(request));
callback();
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return this.requests.length * 5 + 42;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
const ids = this.dependencies.map((dep) => chunkGraph.getModuleId(moduleGraph.getModule(dep)));
const code = Template.asString([
`var ids = ${JSON.stringify(ids)};`,
"var error, result, i = 0;",
`var loop = ${runtimeTemplate.basicFunction("next", [
"while(i < ids.length) {",
Template.indent([`try { next = ${RuntimeGlobals.require}(ids[i++]); } catch(e) { return handleError(e); }`, "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);"]),
"}",
"if(error) throw error;"
])}`,
`var handleResult = ${runtimeTemplate.basicFunction("result", ["if(result) return result;", "return loop();"])};`,
`var handleError = ${runtimeTemplate.basicFunction("e", ["error = e;", "return loop();"])};`,
"module.exports = loop();"
]);
const sources = /* @__PURE__ */ new Map();
sources.set("javascript", new webpackSources.RawSource(code));
return {
sources,
runtimeRequirements: RUNTIME_REQUIREMENTS
};
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.requests);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
* @returns {FallbackModule} deserialized fallback module
*/
static deserialize(context) {
const { read } = context;
const obj = new FallbackModule(read());
obj.deserialize(context);
return obj;
}
};
makeSerializable(FallbackModule, "enhanced/lib/container/FallbackModule");
//#endregion
exports.default = FallbackModule;
//# sourceMappingURL=FallbackModule.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,16 @@
import * as webpack_lib_ModuleFactory0 from "webpack/lib/ModuleFactory";
import { ModuleFactoryCreateData, ModuleFactoryResult } from "webpack/lib/ModuleFactory";
//#region src/lib/container/FallbackModuleFactory.d.ts
declare const ModuleFactory: typeof webpack_lib_ModuleFactory0;
declare class FallbackModuleFactory extends ModuleFactory {
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data: ModuleFactoryCreateData, callback: (error: Error | null, result?: ModuleFactoryResult) => void): void;
}
//#endregion
export { FallbackModuleFactory as default };
//# sourceMappingURL=FallbackModuleFactory.d.ts.map

View File

@@ -0,0 +1,24 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_FallbackModule = require('./FallbackModule.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/FallbackModuleFactory.ts
const ModuleFactory = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/ModuleFactory"));
var FallbackModuleFactory = class extends ModuleFactory {
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
const dependency = data.dependencies[0];
callback(null, { module: new require_lib_container_FallbackModule.default(dependency.requests) });
}
};
//#endregion
exports.default = FallbackModuleFactory;
//# sourceMappingURL=FallbackModuleFactory.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"FallbackModuleFactory.js","names":["FallbackModule"],"sources":["../../../../src/lib/container/FallbackModuleFactory.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr\n*/\n\n'use strict';\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\nimport type {\n ModuleFactoryCreateData,\n ModuleFactoryResult,\n} from 'webpack/lib/ModuleFactory';\nimport FallbackModule from './FallbackModule';\n\nconst ModuleFactory = require(\n normalizeWebpackPath('webpack/lib/ModuleFactory'),\n) as typeof import('webpack/lib/ModuleFactory');\n\nexport default class FallbackModuleFactory extends ModuleFactory {\n /**\n * @param {ModuleFactoryCreateData} data data object\n * @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback\n * @returns {void}\n */\n override create(\n data: ModuleFactoryCreateData,\n callback: (error: Error | null, result?: ModuleFactoryResult) => void,\n ): void {\n const dependency = data.dependencies[0];\n callback(null, {\n // @ts-expect-error Module !== FallbackModule\n module: new FallbackModule(dependency.requests),\n });\n }\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,gBAAgB,gFACC,4BAA4B,CAClD;AAED,IAAqB,wBAArB,cAAmD,cAAc;;;;;;CAM/D,AAAS,OACP,MACA,UACM;EACN,MAAM,aAAa,KAAK,aAAa;AACrC,WAAS,MAAM,EAEb,QAAQ,IAAIA,6CAAe,WAAW,SAAS,EAChD,CAAC"}

View File

@@ -0,0 +1,16 @@
import { Compilation, Compiler, Module, WebpackPluginInstance } from "webpack";
//#region src/lib/container/HoistContainerReferencesPlugin.d.ts
/**
* This plugin hoists container-related modules into runtime chunks when using runtimeChunk: single configuration.
*/
declare class HoistContainerReferences implements WebpackPluginInstance {
apply(compiler: Compiler): void;
private hoistModulesInChunks;
private cleanUpChunks;
private getRuntimeChunks;
}
declare function getAllReferencedModules(compilation: Compilation, module: Module, type?: 'all' | 'initial' | 'external'): Set<Module>;
//#endregion
export { HoistContainerReferences as default, getAllReferencedModules };
//# sourceMappingURL=HoistContainerReferencesPlugin.d.ts.map

View File

@@ -0,0 +1,129 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./runtime/FederationModulesPlugin.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/HoistContainerReferencesPlugin.ts
const { AsyncDependenciesBlock, ExternalModule } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const PLUGIN_NAME = "HoistContainerReferences";
/**
* This plugin hoists container-related modules into runtime chunks when using runtimeChunk: single configuration.
*/
var HoistContainerReferences = class {
apply(compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const logger = compilation.getLogger(PLUGIN_NAME);
const hooks = require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation);
const containerEntryDependencies = /* @__PURE__ */ new Set();
const federationRuntimeDependencies = /* @__PURE__ */ new Set();
const remoteDependencies = /* @__PURE__ */ new Set();
hooks.addContainerEntryDependency.tap("HoistContainerReferences", (dep) => {
containerEntryDependencies.add(dep);
});
hooks.addFederationRuntimeDependency.tap("HoistContainerReferences", (dep) => {
federationRuntimeDependencies.add(dep);
});
hooks.addRemoteDependency.tap("HoistContainerReferences", (dep) => {
remoteDependencies.add(dep);
});
compilation.hooks.optimizeChunks.tap({
name: PLUGIN_NAME,
stage: 11
}, (chunks) => {
const runtimeChunks = this.getRuntimeChunks(compilation);
this.hoistModulesInChunks(compilation, runtimeChunks, logger, containerEntryDependencies, federationRuntimeDependencies, remoteDependencies);
});
});
}
hoistModulesInChunks(compilation, runtimeChunks, logger, containerEntryDependencies, federationRuntimeDependencies, remoteDependencies) {
const { chunkGraph, moduleGraph } = compilation;
const allModulesToHoist = /* @__PURE__ */ new Set();
for (const dep of containerEntryDependencies) {
const containerEntryModule = moduleGraph.getModule(dep);
if (!containerEntryModule) continue;
const referencedModules = getAllReferencedModules(compilation, containerEntryModule, "initial");
referencedModules.forEach((m) => allModulesToHoist.add(m));
const moduleRuntimes = chunkGraph.getModuleRuntimes(containerEntryModule);
const runtimes = /* @__PURE__ */ new Set();
for (const runtimeSpec of moduleRuntimes) compilation.compiler.webpack.util.runtime.forEachRuntime(runtimeSpec, (runtimeKey) => {
if (runtimeKey) runtimes.add(runtimeKey);
});
for (const runtime of runtimes) {
const runtimeChunk = compilation.namedChunks.get(runtime);
if (!runtimeChunk) continue;
for (const module of referencedModules) if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) chunkGraph.connectChunkAndModule(runtimeChunk, module);
}
}
for (const dep of federationRuntimeDependencies) {
const runtimeModule = moduleGraph.getModule(dep);
if (!runtimeModule) continue;
const referencedModules = getAllReferencedModules(compilation, runtimeModule, "initial");
referencedModules.forEach((m) => allModulesToHoist.add(m));
const moduleRuntimes = chunkGraph.getModuleRuntimes(runtimeModule);
const runtimes = /* @__PURE__ */ new Set();
for (const runtimeSpec of moduleRuntimes) compilation.compiler.webpack.util.runtime.forEachRuntime(runtimeSpec, (runtimeKey) => {
if (runtimeKey) runtimes.add(runtimeKey);
});
for (const runtime of runtimes) {
const runtimeChunk = compilation.namedChunks.get(runtime);
if (!runtimeChunk) continue;
for (const module of referencedModules) if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) chunkGraph.connectChunkAndModule(runtimeChunk, module);
}
}
for (const remoteDep of remoteDependencies) {
const remoteModule = moduleGraph.getModule(remoteDep);
if (!remoteModule) continue;
const referencedRemoteModules = getAllReferencedModules(compilation, remoteModule, "initial");
referencedRemoteModules.forEach((m) => allModulesToHoist.add(m));
const remoteModuleRuntimes = chunkGraph.getModuleRuntimes(remoteModule);
const remoteRuntimes = /* @__PURE__ */ new Set();
for (const runtimeSpec of remoteModuleRuntimes) compilation.compiler.webpack.util.runtime.forEachRuntime(runtimeSpec, (runtimeKey) => {
if (runtimeKey) remoteRuntimes.add(runtimeKey);
});
for (const runtime of remoteRuntimes) {
const runtimeChunk = compilation.namedChunks.get(runtime);
if (!runtimeChunk) continue;
for (const module of referencedRemoteModules) if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) chunkGraph.connectChunkAndModule(runtimeChunk, module);
}
}
this.cleanUpChunks(compilation, allModulesToHoist);
}
cleanUpChunks(compilation, modules) {
const { chunkGraph } = compilation;
for (const module of modules) for (const chunk of chunkGraph.getModuleChunks(module)) if (!chunk.hasRuntime()) chunkGraph.disconnectChunkAndModule(chunk, module);
}
getRuntimeChunks(compilation) {
const runtimeChunks = /* @__PURE__ */ new Set();
for (const chunk of compilation.chunks) if (chunk.hasRuntime()) runtimeChunks.add(chunk);
return runtimeChunks;
}
};
function getAllReferencedModules(compilation, module, type) {
const collectedModules = new Set([module]);
const visitedModules = new WeakSet([module]);
const stack = [module];
while (stack.length > 0) {
const currentModule = stack.pop();
if (!currentModule) continue;
const mgm = compilation.moduleGraph._getModuleGraphModule(currentModule);
if (!mgm?.outgoingConnections) continue;
for (const connection of mgm.outgoingConnections) {
const connectedModule = connection.module;
if (!connectedModule || visitedModules.has(connectedModule)) continue;
if (type === "initial") {
if (compilation.moduleGraph.getParentBlock(connection.dependency) instanceof AsyncDependenciesBlock) continue;
}
if (type === "external") {
if (connection.module instanceof ExternalModule) collectedModules.add(connectedModule);
} else collectedModules.add(connectedModule);
visitedModules.add(connectedModule);
stack.push(connectedModule);
}
}
return collectedModules;
}
//#endregion
exports.default = HoistContainerReferences;
exports.getAllReferencedModules = getAllReferencedModules;
//# sourceMappingURL=HoistContainerReferencesPlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
import { moduleFederationPlugin } from "@module-federation/sdk";
import { Compiler, WebpackPluginInstance } from "webpack";
//#region src/lib/container/ModuleFederationPlugin.d.ts
declare class ModuleFederationPlugin implements WebpackPluginInstance {
private _options;
private _statsPlugin?;
/**
* @param {moduleFederationPlugin.ModuleFederationPluginOptions} options options
*/
constructor(options: moduleFederationPlugin.ModuleFederationPluginOptions);
private _patchBundlerConfig;
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler: Compiler): void;
}
//#endregion
export { ModuleFederationPlugin as default };
//# sourceMappingURL=ModuleFederationPlugin.d.ts.map

View File

@@ -0,0 +1,145 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_utils = require('../../utils.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./runtime/FederationModulesPlugin.js');
const require_lib_container_runtime_FederationRuntimePlugin = require('./runtime/FederationRuntimePlugin.js');
const require_lib_container_ContainerPlugin = require('./ContainerPlugin.js');
const require_lib_container_ContainerReferencePlugin = require('./ContainerReferencePlugin.js');
const require_lib_sharing_SharePlugin = require('../sharing/SharePlugin.js');
const require_lib_startup_MfStartupChunkDependenciesPlugin = require('../startup/MfStartupChunkDependenciesPlugin.js');
const require_lib_sharing_tree_shaking_TreeShakingSharedPlugin = require('../sharing/tree-shaking/TreeShakingSharedPlugin.js');
const require_schemas_container_ModuleFederationPlugin_check = require('../../schemas/container/ModuleFederationPlugin.check.js');
const require_schemas_container_ModuleFederationPlugin = require('../../schemas/container/ModuleFederationPlugin.js');
let _module_federation_sdk = require("@module-federation/sdk");
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path);
let node_fs = require("node:fs");
node_fs = require_runtime.__toESM(node_fs);
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
let _module_federation_dts_plugin = require("@module-federation/dts-plugin");
let _module_federation_managers = require("@module-federation/managers");
let _module_federation_manifest = require("@module-federation/manifest");
let _module_federation_rspack_remote_entry_plugin = require("@module-federation/rspack/remote-entry-plugin");
//#region src/lib/container/ModuleFederationPlugin.ts
const isValidExternalsType = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/schemas/plugins/container/ExternalsType.check.js"));
const { ExternalsPlugin } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const validate = require_utils.createSchemaValidation((require_schemas_container_ModuleFederationPlugin_check.init_ModuleFederationPlugin_check(), require_runtime.__toCommonJS(require_schemas_container_ModuleFederationPlugin_check.ModuleFederationPlugin_check_exports)).validate, () => (require_schemas_container_ModuleFederationPlugin.init_ModuleFederationPlugin(), require_runtime.__toCommonJS(require_schemas_container_ModuleFederationPlugin.ModuleFederationPlugin_exports)).default, {
name: "Module Federation Plugin",
baseDataPath: "options"
});
function getEnhancedPackageVersion() {
let currentDir = __dirname;
while (true) {
const packageJsonPath = node_path.default.join(currentDir, "package.json");
if (node_fs.default.existsSync(packageJsonPath)) {
const pkg = JSON.parse(node_fs.default.readFileSync(packageJsonPath, "utf-8"));
if (pkg.name === "@module-federation/enhanced" && pkg.version) return pkg.version;
}
const parentDir = node_path.default.dirname(currentDir);
if (parentDir === currentDir) break;
currentDir = parentDir;
}
throw new Error("Unable to resolve @module-federation/enhanced package.json");
}
var ModuleFederationPlugin = class {
/**
* @param {moduleFederationPlugin.ModuleFederationPluginOptions} options options
*/
constructor(options) {
validate(options);
this._options = options;
}
_patchBundlerConfig(compiler) {
const { name, experiments } = this._options;
const definePluginOptions = {};
const MFPluginNum = compiler.options.plugins.filter((p) => !!p && p.name === "ModuleFederationPlugin").length;
if (name && MFPluginNum < 2) definePluginOptions["FEDERATION_BUILD_IDENTIFIER"] = JSON.stringify((0, _module_federation_sdk.composeKeyWithSeparator)(name, _module_federation_managers.utils.getBuildVersion()));
definePluginOptions["FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN"] = experiments?.optimization?.disableSnapshot ?? false;
if (experiments?.optimization && typeof experiments.optimization === "object" && experiments.optimization !== null && "target" in experiments.optimization) {
const manualTarget = experiments.optimization.target;
if (manualTarget === "web" || manualTarget === "node") definePluginOptions["ENV_TARGET"] = JSON.stringify(manualTarget);
}
new compiler.webpack.DefinePlugin(definePluginOptions).apply(compiler);
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
(0, _module_federation_sdk.bindLoggerToCompiler)(_module_federation_sdk.infrastructureLogger, compiler, "EnhancedModuleFederationPlugin");
const { _options: options } = this;
const { name, experiments, dts, remotes, shared, shareScope } = options;
if (!name) throw new Error("ModuleFederationPlugin name is required");
new _module_federation_rspack_remote_entry_plugin.RemoteEntryPlugin(options).apply(compiler);
const useContainerPlugin = options.exposes && (Array.isArray(options.exposes) ? options.exposes.length > 0 : Object.keys(options.exposes).length > 0);
if (experiments?.provideExternalRuntime) {
if (useContainerPlugin) throw new Error("You can only set provideExternalRuntime: true in pure consumer which not expose modules.");
options.runtimePlugins = (options.runtimePlugins || []).concat(require.resolve("@module-federation/inject-external-runtime-core-plugin"));
}
if (experiments?.externalRuntime === true) new (compiler.webpack.ExternalsPlugin || ExternalsPlugin)(compiler.options.externalsType || "global", { "@module-federation/runtime-core": "_FEDERATION_RUNTIME_CORE" }).apply(compiler);
new require_lib_container_runtime_FederationModulesPlugin.default().apply(compiler);
if (experiments?.asyncStartup) new require_lib_startup_MfStartupChunkDependenciesPlugin.default({ asyncChunkLoading: true }).apply(compiler);
if (dts !== false) {
const dtsPlugin = new _module_federation_dts_plugin.DtsPlugin(options);
dtsPlugin.apply(compiler);
dtsPlugin.addRuntimePlugins();
}
new require_lib_container_runtime_FederationRuntimePlugin.default(options).apply(compiler);
const library = options.library || {
type: "var",
name
};
const containerRemoteType = options.remoteType || (options.library && isValidExternalsType(options.library.type) ? options.library.type : "script");
let disableManifest = options.manifest === false;
if (useContainerPlugin) require_lib_container_ContainerPlugin.default.patchChunkSplit(compiler, name);
this._patchBundlerConfig(compiler);
if (!disableManifest && useContainerPlugin) try {
const containerManager = new _module_federation_managers.ContainerManager();
containerManager.init(options);
options.exposes = containerManager.containerPluginExposesOptions;
} catch (err) {
if (err instanceof Error) err.message = `[ ModuleFederationPlugin ]: Manifest will not generate, because: ${err.message}`;
_module_federation_sdk.infrastructureLogger.warn(err);
disableManifest = true;
}
if (library && !compiler.options.output.enabledLibraryTypes?.includes(library.type)) compiler.options.output.enabledLibraryTypes?.push(library.type);
compiler.hooks.afterPlugins.tap("ModuleFederationPlugin", () => {
if (useContainerPlugin) new require_lib_container_ContainerPlugin.default({
name,
library,
filename: options.filename,
runtime: options.runtime,
shareScope: options.shareScope,
exposes: options.exposes,
runtimePlugins: options.runtimePlugins
}).apply(compiler);
if (remotes && (Array.isArray(remotes) ? remotes.length > 0 : Object.keys(remotes).length > 0)) new require_lib_container_ContainerReferencePlugin.default({
remoteType: containerRemoteType,
shareScope,
remotes
}).apply(compiler);
if (shared) {
new require_lib_sharing_tree_shaking_TreeShakingSharedPlugin.default({ mfConfig: options }).apply(compiler);
new require_lib_sharing_SharePlugin.default({
shared,
shareScope
}).apply(compiler);
}
});
if (!disableManifest) {
this._statsPlugin = new _module_federation_manifest.StatsPlugin(options, {
pluginVersion: getEnhancedPackageVersion(),
bundler: "webpack"
});
this._statsPlugin.apply(compiler);
}
}
};
//#endregion
exports.default = ModuleFederationPlugin;
//# sourceMappingURL=ModuleFederationPlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,84 @@
import * as webpack$1 from "webpack";
import { Compilation, WebpackOptionsNormalized } from "webpack";
import { CodeGenerationContext, CodeGenerationResult, LibIdentOptions, NeedBuildContext, WebpackError } from "webpack/lib/Module";
import { ResolverWithOptions as ResolverWithOptions$1 } from "webpack/lib/ResolverFactory";
import { InputFileSystem as InputFileSystem$1 } from "webpack/lib/FileSystemInfo";
import { RequestShortener as RequestShortener$1 } from "webpack/lib/RuntimeModule";
import { ObjectDeserializerContext as ObjectDeserializerContext$1 } from "webpack/lib/serialization/ObjectMiddleware";
//#region src/lib/container/RemoteModule.d.ts
declare const Module$1: typeof webpack$1.Module;
declare class RemoteModule extends Module$1 {
private _identifier;
request: string;
externalRequests: string[];
internalRequest: string;
shareScope: string | string[];
/**
* @param {string} request request string
* @param {string[]} externalRequests list of external requests to containers
* @param {string} internalRequest name of exposed module in container
* @param {string|string[]} shareScope scope in which modules are shared
*/
constructor(request: string, externalRequests: string[], internalRequest: string, shareScope: string | string[]);
/**
* @returns {string} a unique identifier of the module
*/
identifier(): string;
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener: RequestShortener$1): string;
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options: LibIdentOptions): string | null;
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context: NeedBuildContext, callback: (err: WebpackError | null, needsRebuild?: boolean) => void): void;
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options: WebpackOptionsNormalized, compilation: Compilation, resolver: ResolverWithOptions$1, fs: InputFileSystem$1, callback: (err?: WebpackError | undefined) => void): void;
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type?: string): number;
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes(): Set<string>;
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceBasicTypes(): Set<string>;
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition(): string | null;
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration(context: CodeGenerationContext): CodeGenerationResult;
serialize(context: any): void;
/**
* @param {ObjectDeserializerContext} context context
* @returns {RemoteModule} deserialized module
*/
static deserialize(context: ObjectDeserializerContext$1): RemoteModule;
}
//#endregion
export { RemoteModule as default };
//# sourceMappingURL=RemoteModule.d.ts.map

View File

@@ -0,0 +1,152 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_Constants = require('../Constants.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./runtime/FederationModulesPlugin.js');
const require_lib_container_FallbackDependency = require('./FallbackDependency.js');
const require_lib_container_RemoteToExternalDependency = require('./RemoteToExternalDependency.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/RemoteModule.ts
const { sources: webpackSources } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const { Module, RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const TYPES = new Set(["remote", "share-init"]);
const JAVASCRIPT_TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
var RemoteModule = class RemoteModule extends Module {
/**
* @param {string} request request string
* @param {string[]} externalRequests list of external requests to containers
* @param {string} internalRequest name of exposed module in container
* @param {string|string[]} shareScope scope in which modules are shared
*/
constructor(request, externalRequests, internalRequest, shareScope) {
super(require_lib_Constants.WEBPACK_MODULE_TYPE_REMOTE);
this.request = request;
this.externalRequests = externalRequests;
this.internalRequest = internalRequest;
this.shareScope = shareScope;
this._identifier = `remote (${Array.isArray(shareScope) ? shareScope.join("|") : shareScope}) ${this.externalRequests.join(" ")} ${this.internalRequest}`;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return this._identifier;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `remote ${this.request}`;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${this.request}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
callback(null, !this.buildInfo);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = { strict: true };
this.clearDependenciesAndBlocks();
if (this.externalRequests.length === 1) {
const dep = new require_lib_container_RemoteToExternalDependency.default(this.externalRequests[0]);
this.addDependency(dep);
require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation).addRemoteDependency.call(dep);
} else {
const dep = new require_lib_container_FallbackDependency.default(this.externalRequests);
this.addDependency(dep);
require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation).addRemoteDependency.call(dep);
}
callback();
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 6;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceBasicTypes() {
return JAVASCRIPT_TYPES;
}
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition() {
return this.request;
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration(context) {
const { moduleGraph, chunkGraph } = context;
const module = moduleGraph.getModule(this.dependencies[0]);
const id = module && chunkGraph.getModuleId(module);
const sources = /* @__PURE__ */ new Map();
sources.set("remote", new webpackSources.RawSource(""));
const data = /* @__PURE__ */ new Map();
data.set("share-init", [{
shareScope: this.shareScope,
initStage: 20,
init: id === void 0 ? "" : `initExternal(${JSON.stringify(id)});`
}]);
return {
sources,
data,
runtimeRequirements: RUNTIME_REQUIREMENTS
};
}
serialize(context) {
const { write } = context;
write(this.request);
write(this.externalRequests);
write(this.internalRequest);
write(this.shareScope);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
* @returns {RemoteModule} deserialized module
*/
static deserialize(context) {
const { read } = context;
const obj = new RemoteModule(read(), read(), read(), read());
obj.deserialize(context);
return obj;
}
};
makeSerializable(RemoteModule, "enhanced/lib/container/RemoteModule");
//#endregion
exports.default = RemoteModule;
//# sourceMappingURL=RemoteModule.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
import * as webpack$1 from "webpack";
//#region src/lib/container/RemoteRuntimeModule.d.ts
declare const RuntimeModule: typeof webpack$1.RuntimeModule;
declare class RemoteRuntimeModule extends RuntimeModule {
constructor();
/**
* @returns {string | null} runtime code
*/
generate(): string | null;
}
//#endregion
export { RemoteRuntimeModule as default };
//# sourceMappingURL=RemoteRuntimeModule.d.ts.map

View File

@@ -0,0 +1,88 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_runtime_utils = require('./runtime/utils.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/RemoteRuntimeModule.ts
const extractUrlAndGlobal = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/extractUrlAndGlobal"));
const { Template, RuntimeModule, RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var RemoteRuntimeModule = class extends RuntimeModule {
constructor() {
super("remotes loading");
}
/**
* @returns {string | null} runtime code
*/
generate() {
const { compilation, chunkGraph } = this;
const { runtimeTemplate, moduleGraph } = compilation;
const chunkToRemotesMapping = {};
const idToExternalAndNameMapping = {};
const idToRemoteMap = {};
const moduleIdToRemoteDataMapping = {};
const allChunks = [...Array.from(this.chunk?.getAllReferencedChunks() || [])];
for (const chunk of allChunks) {
if (chunk.id === null || chunk.id === void 0) continue;
const modules = chunkGraph?.getChunkModulesIterableBySourceType(chunk, "remote");
if (!modules) continue;
const remotes = chunkToRemotesMapping[chunk.id] = [];
for (const m of modules) {
const module = m;
const name = module.internalRequest;
const id = chunkGraph ? chunkGraph.getModuleId(module) : void 0;
const { shareScope } = module;
const dep = module.dependencies[0];
const externalModule = moduleGraph.getModule(dep);
const externalModuleId = chunkGraph && externalModule ? chunkGraph.getModuleId(externalModule) : void 0;
if (id !== void 0 && id !== null) {
remotes.push(id);
idToExternalAndNameMapping[id] = [
shareScope,
name,
externalModuleId === null || externalModuleId === void 0 ? void 0 : externalModuleId
];
const remoteModules = [];
if ("requests" in externalModule && externalModule.requests) externalModule.dependencies.forEach((dependency) => {
const remoteModule = moduleGraph.getModule(dependency);
if (remoteModule) remoteModules.push(remoteModule);
});
else remoteModules.push(externalModule);
idToRemoteMap[id] = [];
remoteModules.forEach((remoteModule) => {
let remoteName = "";
try {
const [_url, name] = extractUrlAndGlobal(remoteModule.request);
remoteName = name;
} catch (err) {}
const externalModuleId = chunkGraph && remoteModule && chunkGraph.getModuleId(remoteModule);
idToRemoteMap[id].push({
externalType: remoteModule.externalType,
name: remoteModule.externalType === "script" ? remoteName : ""
});
if (externalModuleId !== null && externalModuleId !== void 0) moduleIdToRemoteDataMapping[id] = {
shareScope,
name,
externalModuleId,
remoteName
};
});
}
}
}
const federationGlobal = require_lib_container_runtime_utils.getFederationGlobalScope(RuntimeGlobals || {});
return Template.asString([
`var chunkMapping = ${JSON.stringify(chunkToRemotesMapping, null, " ")};`,
`var idToExternalAndNameMapping = ${JSON.stringify(idToExternalAndNameMapping, null, " ")};`,
`var idToRemoteMap = ${JSON.stringify(idToRemoteMap, null, " ")};`,
`${federationGlobal}.bundlerRuntimeOptions.remotes.chunkMapping = chunkMapping;`,
`${federationGlobal}.bundlerRuntimeOptions.remotes.idToExternalAndNameMapping = idToExternalAndNameMapping;`,
`${federationGlobal}.bundlerRuntimeOptions.remotes.idToRemoteMap = idToRemoteMap;`,
`${RuntimeGlobals.require}.remotesLoadingData.moduleIdToRemoteDataMapping = ${JSON.stringify(moduleIdToRemoteDataMapping, null, " ")};`,
`${RuntimeGlobals.ensureChunkHandlers}.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [`${federationGlobal}.bundlerRuntime.remotes({idToRemoteMap,chunkMapping, idToExternalAndNameMapping, chunkId, promises, webpackRequire:${RuntimeGlobals.require}});`])}`
]);
}
};
//#endregion
exports.default = RemoteRuntimeModule;
//# sourceMappingURL=RemoteRuntimeModule.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import * as webpack$1 from "webpack";
//#region src/lib/container/RemoteToExternalDependency.d.ts
declare const dependencies: typeof webpack$1.dependencies;
declare class RemoteToExternalDependency extends dependencies.ModuleDependency {
/**
* @param {string} request request
*/
constructor(request: string);
get type(): string;
get category(): string;
}
//#endregion
export { RemoteToExternalDependency as default };
//# sourceMappingURL=RemoteToExternalDependency.d.ts.map

View File

@@ -0,0 +1,28 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/RemoteToExternalDependency.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { dependencies } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var RemoteToExternalDependency = class extends dependencies.ModuleDependency {
/**
* @param {string} request request
*/
constructor(request) {
super(request);
}
get type() {
return "remote to external";
}
get category() {
return "esm";
}
};
makeSerializable(RemoteToExternalDependency, "enhanced/lib/container/RemoteToExternalDependency");
//#endregion
exports.default = RemoteToExternalDependency;
//# sourceMappingURL=RemoteToExternalDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"RemoteToExternalDependency.js","names":[],"sources":["../../../../src/lib/container/RemoteToExternalDependency.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy\n*/\n\n'use strict';\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst makeSerializable = require(\n normalizeWebpackPath('webpack/lib/util/makeSerializable'),\n) as typeof import('webpack/lib/util/makeSerializable');\nconst { dependencies } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass RemoteToExternalDependency extends dependencies.ModuleDependency {\n /**\n * @param {string} request request\n */\n constructor(request: string) {\n super(request);\n }\n override get type() {\n return 'remote to external';\n }\n\n override get category() {\n return 'esm';\n }\n}\n\nmakeSerializable(\n RemoteToExternalDependency,\n 'enhanced/lib/container/RemoteToExternalDependency',\n);\n\nexport default RemoteToExternalDependency;\n"],"mappings":";;;;;;;AAQA,MAAM,mBAAmB,gFACF,oCAAoC,CAC1D;AACD,MAAM,EAAE,iBAAiB,gFACF,UAAU,CAChC;AAED,IAAM,6BAAN,cAAyC,aAAa,iBAAiB;;;;CAIrE,YAAY,SAAiB;AAC3B,QAAM,QAAQ;;CAEhB,IAAa,OAAO;AAClB,SAAO;;CAGT,IAAa,WAAW;AACtB,SAAO;;;AAIX,iBACE,4BACA,oDACD"}

View File

@@ -0,0 +1,6 @@
//#region src/lib/container/constant.d.ts
declare const FEDERATION_SUPPORTED_TYPES: string[];
declare const TEMP_DIR: string;
//#endregion
export { FEDERATION_SUPPORTED_TYPES, TEMP_DIR };
//# sourceMappingURL=constant.d.ts.map

View File

@@ -0,0 +1,14 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk = require("@module-federation/sdk");
let path = require("path");
path = require_runtime.__toESM(path);
//#region src/lib/container/constant.ts
const FEDERATION_SUPPORTED_TYPES = ["script"];
const TEMP_DIR = path.default.join(`${process.cwd()}/node_modules`, _module_federation_sdk.TEMP_DIR);
//#endregion
exports.FEDERATION_SUPPORTED_TYPES = FEDERATION_SUPPORTED_TYPES;
exports.TEMP_DIR = TEMP_DIR;
//# sourceMappingURL=constant.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"constant.js","names":["BasicTempDir"],"sources":["../../../../src/lib/container/constant.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Zackary Jackson @ScriptedAlchemy\n*/\nimport path from 'path';\nimport { TEMP_DIR as BasicTempDir } from '@module-federation/sdk';\n\nconst FEDERATION_SUPPORTED_TYPES = ['script'];\nconst TEMP_DIR = path.join(`${process.cwd()}/node_modules`, BasicTempDir);\n\nexport { FEDERATION_SUPPORTED_TYPES, TEMP_DIR };\n"],"mappings":";;;;;;;AAOA,MAAM,6BAA6B,CAAC,SAAS;AAC7C,MAAM,WAAW,aAAK,KAAK,GAAG,QAAQ,KAAK,CAAC,gBAAgBA,gCAAa"}

View File

@@ -0,0 +1,21 @@
//#region src/lib/container/options.d.ts
type ContainerOptionsFormat<T> = (string | Record<string, string | string[] | T>)[] | Record<string, string | string[] | T>;
/**
* @template T
* @template R
* @param {ContainerOptionsFormat<T>} options options passed by the user
* @param {function(string | string[], string) : R} normalizeSimple normalize a simple item
* @param {function(T, string) : R} normalizeOptions normalize a complex item
* @returns {[string, R][]} parsed options
*/
declare function parseOptions<T, R>(options: ContainerOptionsFormat<T>, normalizeSimple: (item: string | string[], name: string) => R, normalizeOptions: (item: T, name: string) => R): [string, R][];
/**
* @template T
* @param {string} scope scope name
* @param {ContainerOptionsFormat<T>} options options passed by the user
* @returns {Record<string, string | string[] | T>} options to spread or pass
*/
declare function scope<T>(scope: string, options: ContainerOptionsFormat<T>): Record<string, string | string[] | T>;
//#endregion
export { ContainerOptionsFormat, parseOptions, scope };
//# sourceMappingURL=options.d.ts.map

View File

@@ -0,0 +1,62 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
//#region src/lib/container/options.ts
/** @template T @typedef {(string | Record<string, string | string[] | T>)[] | Record<string, string | string[] | T>} ContainerOptionsFormat */
/**
* @template T
* @template N
* @param {ContainerOptionsFormat<T>} options options passed by the user
* @param {function(string | string[], string) : N} normalizeSimple normalize a simple item
* @param {function(T, string) : N} normalizeOptions normalize a complex item
* @param {function(string, N): void} fn processing function
* @returns {void}
*/
const process = (options, normalizeSimple, normalizeOptions, fn) => {
const array = (items) => {
for (const item of items) if (typeof item === "string") fn(item, normalizeSimple(item, item));
else if (item && typeof item === "object") object(item);
else throw new Error("Unexpected options format");
};
const object = (obj) => {
for (const [key, value] of Object.entries(obj)) if (typeof value === "string" || Array.isArray(value)) fn(key, normalizeSimple(value, key));
else fn(key, normalizeOptions(value, key));
};
if (!options) return;
else if (Array.isArray(options)) array(options);
else if (typeof options === "object") object(options);
else throw new Error("Unexpected options format");
};
/**
* @template T
* @template R
* @param {ContainerOptionsFormat<T>} options options passed by the user
* @param {function(string | string[], string) : R} normalizeSimple normalize a simple item
* @param {function(T, string) : R} normalizeOptions normalize a complex item
* @returns {[string, R][]} parsed options
*/
function parseOptions(options, normalizeSimple, normalizeOptions) {
const items = [];
process(options, normalizeSimple, normalizeOptions, (key, value) => {
items.push([key, value]);
});
return items;
}
/**
* @template T
* @param {string} scope scope name
* @param {ContainerOptionsFormat<T>} options options passed by the user
* @returns {Record<string, string | string[] | T>} options to spread or pass
*/
function scope(scope, options) {
const obj = {};
process(options, (item) => item, (item) => item, (key, value) => {
obj[key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}`] = value;
});
return obj;
}
//#endregion
exports.parseOptions = parseOptions;
exports.scope = scope;
//# sourceMappingURL=options.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"options.js","names":[],"sources":["../../../../src/lib/container/options.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy\n*/\nexport type ContainerOptionsFormat<T> =\n | (string | Record<string, string | string[] | T>)[]\n | Record<string, string | string[] | T>;\n\n/** @template T @typedef {(string | Record<string, string | string[] | T>)[] | Record<string, string | string[] | T>} ContainerOptionsFormat */\n\n/**\n * @template T\n * @template N\n * @param {ContainerOptionsFormat<T>} options options passed by the user\n * @param {function(string | string[], string) : N} normalizeSimple normalize a simple item\n * @param {function(T, string) : N} normalizeOptions normalize a complex item\n * @param {function(string, N): void} fn processing function\n * @returns {void}\n */\nconst process = <T, N>(\n options: ContainerOptionsFormat<T>,\n normalizeSimple: (item: string | string[], name: string) => N,\n normalizeOptions: (item: T, name: string) => N,\n fn: (name: string, item: N) => void,\n): void => {\n const array = (\n items: (string | Record<string, string | string[] | T>)[],\n ): void => {\n for (const item of items) {\n if (typeof item === 'string') {\n fn(item, normalizeSimple(item, item));\n } else if (item && typeof item === 'object') {\n object(item as Record<string, string | string[] | T>);\n } else {\n throw new Error('Unexpected options format');\n }\n }\n };\n const object = (obj: Record<string, string | string[] | T>): void => {\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string' || Array.isArray(value)) {\n fn(key, normalizeSimple(value, key));\n } else {\n fn(key, normalizeOptions(value as T, key));\n }\n }\n };\n if (!options) {\n return;\n } else if (Array.isArray(options)) {\n array(options);\n } else if (typeof options === 'object') {\n object(options);\n } else {\n throw new Error('Unexpected options format');\n }\n};\n\n/**\n * @template T\n * @template R\n * @param {ContainerOptionsFormat<T>} options options passed by the user\n * @param {function(string | string[], string) : R} normalizeSimple normalize a simple item\n * @param {function(T, string) : R} normalizeOptions normalize a complex item\n * @returns {[string, R][]} parsed options\n */\nexport function parseOptions<T, R>(\n options: ContainerOptionsFormat<T>,\n normalizeSimple: (item: string | string[], name: string) => R,\n normalizeOptions: (item: T, name: string) => R,\n): [string, R][] {\n const items: [string, R][] = [];\n process(options, normalizeSimple, normalizeOptions, (key, value) => {\n items.push([key, value]);\n });\n return items;\n}\n\n/**\n * @template T\n * @param {string} scope scope name\n * @param {ContainerOptionsFormat<T>} options options passed by the user\n * @returns {Record<string, string | string[] | T>} options to spread or pass\n */\nexport function scope<T>(\n scope: string,\n options: ContainerOptionsFormat<T>,\n): Record<string, string | string[] | T> {\n const obj: Record<string, string | string[] | T> = {};\n process(\n options,\n (item) => item as string | string[] | T,\n (item) => item as string | string[] | T,\n (key, value) => {\n obj[\n key.startsWith('./') ? `${scope}${key.slice(1)}` : `${scope}/${key}`\n ] = value;\n },\n );\n return obj;\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAM,WACJ,SACA,iBACA,kBACA,OACS;CACT,MAAM,SACJ,UACS;AACT,OAAK,MAAM,QAAQ,MACjB,KAAI,OAAO,SAAS,SAClB,IAAG,MAAM,gBAAgB,MAAM,KAAK,CAAC;WAC5B,QAAQ,OAAO,SAAS,SACjC,QAAO,KAA8C;MAErD,OAAM,IAAI,MAAM,4BAA4B;;CAIlD,MAAM,UAAU,QAAqD;AACnE,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,CAC5C,KAAI,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CACnD,IAAG,KAAK,gBAAgB,OAAO,IAAI,CAAC;MAEpC,IAAG,KAAK,iBAAiB,OAAY,IAAI,CAAC;;AAIhD,KAAI,CAAC,QACH;UACS,MAAM,QAAQ,QAAQ,CAC/B,OAAM,QAAQ;UACL,OAAO,YAAY,SAC5B,QAAO,QAAQ;KAEf,OAAM,IAAI,MAAM,4BAA4B;;;;;;;;;;AAYhD,SAAgB,aACd,SACA,iBACA,kBACe;CACf,MAAM,QAAuB,EAAE;AAC/B,SAAQ,SAAS,iBAAiB,mBAAmB,KAAK,UAAU;AAClE,QAAM,KAAK,CAAC,KAAK,MAAM,CAAC;GACxB;AACF,QAAO;;;;;;;;AAST,SAAgB,MACd,OACA,SACuC;CACvC,MAAM,MAA6C,EAAE;AACrD,SACE,UACC,SAAS,OACT,SAAS,OACT,KAAK,UAAU;AACd,MACE,IAAI,WAAW,KAAK,GAAG,GAAG,QAAQ,IAAI,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,SAC7D;GAEP;AACD,QAAO"}

View File

@@ -0,0 +1,16 @@
import ContainerEntryDependency from "../ContainerEntryDependency.js";
import FederationRuntimeDependency from "./FederationRuntimeDependency.js";
import * as webpack$1 from "webpack";
//#region src/lib/container/runtime/EmbedFederationRuntimeModule.d.ts
declare const RuntimeModule: typeof webpack$1.RuntimeModule;
declare class EmbedFederationRuntimeModule extends RuntimeModule {
private containerEntrySet;
_cachedGeneratedCode: string | undefined;
constructor(containerEntrySet: Set<ContainerEntryDependency | FederationRuntimeDependency>);
identifier(): string;
generate(): string | null;
}
//#endregion
export { EmbedFederationRuntimeModule as default };
//# sourceMappingURL=EmbedFederationRuntimeModule.d.ts.map

View File

@@ -0,0 +1,58 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/runtime/EmbedFederationRuntimeModule.ts
const { RuntimeModule, Template, RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var EmbedFederationRuntimeModule = class extends RuntimeModule {
constructor(containerEntrySet) {
super("embed federation", RuntimeModule.STAGE_ATTACH);
this.containerEntrySet = containerEntrySet;
this._cachedGeneratedCode = void 0;
}
identifier() {
return "webpack/runtime/embed/federation";
}
generate() {
if (this._cachedGeneratedCode !== void 0) return this._cachedGeneratedCode;
const { compilation, chunk, chunkGraph } = this;
if (!chunk || !chunkGraph || !compilation) return null;
let found;
if (chunk.name) for (const dep of this.containerEntrySet) {
const mod = compilation.moduleGraph.getModule(dep);
if (mod && compilation.chunkGraph.isModuleInChunk(mod, chunk)) {
found = mod;
break;
}
}
if (!found) return null;
const initRuntimeModuleGetter = compilation.runtimeTemplate.moduleRaw({
module: found,
chunkGraph,
request: found.request,
weak: false,
runtimeRequirements: /* @__PURE__ */ new Set()
});
const result = Template.asString([
`var prevStartup = ${RuntimeGlobals.startup};`,
`var hasRun = false;`,
`${RuntimeGlobals.startup} = ${compilation.runtimeTemplate.basicFunction("", [
`if (!hasRun) {`,
` hasRun = true;`,
` ${initRuntimeModuleGetter};`,
`}`,
`if (typeof prevStartup === 'function') {`,
` return prevStartup();`,
`} else {`,
` console.warn('[Module Federation] prevStartup is not a function, skipping startup execution');`,
`}`
])};`
]);
this._cachedGeneratedCode = result;
return result;
}
};
//#endregion
exports.default = EmbedFederationRuntimeModule;
//# sourceMappingURL=EmbedFederationRuntimeModule.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"EmbedFederationRuntimeModule.js","names":[],"sources":["../../../../../src/lib/container/runtime/EmbedFederationRuntimeModule.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Zackary Jackson @ScriptedAlchemy\n*/\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\nimport ContainerEntryDependency from '../ContainerEntryDependency';\n\nimport type { NormalModule as NormalModuleType } from 'webpack';\nimport type FederationRuntimeDependency from './FederationRuntimeDependency';\n\nconst { RuntimeModule, Template, RuntimeGlobals } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass EmbedFederationRuntimeModule extends RuntimeModule {\n private containerEntrySet: Set<\n ContainerEntryDependency | FederationRuntimeDependency\n >;\n public override _cachedGeneratedCode: string | undefined;\n\n constructor(\n containerEntrySet: Set<\n ContainerEntryDependency | FederationRuntimeDependency\n >,\n ) {\n super('embed federation', RuntimeModule.STAGE_ATTACH);\n this.containerEntrySet = containerEntrySet;\n this._cachedGeneratedCode = undefined;\n }\n\n override identifier() {\n return 'webpack/runtime/embed/federation';\n }\n\n override generate(): string | null {\n if (this._cachedGeneratedCode !== undefined) {\n return this._cachedGeneratedCode;\n }\n const { compilation, chunk, chunkGraph } = this;\n if (!chunk || !chunkGraph || !compilation) {\n return null;\n }\n let found;\n if (chunk.name) {\n for (const dep of this.containerEntrySet) {\n const mod = compilation.moduleGraph.getModule(dep);\n if (mod && compilation.chunkGraph.isModuleInChunk(mod, chunk)) {\n found = mod as NormalModuleType;\n break;\n }\n }\n }\n if (!found) {\n return null;\n }\n const initRuntimeModuleGetter = compilation.runtimeTemplate.moduleRaw({\n module: found,\n chunkGraph,\n request: found.request,\n weak: false,\n runtimeRequirements: new Set(),\n });\n\n const result = Template.asString([\n `var prevStartup = ${RuntimeGlobals.startup};`,\n `var hasRun = false;`,\n `${RuntimeGlobals.startup} = ${compilation.runtimeTemplate.basicFunction(\n '',\n [\n `if (!hasRun) {`,\n ` hasRun = true;`,\n ` ${initRuntimeModuleGetter};`,\n `}`,\n `if (typeof prevStartup === 'function') {`,\n ` return prevStartup();`,\n `} else {`,\n ` console.warn('[Module Federation] prevStartup is not a function, skipping startup execution');`,\n `}`,\n ],\n )};`,\n ]);\n this._cachedGeneratedCode = result;\n return result;\n }\n}\nexport default EmbedFederationRuntimeModule;\n"],"mappings":";;;;;AAUA,MAAM,EAAE,eAAe,UAAU,mBAAmB,gFAC7B,UAAU,CAChC;AAED,IAAM,+BAAN,cAA2C,cAAc;CAMvD,YACE,mBAGA;AACA,QAAM,oBAAoB,cAAc,aAAa;AACrD,OAAK,oBAAoB;AACzB,OAAK,uBAAuB;;CAG9B,AAAS,aAAa;AACpB,SAAO;;CAGT,AAAS,WAA0B;AACjC,MAAI,KAAK,yBAAyB,OAChC,QAAO,KAAK;EAEd,MAAM,EAAE,aAAa,OAAO,eAAe;AAC3C,MAAI,CAAC,SAAS,CAAC,cAAc,CAAC,YAC5B,QAAO;EAET,IAAI;AACJ,MAAI,MAAM,KACR,MAAK,MAAM,OAAO,KAAK,mBAAmB;GACxC,MAAM,MAAM,YAAY,YAAY,UAAU,IAAI;AAClD,OAAI,OAAO,YAAY,WAAW,gBAAgB,KAAK,MAAM,EAAE;AAC7D,YAAQ;AACR;;;AAIN,MAAI,CAAC,MACH,QAAO;EAET,MAAM,0BAA0B,YAAY,gBAAgB,UAAU;GACpE,QAAQ;GACR;GACA,SAAS,MAAM;GACf,MAAM;GACN,qCAAqB,IAAI,KAAK;GAC/B,CAAC;EAEF,MAAM,SAAS,SAAS,SAAS;GAC/B,qBAAqB,eAAe,QAAQ;GAC5C;GACA,GAAG,eAAe,QAAQ,KAAK,YAAY,gBAAgB,cACzD,IACA;IACE;IACA;IACA,KAAK,wBAAwB;IAC7B;IACA;IACA;IACA;IACA;IACA;IACD,CACF,CAAC;GACH,CAAC;AACF,OAAK,uBAAuB;AAC5B,SAAO"}

View File

@@ -0,0 +1,31 @@
import { Compiler } from "webpack";
//#region src/lib/container/runtime/EmbedFederationRuntimePlugin.d.ts
interface EmbedFederationRuntimePluginOptions {
/**
* Whether to enable runtime module embedding for all chunks.
* If false, only chunks that explicitly require it will be embedded.
*/
enableForAllChunks?: boolean;
}
/**
* Plugin that embeds Module Federation runtime code into chunks.
* It ensures proper initialization of federated modules and manages runtime requirements.
*/
declare class EmbedFederationRuntimePlugin {
private readonly options;
private readonly processedChunks;
constructor(options?: EmbedFederationRuntimePluginOptions);
/**
* Determines if runtime embedding should be enabled for a given chunk.
*/
private isEnabledForChunk;
/**
* Checks if a hook has already been tapped by this plugin.
*/
private isHookAlreadyTapped;
apply(compiler: Compiler): void;
}
//#endregion
export { EmbedFederationRuntimePlugin as default };
//# sourceMappingURL=EmbedFederationRuntimePlugin.d.ts.map

View File

@@ -0,0 +1,73 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
const require_lib_container_runtime_utils = require('./utils.js');
const require_lib_container_runtime_EmbedFederationRuntimeModule = require('./EmbedFederationRuntimeModule.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./FederationModulesPlugin.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/runtime/EmbedFederationRuntimePlugin.ts
const { RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const PLUGIN_NAME = "EmbedFederationRuntimePlugin";
const federationGlobal = require_lib_container_runtime_utils.getFederationGlobalScope(RuntimeGlobals);
/**
* Plugin that embeds Module Federation runtime code into chunks.
* It ensures proper initialization of federated modules and manages runtime requirements.
*/
var EmbedFederationRuntimePlugin = class {
constructor(options = {}) {
this.processedChunks = /* @__PURE__ */ new WeakMap();
this.options = {
enableForAllChunks: false,
...options
};
}
/**
* Determines if runtime embedding should be enabled for a given chunk.
*/
isEnabledForChunk(chunk) {
if (chunk.id === "build time chunk") return false;
return this.options.enableForAllChunks || chunk.hasRuntime();
}
/**
* Checks if a hook has already been tapped by this plugin.
*/
isHookAlreadyTapped(taps, hookName) {
return taps.some((tap) => tap.name === hookName);
}
apply(compiler) {
const compilationTaps = compiler.hooks.thisCompilation.taps || [];
if (this.isHookAlreadyTapped(compilationTaps, PLUGIN_NAME)) return;
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
const { renderStartup } = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
renderStartup.tap(PLUGIN_NAME, (startupSource, _lastInlinedModule, renderContext) => {
const { chunk, chunkGraph } = renderContext;
if (!this.isEnabledForChunk(chunk)) return startupSource;
const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk);
if (chunkGraph.getNumberOfEntryModules(chunk) > 0 || runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) return startupSource;
return new compiler.webpack.sources.ConcatSource(startupSource, "\n// Custom hook: appended startup call because none was added automatically\n", `${RuntimeGlobals.startup}();\n`);
});
const federationHooks = require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation);
const containerEntrySet = /* @__PURE__ */ new Set();
compilation.hooks.additionalChunkRuntimeRequirements.tap(PLUGIN_NAME, (chunk, runtimeRequirements) => {
if (!this.isEnabledForChunk(chunk)) return;
runtimeRequirements.add(RuntimeGlobals.startupOnlyBefore);
});
federationHooks.addFederationRuntimeDependency.tap(PLUGIN_NAME, (dependency) => {
containerEntrySet.add(dependency);
});
const handleRuntimeRequirements = (chunk, runtimeRequirements) => {
if (!this.isEnabledForChunk(chunk)) return;
if (runtimeRequirements.has("embeddedFederationRuntime")) return;
if (!runtimeRequirements.has(federationGlobal)) return;
runtimeRequirements.add("embeddedFederationRuntime");
const runtimeModule = new require_lib_container_runtime_EmbedFederationRuntimeModule.default(containerEntrySet);
compilation.addRuntimeModule(chunk, runtimeModule);
};
compilation.hooks.runtimeRequirementInTree.for(federationGlobal).tap(PLUGIN_NAME, handleRuntimeRequirements);
});
}
};
//#endregion
exports.default = EmbedFederationRuntimePlugin;
//# sourceMappingURL=EmbedFederationRuntimePlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,25 @@
import ContainerEntryDependency from "../ContainerEntryDependency.js";
import FederationRuntimeDependency from "./FederationRuntimeDependency.js";
import { Compilation, Compiler } from "webpack";
import { SyncHook } from "tapable";
//#region src/lib/container/runtime/FederationModulesPlugin.d.ts
/** @typedef {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} Bootstrap */
type CompilationHooks = {
addContainerEntryDependency: SyncHook<[ContainerEntryDependency], void>;
addFederationRuntimeDependency: SyncHook<[FederationRuntimeDependency], void>;
addRemoteDependency: SyncHook<[any], void>;
};
declare class FederationModulesPlugin {
options: any;
/**
* @param {Compilation} compilation the compilation
* @returns {CompilationHooks} the attached hooks
*/
static getCompilationHooks(compilation: Compilation): CompilationHooks;
constructor(options?: {});
apply(compiler: Compiler): void;
}
//#endregion
export { FederationModulesPlugin as default };
//# sourceMappingURL=FederationModulesPlugin.d.ts.map

View File

@@ -0,0 +1,41 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
let tapable = require("tapable");
//#region src/lib/container/runtime/FederationModulesPlugin.ts
require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/Compilation"));
/** @type {WeakMap<import("webpack").Compilation, CompilationHooks>} */
const compilationHooksMap = /* @__PURE__ */ new WeakMap();
const PLUGIN_NAME = "FederationModulesPlugin";
var FederationModulesPlugin = class FederationModulesPlugin {
/**
* @param {Compilation} compilation the compilation
* @returns {CompilationHooks} the attached hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation && typeof compilation === "object" && typeof compilation.hooks === "object" && typeof compilation.hooks.processAssets?.tap === "function")) throw new TypeError("Invalid 'compilation' argument: expected a Webpack Compilation-like object");
let hooks = compilationHooksMap.get(compilation);
if (hooks === void 0) {
hooks = {
addContainerEntryDependency: new tapable.SyncHook(["dependency"]),
addFederationRuntimeDependency: new tapable.SyncHook(["dependency"]),
addRemoteDependency: new tapable.SyncHook(["dependency"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
constructor(options = {}) {
this.options = options;
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory }) => {
FederationModulesPlugin.getCompilationHooks(compilation);
});
}
};
//#endregion
exports.default = FederationModulesPlugin;
//# sourceMappingURL=FederationModulesPlugin.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"FederationModulesPlugin.js","names":["SyncHook"],"sources":["../../../../../src/lib/container/runtime/FederationModulesPlugin.ts"],"sourcesContent":["import type { Compiler, Compilation as CompilationType } from 'webpack';\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst Compilation = require(\n normalizeWebpackPath('webpack/lib/Compilation'),\n) as typeof import('webpack/lib/Compilation');\nimport { SyncHook } from 'tapable';\nimport ContainerEntryDependency from '../ContainerEntryDependency';\nimport FederationRuntimeDependency from './FederationRuntimeDependency';\n\n/** @type {WeakMap<import(\"webpack\").Compilation, CompilationHooks>} */\nconst compilationHooksMap = new WeakMap<CompilationType, CompilationHooks>();\n\nconst PLUGIN_NAME = 'FederationModulesPlugin';\n\n/** @typedef {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} Bootstrap */\n\ntype CompilationHooks = {\n addContainerEntryDependency: SyncHook<[ContainerEntryDependency], void>;\n addFederationRuntimeDependency: SyncHook<[FederationRuntimeDependency], void>;\n addRemoteDependency: SyncHook<[any], void>;\n};\n\nclass FederationModulesPlugin {\n options: any;\n\n /**\n * @param {Compilation} compilation the compilation\n * @returns {CompilationHooks} the attached hooks\n */\n static getCompilationHooks(compilation: CompilationType): CompilationHooks {\n // Avoid cross-realm instanceof checks (e.g., Jest VM modules) by using\n // a duck-typed verification of a Webpack Compilation-like object.\n const isLikelyCompilation =\n compilation &&\n typeof compilation === 'object' &&\n // @ts-ignore\n typeof (compilation as any).hooks === 'object' &&\n // A couple of well-known hooks available on Webpack 5 compilations\n // @ts-ignore\n typeof (compilation as any).hooks.processAssets?.tap === 'function';\n\n if (!isLikelyCompilation) {\n throw new TypeError(\n \"Invalid 'compilation' argument: expected a Webpack Compilation-like object\",\n );\n }\n let hooks = compilationHooksMap.get(compilation);\n if (hooks === undefined) {\n hooks = {\n addContainerEntryDependency: new SyncHook(['dependency']),\n addFederationRuntimeDependency: new SyncHook(['dependency']),\n addRemoteDependency: new SyncHook(['dependency']),\n };\n compilationHooksMap.set(compilation, hooks);\n }\n return hooks;\n }\n\n constructor(options = {}) {\n this.options = options;\n }\n\n apply(compiler: Compiler) {\n compiler.hooks.compilation.tap(\n PLUGIN_NAME,\n (compilation: CompilationType, { normalModuleFactory }) => {\n //@ts-ignore\n const hooks = FederationModulesPlugin.getCompilationHooks(compilation);\n },\n );\n }\n}\n\nexport default FederationModulesPlugin;\n"],"mappings":";;;;;;AAGoB,gFACG,0BAA0B,CAChD;;AAMD,MAAM,sCAAsB,IAAI,SAA4C;AAE5E,MAAM,cAAc;AAUpB,IAAM,0BAAN,MAAM,wBAAwB;;;;;CAO5B,OAAO,oBAAoB,aAAgD;AAYzE,MAAI,EARF,eACA,OAAO,gBAAgB,YAEvB,OAAQ,YAAoB,UAAU,YAGtC,OAAQ,YAAoB,MAAM,eAAe,QAAQ,YAGzD,OAAM,IAAI,UACR,6EACD;EAEH,IAAI,QAAQ,oBAAoB,IAAI,YAAY;AAChD,MAAI,UAAU,QAAW;AACvB,WAAQ;IACN,6BAA6B,IAAIA,iBAAS,CAAC,aAAa,CAAC;IACzD,gCAAgC,IAAIA,iBAAS,CAAC,aAAa,CAAC;IAC5D,qBAAqB,IAAIA,iBAAS,CAAC,aAAa,CAAC;IAClD;AACD,uBAAoB,IAAI,aAAa,MAAM;;AAE7C,SAAO;;CAGT,YAAY,UAAU,EAAE,EAAE;AACxB,OAAK,UAAU;;CAGjB,MAAM,UAAoB;AACxB,WAAS,MAAM,YAAY,IACzB,cACC,aAA8B,EAAE,0BAA0B;AAE3C,2BAAwB,oBAAoB,YAAY;IAEzE"}

View File

@@ -0,0 +1,11 @@
import * as webpack_lib_dependencies_ModuleDependency0 from "webpack/lib/dependencies/ModuleDependency";
//#region src/lib/container/runtime/FederationRuntimeDependency.d.ts
declare const ModuleDependency: typeof webpack_lib_dependencies_ModuleDependency0;
declare class FederationRuntimeDependency extends ModuleDependency {
constructor(request: string);
get type(): string;
}
//#endregion
export { FederationRuntimeDependency as default };
//# sourceMappingURL=FederationRuntimeDependency.d.ts.map

View File

@@ -0,0 +1,18 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/runtime/FederationRuntimeDependency.ts
const ModuleDependency = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/dependencies/ModuleDependency"));
var FederationRuntimeDependency = class extends ModuleDependency {
constructor(request) {
super(request);
}
get type() {
return "federation runtime dependency";
}
};
//#endregion
exports.default = FederationRuntimeDependency;
//# sourceMappingURL=FederationRuntimeDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"FederationRuntimeDependency.js","names":[],"sources":["../../../../../src/lib/container/runtime/FederationRuntimeDependency.ts"],"sourcesContent":["import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\n\nconst ModuleDependency = require(\n normalizeWebpackPath('webpack/lib/dependencies/ModuleDependency'),\n) as typeof import('webpack/lib/dependencies/ModuleDependency');\n\nclass FederationRuntimeDependency extends ModuleDependency {\n constructor(request: string) {\n super(request);\n }\n\n override get type() {\n return 'federation runtime dependency';\n }\n}\n\nexport default FederationRuntimeDependency;\n"],"mappings":";;;;;AAEA,MAAM,mBAAmB,gFACF,4CAA4C,CAClE;AAED,IAAM,8BAAN,cAA0C,iBAAiB;CACzD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;;CAGhB,IAAa,OAAO;AAClB,SAAO"}

View File

@@ -0,0 +1,18 @@
import { NormalizedRuntimeInitOptionsWithOutShared } from "./utils.js";
import * as webpack$1 from "webpack";
//#region src/lib/container/runtime/FederationRuntimeModule.d.ts
declare const RuntimeModule: typeof webpack$1.RuntimeModule;
declare class FederationRuntimeModule extends RuntimeModule {
runtimeRequirements: ReadonlySet<string>;
containerName: string;
initOptionsWithoutShared: NormalizedRuntimeInitOptionsWithOutShared;
constructor(runtimeRequirements: ReadonlySet<string>, containerName: string, initOptionsWithoutShared: NormalizedRuntimeInitOptionsWithOutShared);
/**
* @returns {string | null} runtime code
*/
generate(): string;
}
//#endregion
export { FederationRuntimeModule as default };
//# sourceMappingURL=FederationRuntimeModule.d.ts.map

View File

@@ -0,0 +1,42 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
const require_lib_container_runtime_getFederationGlobal = require('./getFederationGlobal.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/runtime/FederationRuntimeModule.ts
const compileBooleanMatcher = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/compileBooleanMatcher"));
const { getUndoPath } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/identifier"));
const { RuntimeModule, RuntimeGlobals, Template } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var FederationRuntimeModule = class extends RuntimeModule {
constructor(runtimeRequirements, containerName, initOptionsWithoutShared) {
super("federation runtime", RuntimeModule.STAGE_NORMAL - 1);
this.runtimeRequirements = runtimeRequirements;
this.containerName = containerName;
this.initOptionsWithoutShared = initOptionsWithoutShared;
}
/**
* @returns {string | null} runtime code
*/
generate() {
let matcher = false;
let rootOutputDir;
if (this.compilation && this.chunk) {
const jsModulePlugin = this.compilation.compiler.webpack?.javascript?.JavascriptModulesPlugin || require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/javascript/JavascriptModulesPlugin"));
const { chunkHasJs } = jsModulePlugin;
if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) {
const hasJsMatcher = compileBooleanMatcher(this.compilation.chunkGraph.getChunkConditionMap(this.chunk, chunkHasJs));
if (typeof hasJsMatcher === "boolean") matcher = hasJsMatcher;
else matcher = hasJsMatcher("chunkId");
rootOutputDir = getUndoPath(this.compilation.getPath(jsModulePlugin.getChunkFilenameTemplate(this.chunk, this.compilation.outputOptions), {
chunk: this.chunk,
contentHashType: "javascript"
}), this.compilation.outputOptions.path || "", false);
}
}
return Template.asString([require_lib_container_runtime_getFederationGlobal.default(Template, RuntimeGlobals, matcher, rootOutputDir, this.initOptionsWithoutShared)]);
}
};
//#endregion
exports.default = FederationRuntimeModule;
//# sourceMappingURL=FederationRuntimeModule.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"FederationRuntimeModule.js","names":["getFederationGlobal"],"sources":["../../../../../src/lib/container/runtime/FederationRuntimeModule.ts"],"sourcesContent":["import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\nconst compileBooleanMatcher = require(\n normalizeWebpackPath('webpack/lib/util/compileBooleanMatcher'),\n) as typeof import('webpack/lib/util/compileBooleanMatcher');\nconst { getUndoPath } = require(\n normalizeWebpackPath('webpack/lib/util/identifier'),\n) as typeof import('webpack/lib/util/identifier');\n// inspired by react-refresh-webpack-plugin\nimport getFederationGlobal from './getFederationGlobal';\nimport type { NormalizedRuntimeInitOptionsWithOutShared } from './utils';\n\nconst { RuntimeModule, RuntimeGlobals, Template } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass FederationRuntimeModule extends RuntimeModule {\n runtimeRequirements: ReadonlySet<string>;\n containerName: string;\n initOptionsWithoutShared: NormalizedRuntimeInitOptionsWithOutShared;\n\n constructor(\n runtimeRequirements: ReadonlySet<string>,\n containerName: string,\n initOptionsWithoutShared: NormalizedRuntimeInitOptionsWithOutShared,\n ) {\n super('federation runtime', RuntimeModule.STAGE_NORMAL - 1);\n this.runtimeRequirements = runtimeRequirements;\n this.containerName = containerName;\n this.initOptionsWithoutShared = initOptionsWithoutShared;\n }\n\n /**\n * @returns {string | null} runtime code\n */\n override generate() {\n let matcher: string | boolean = false;\n let rootOutputDir: string | undefined;\n if (this.compilation && this.chunk) {\n const jsModulePlugin =\n this.compilation.compiler.webpack?.javascript\n ?.JavascriptModulesPlugin ||\n require(\n normalizeWebpackPath(\n 'webpack/lib/javascript/JavascriptModulesPlugin',\n ),\n );\n const { chunkHasJs } = jsModulePlugin;\n if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) {\n const conditionMap = this.compilation.chunkGraph.getChunkConditionMap(\n this.chunk,\n chunkHasJs,\n );\n const hasJsMatcher = compileBooleanMatcher(conditionMap);\n if (typeof hasJsMatcher === 'boolean') {\n matcher = hasJsMatcher;\n } else {\n matcher = hasJsMatcher('chunkId');\n }\n const outputName = this.compilation.getPath(\n jsModulePlugin.getChunkFilenameTemplate(\n this.chunk,\n this.compilation.outputOptions,\n ),\n { chunk: this.chunk, contentHashType: 'javascript' },\n );\n rootOutputDir = getUndoPath(\n outputName,\n this.compilation.outputOptions.path || '',\n false,\n );\n }\n }\n\n return Template.asString([\n getFederationGlobal(\n Template,\n RuntimeGlobals,\n matcher,\n rootOutputDir,\n this.initOptionsWithoutShared,\n ),\n ]);\n }\n}\nexport default FederationRuntimeModule;\n"],"mappings":";;;;;;AACA,MAAM,wBAAwB,gFACP,yCAAyC,CAC/D;AACD,MAAM,EAAE,gBAAgB,gFACD,8BAA8B,CACpD;AAKD,MAAM,EAAE,eAAe,gBAAgB,aAAa,gFAC7B,UAAU,CAChC;AAED,IAAM,0BAAN,cAAsC,cAAc;CAKlD,YACE,qBACA,eACA,0BACA;AACA,QAAM,sBAAsB,cAAc,eAAe,EAAE;AAC3D,OAAK,sBAAsB;AAC3B,OAAK,gBAAgB;AACrB,OAAK,2BAA2B;;;;;CAMlC,AAAS,WAAW;EAClB,IAAI,UAA4B;EAChC,IAAI;AACJ,MAAI,KAAK,eAAe,KAAK,OAAO;GAClC,MAAM,iBACJ,KAAK,YAAY,SAAS,SAAS,YAC/B,2BACJ,gFAEI,iDACD,CACF;GACH,MAAM,EAAE,eAAe;AACvB,OAAI,KAAK,oBAAoB,IAAI,eAAe,oBAAoB,EAAE;IAKpE,MAAM,eAAe,sBAJA,KAAK,YAAY,WAAW,qBAC/C,KAAK,OACL,WACD,CACuD;AACxD,QAAI,OAAO,iBAAiB,UAC1B,WAAU;QAEV,WAAU,aAAa,UAAU;AASnC,oBAAgB,YAPG,KAAK,YAAY,QAClC,eAAe,yBACb,KAAK,OACL,KAAK,YAAY,cAClB,EACD;KAAE,OAAO,KAAK;KAAO,iBAAiB;KAAc,CACrD,EAGC,KAAK,YAAY,cAAc,QAAQ,IACvC,MACD;;;AAIL,SAAO,SAAS,SAAS,CACvBA,0DACE,UACA,gBACA,SACA,eACA,KAAK,yBACN,CACF,CAAC"}

View File

@@ -0,0 +1,33 @@
import { __require } from "../../../_virtual/_rolldown/runtime.js";
import FederationRuntimeDependency from "./FederationRuntimeDependency.js";
import { moduleFederationPlugin } from "@module-federation/sdk";
import { Compiler } from "webpack";
//#region src/lib/container/runtime/FederationRuntimePlugin.d.ts
type ResolveFn = typeof __require.resolve;
declare function resolveRuntimePaths(implementation?: string, resolve?: ResolveFn): {
runtimeToolsPath: string;
bundlerRuntimePath: string;
runtimePath: string;
};
declare class FederationRuntimePlugin {
options?: moduleFederationPlugin.ModuleFederationPluginOptions;
entryFilePath: string;
bundlerRuntimePath: string;
runtimePath: string;
runtimeToolsPath: string;
federationRuntimeDependency?: FederationRuntimeDependency;
constructor(options?: moduleFederationPlugin.ModuleFederationPluginOptions);
static getTemplate(compiler: Compiler, options: moduleFederationPlugin.ModuleFederationPluginOptions, bundlerRuntimePath?: string): string;
getFilePath(compiler: Compiler): string;
ensureFile(compiler: Compiler): void;
getDependency(compiler: Compiler): FederationRuntimeDependency;
prependEntry(compiler: Compiler): void;
injectRuntime(compiler: Compiler): void;
getRuntimeAlias(compiler: Compiler): string;
setRuntimeAlias(compiler: Compiler): void;
apply(compiler: Compiler): void;
}
//#endregion
export { FederationRuntimePlugin as default, resolveRuntimePaths };
//# sourceMappingURL=FederationRuntimePlugin.d.ts.map

View File

@@ -0,0 +1,265 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
const require_lib_container_runtime_utils = require('./utils.js');
const require_lib_container_runtime_FederationRuntimeModule = require('./FederationRuntimeModule.js');
const require_lib_container_constant = require('../constant.js');
const require_lib_container_runtime_FederationModulesPlugin = require('./FederationModulesPlugin.js');
const require_lib_container_runtime_EmbedFederationRuntimePlugin = require('./EmbedFederationRuntimePlugin.js');
const require_lib_container_HoistContainerReferencesPlugin = require('../HoistContainerReferencesPlugin.js');
const require_lib_container_runtime_FederationRuntimeDependency = require('./FederationRuntimeDependency.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
let path = require("path");
path = require_runtime.__toESM(path);
let fs = require("fs");
fs = require_runtime.__toESM(fs);
//#region src/lib/container/runtime/FederationRuntimePlugin.ts
const ModuleDependency = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/dependencies/ModuleDependency"));
const { RuntimeGlobals, Template } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const { mkdirpSync } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/fs"));
function resolveRuntimeEntry(spec, implementation, resolve = require.resolve) {
const candidates = [
spec.bundler,
spec.esm,
spec.cjs
];
const modulePaths = implementation ? [implementation] : void 0;
let lastError;
for (const candidate of candidates) try {
return modulePaths ? resolve(candidate, { paths: modulePaths }) : resolve(candidate);
} catch (error) {
lastError = error;
}
throw lastError;
}
function resolveRuntimeEntryWithFallback(spec, implementation, resolve = require.resolve) {
if (implementation) try {
return resolveRuntimeEntry(spec, implementation, resolve);
} catch {}
return resolveRuntimeEntry(spec, void 0, resolve);
}
function resolveRuntimePaths(implementation, resolve = require.resolve) {
const runtimeToolsPath = resolveRuntimeEntryWithFallback({
bundler: "@module-federation/runtime-tools/bundler",
esm: "@module-federation/runtime-tools/dist/index.js",
cjs: "@module-federation/runtime-tools/dist/index.cjs"
}, implementation, resolve);
const moduleBase = implementation || runtimeToolsPath;
return {
runtimeToolsPath,
bundlerRuntimePath: resolveRuntimeEntry({
bundler: "@module-federation/webpack-bundler-runtime/bundler",
esm: "@module-federation/webpack-bundler-runtime/dist/index.js",
cjs: "@module-federation/webpack-bundler-runtime/dist/index.cjs"
}, moduleBase, resolve),
runtimePath: resolveRuntimeEntry({
bundler: "@module-federation/runtime/bundler",
esm: "@module-federation/runtime/dist/index.js",
cjs: "@module-federation/runtime/dist/index.cjs"
}, moduleBase, resolve)
};
}
const { runtimeToolsPath: RuntimeToolsPath, bundlerRuntimePath: BundlerRuntimePath, runtimePath: RuntimePath } = resolveRuntimePaths();
const federationGlobal = require_lib_container_runtime_utils.getFederationGlobalScope(RuntimeGlobals);
const onceForCompiler = /* @__PURE__ */ new WeakSet();
const onceForCompilerEntryMap = /* @__PURE__ */ new WeakMap();
var FederationRuntimePlugin = class FederationRuntimePlugin {
constructor(options) {
this.options = options ? { ...options } : void 0;
this.entryFilePath = "";
this.bundlerRuntimePath = BundlerRuntimePath;
this.runtimePath = RuntimePath;
this.runtimeToolsPath = RuntimeToolsPath;
this.federationRuntimeDependency = void 0;
}
static getTemplate(compiler, options, bundlerRuntimePath) {
const runtimePlugins = options.runtimePlugins;
const normalizedBundlerRuntimePath = require_lib_container_runtime_utils.normalizeToPosixPath(bundlerRuntimePath || BundlerRuntimePath);
let runtimePluginTemplates = "";
const runtimePluginCalls = [];
if (Array.isArray(runtimePlugins)) runtimePlugins.forEach((runtimePlugin, index) => {
if (!runtimePlugin) return;
const runtimePluginName = `plugin_${index}`;
const runtimePluginEntry = Array.isArray(runtimePlugin) ? runtimePlugin[0] : runtimePlugin;
const runtimePluginPath = require_lib_container_runtime_utils.normalizeToPosixPath(path.default.isAbsolute(runtimePluginEntry) ? runtimePluginEntry : path.default.join(process.cwd(), runtimePluginEntry));
const paramsStr = Array.isArray(runtimePlugin) && runtimePlugin.length > 1 ? JSON.stringify(runtimePlugin[1]) : "undefined";
runtimePluginTemplates += `import ${runtimePluginName} from '${runtimePluginPath}';\n`;
runtimePluginCalls.push(`${runtimePluginName} ? (${runtimePluginName}.default || ${runtimePluginName})(${paramsStr}) : false`);
});
const embedRuntimeLines = Template.asString([
`if(!${federationGlobal}.runtime || !${federationGlobal}.bundlerRuntime){`,
Template.indent([
`var prevFederation = ${federationGlobal};`,
`${federationGlobal} = {}`,
`for(var key in federation){`,
Template.indent([`${federationGlobal}[key] = federation[key];`]),
"}",
`for(var key in prevFederation){`,
Template.indent([`${federationGlobal}[key] = prevFederation[key];`]),
"}"
]),
"}"
]);
return Template.asString([
`import federation from '${normalizedBundlerRuntimePath}';`,
runtimePluginTemplates,
embedRuntimeLines,
`if(!${federationGlobal}.instance){`,
Template.indent([
runtimePluginCalls.length ? Template.asString([
`var pluginsToAdd = [`,
Template.indent(Template.indent(runtimePluginCalls.map((call) => `${call},`))),
`].filter(Boolean);`,
`${federationGlobal}.initOptions.plugins = ${federationGlobal}.initOptions.plugins ? `,
`${federationGlobal}.initOptions.plugins.concat(pluginsToAdd) : pluginsToAdd;`
]) : "",
`${federationGlobal}.instance = ${federationGlobal}.bundlerRuntime.init({webpackRequire:${RuntimeGlobals.require}});`,
`if(${federationGlobal}.attachShareScopeMap){`,
Template.indent([`${federationGlobal}.attachShareScopeMap(${RuntimeGlobals.require})`]),
"}",
`if(${federationGlobal}.installInitialConsumes){`,
Template.indent([`${federationGlobal}.installInitialConsumes()`]),
"}"
]),
"}"
]);
}
getFilePath(compiler) {
if (!this.options) return "";
const existedFilePath = onceForCompilerEntryMap.get(compiler);
if (existedFilePath) return existedFilePath;
let entryFilePath = "";
if (!this.options?.virtualRuntimeEntry) {
const containerName = this.options.name;
const hash = require_lib_container_runtime_utils.createHash(`${containerName} ${FederationRuntimePlugin.getTemplate(compiler, this.options, this.bundlerRuntimePath)}`);
entryFilePath = path.default.join(require_lib_container_constant.TEMP_DIR, `entry.${hash}.js`);
} else entryFilePath = `data:text/javascript;charset=utf-8;base64,${Buffer.from(FederationRuntimePlugin.getTemplate(compiler, this.options, this.bundlerRuntimePath), "utf8").toString("base64")}`;
onceForCompilerEntryMap.set(compiler, entryFilePath);
return entryFilePath;
}
ensureFile(compiler) {
if (!this.options) return;
if (this.options?.virtualRuntimeEntry) return;
const filePath = this.entryFilePath;
const outputFs = compiler.outputFileSystem;
const fsLike = outputFs && typeof outputFs.readFileSync === "function" && typeof outputFs.writeFileSync === "function" ? outputFs : fs.default;
try {
fsLike.readFileSync(filePath);
} catch {
mkdirpSync(fsLike, require_lib_container_constant.TEMP_DIR);
fsLike.writeFileSync(filePath, FederationRuntimePlugin.getTemplate(compiler, this.options, this.bundlerRuntimePath));
}
}
getDependency(compiler) {
if (this.federationRuntimeDependency) return this.federationRuntimeDependency;
this.ensureFile(compiler);
this.federationRuntimeDependency = new require_lib_container_runtime_FederationRuntimeDependency.default(this.entryFilePath);
return this.federationRuntimeDependency;
}
prependEntry(compiler) {
if (!this.options?.virtualRuntimeEntry) this.ensureFile(compiler);
compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(require_lib_container_runtime_FederationRuntimeDependency.default, normalModuleFactory);
compilation.dependencyTemplates.set(require_lib_container_runtime_FederationRuntimeDependency.default, new ModuleDependency.Template());
});
compiler.hooks.make.tapAsync(this.constructor.name, (compilation, callback) => {
const federationRuntimeDependency = this.getDependency(compiler);
const hooks = require_lib_container_runtime_FederationModulesPlugin.default.getCompilationHooks(compilation);
compilation.addInclude(compiler.context, federationRuntimeDependency, { name: void 0 }, (err) => {
if (err) return callback(err);
hooks.addFederationRuntimeDependency.call(federationRuntimeDependency);
callback();
});
});
}
injectRuntime(compiler) {
if (!this.options || !this.options.name) return;
const name = this.options.name;
const initOptionsWithoutShared = require_lib_container_runtime_utils.normalizeRuntimeInitOptionsWithOutShared(this.options);
const federationGlobal = require_lib_container_runtime_utils.getFederationGlobalScope(RuntimeGlobals || {});
compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
const handler = (chunk, runtimeRequirements) => {
if (runtimeRequirements.has(federationGlobal)) return;
runtimeRequirements.add(federationGlobal);
runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
runtimeRequirements.add(RuntimeGlobals.moduleCache);
runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
compilation.addRuntimeModule(chunk, new require_lib_container_runtime_FederationRuntimeModule.default(runtimeRequirements, name, initOptionsWithoutShared));
};
compilation.hooks.additionalTreeRuntimeRequirements.tap(this.constructor.name, (chunk, runtimeRequirements) => {
if (!chunk.hasRuntime()) return;
if (runtimeRequirements.has(RuntimeGlobals.initializeSharing)) return;
if (runtimeRequirements.has(RuntimeGlobals.currentRemoteGetScope)) return;
if (runtimeRequirements.has(RuntimeGlobals.shareScopeMap)) return;
if (runtimeRequirements.has(federationGlobal)) return;
handler(chunk, runtimeRequirements);
});
compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.initializeSharing).tap(this.constructor.name, handler);
compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.currentRemoteGetScope).tap(this.constructor.name, handler);
compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.shareScopeMap).tap(this.constructor.name, handler);
compilation.hooks.runtimeRequirementInTree.for(federationGlobal).tap(this.constructor.name, handler);
});
}
getRuntimeAlias(compiler) {
const { implementation } = this.options || {};
const alias = compiler.options.resolve.alias || {};
const resolvedPaths = resolveRuntimePaths(implementation);
this.runtimeToolsPath = resolvedPaths.runtimeToolsPath;
this.bundlerRuntimePath = resolvedPaths.bundlerRuntimePath;
if (alias["@module-federation/runtime$"]) {
this.runtimePath = alias["@module-federation/runtime$"];
return this.runtimePath;
}
this.runtimePath = resolvedPaths.runtimePath;
return this.runtimePath;
}
setRuntimeAlias(compiler) {
const { implementation } = this.options || {};
const alias = compiler.options.resolve.alias || {};
const runtimePath = this.getRuntimeAlias(compiler);
alias["@module-federation/runtime$"] = alias["@module-federation/runtime$"] || runtimePath;
alias["@module-federation/runtime-tools$"] = alias["@module-federation/runtime-tools$"] || implementation || this.runtimeToolsPath;
compiler.options.resolve.alias = alias;
}
apply(compiler) {
if (compiler.options.plugins.find((p) => {
if (typeof p !== "object" || !p) return false;
return p["name"] === "SharedContainerPlugin";
})) return;
const useModuleFederationPlugin = compiler.options.plugins.find((p) => {
if (typeof p !== "object" || !p) return false;
return p["name"] === "ModuleFederationPlugin";
});
if (useModuleFederationPlugin && !this.options) this.options = useModuleFederationPlugin._options;
const useContainerPlugin = compiler.options.plugins.find((p) => {
if (typeof p !== "object" || !p) return false;
return p["name"] === "ContainerPlugin";
});
if (useContainerPlugin && !this.options) this.options = useContainerPlugin._options;
if (!useContainerPlugin && !useModuleFederationPlugin) this.options = {
remotes: {},
...this.options
};
if (this.options && !this.options?.name)
//! the instance may get the same one if the name is the same https://github.com/module-federation/core/blob/main/packages/runtime/src/index.ts#L18
this.options.name = compiler.options.output.uniqueName || `container_${Date.now()}`;
const resolvedPaths = resolveRuntimePaths(this.options?.implementation);
this.bundlerRuntimePath = resolvedPaths.bundlerRuntimePath;
this.runtimePath = resolvedPaths.runtimePath;
this.runtimeToolsPath = resolvedPaths.runtimeToolsPath;
this.entryFilePath = this.getFilePath(compiler);
new require_lib_container_runtime_EmbedFederationRuntimePlugin.default().apply(compiler);
new require_lib_container_HoistContainerReferencesPlugin.default().apply(compiler);
if (!onceForCompiler.has(compiler)) {
this.prependEntry(compiler);
this.injectRuntime(compiler);
this.setRuntimeAlias(compiler);
onceForCompiler.add(compiler);
}
}
};
//#endregion
exports.default = FederationRuntimePlugin;
exports.resolveRuntimePaths = resolveRuntimePaths;
//# sourceMappingURL=FederationRuntimePlugin.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
import { NormalizedRuntimeInitOptionsWithOutShared } from "./utils.js";
import * as webpack$1 from "webpack";
import RuntimeGlobals from "webpack/lib/RuntimeGlobals";
//#region src/lib/container/runtime/getFederationGlobal.d.ts
declare const Template: typeof webpack$1.Template;
declare function getFederationGlobal(template: typeof Template, runtimeGlobals: typeof RuntimeGlobals, matcher: string | boolean, rootOutputDir: string | undefined, initOptionsWithoutShared: NormalizedRuntimeInitOptionsWithOutShared): string;
//#endregion
export { getFederationGlobal as default };
//# sourceMappingURL=getFederationGlobal.d.ts.map

View File

@@ -0,0 +1,47 @@
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
const require_lib_container_runtime_utils = require('./utils.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/container/runtime/getFederationGlobal.ts
const { Template } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
function getFederationGlobal(template, runtimeGlobals, matcher, rootOutputDir, initOptionsWithoutShared) {
const federationGlobal = require_lib_container_runtime_utils.getFederationGlobalScope(runtimeGlobals);
const initOptionsStrWithoutShared = JSON.stringify({
...initOptionsWithoutShared,
remotes: initOptionsWithoutShared.remotes.filter((remote) => remote.externalType === "script")
});
const remoteInfos = JSON.stringify(initOptionsWithoutShared.remotes.reduce((acc, remote) => {
const item = {
alias: remote.alias || "",
name: remote.name,
entry: remote.entry || "",
shareScope: remote.shareScope,
externalType: remote.externalType
};
const key = remote.name || remote.alias || "";
acc[key] ||= [];
acc[key].push(item);
return acc;
}, {}));
return template.asString([
`if(!${federationGlobal}){`,
template.indent([
`${federationGlobal} = {`,
template.indent([
`initOptions: ${initOptionsStrWithoutShared},`,
`chunkMatcher: function(chunkId) {return ${matcher}},`,
`rootOutputDir: ${JSON.stringify(rootOutputDir || "")},`,
`bundlerRuntimeOptions: { remotes: { remoteInfos: ${remoteInfos}, webpackRequire: ${runtimeGlobals.require},idToRemoteMap: {}, chunkMapping: {},idToExternalAndNameMapping: {} } }`
]),
"};"
]),
`${runtimeGlobals.require}.consumesLoadingData = {}`,
`${runtimeGlobals.require}.remotesLoadingData = {}`,
"}"
]);
}
//#endregion
exports.default = getFederationGlobal;
//# sourceMappingURL=getFederationGlobal.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getFederationGlobal.js","names":["getFederationGlobalScope"],"sources":["../../../../../src/lib/container/runtime/getFederationGlobal.ts"],"sourcesContent":["import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\nimport { getFederationGlobalScope } from './utils';\nimport type RuntimeGlobals from 'webpack/lib/RuntimeGlobals';\nimport type { NormalizedRuntimeInitOptionsWithOutShared } from './utils';\nimport type { RemoteInfos } from '@module-federation/webpack-bundler-runtime';\n\nconst { Template } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nfunction getFederationGlobal(\n template: typeof Template,\n runtimeGlobals: typeof RuntimeGlobals,\n matcher: string | boolean,\n rootOutputDir: string | undefined,\n initOptionsWithoutShared: NormalizedRuntimeInitOptionsWithOutShared,\n): string {\n const federationGlobal = getFederationGlobalScope(runtimeGlobals);\n const initOptionsStrWithoutShared = JSON.stringify({\n ...initOptionsWithoutShared,\n remotes: initOptionsWithoutShared.remotes.filter(\n (remote) => remote.externalType === 'script',\n ),\n });\n const remoteInfos = JSON.stringify(\n initOptionsWithoutShared.remotes.reduce((acc, remote) => {\n const item: RemoteInfos[string][0] = {\n alias: remote.alias || '',\n name: remote.name,\n // @ts-ignore\n entry: remote.entry || '',\n // @ts-ignore\n shareScope: remote.shareScope,\n externalType: remote.externalType,\n };\n const key = remote.name || remote.alias || '';\n acc[key] ||= [];\n acc[key].push(item);\n return acc;\n }, {} as RemoteInfos),\n );\n\n return template.asString([\n `if(!${federationGlobal}){`,\n template.indent([\n `${federationGlobal} = {`,\n template.indent([\n `initOptions: ${initOptionsStrWithoutShared},`,\n `chunkMatcher: function(chunkId) {return ${matcher}},`,\n `rootOutputDir: ${JSON.stringify(rootOutputDir || '')},`,\n `bundlerRuntimeOptions: { remotes: { remoteInfos: ${remoteInfos}, webpackRequire: ${runtimeGlobals.require},idToRemoteMap: {}, chunkMapping: {},idToExternalAndNameMapping: {} } }`,\n ]),\n '};',\n ]),\n `${runtimeGlobals.require}.consumesLoadingData = {}`,\n `${runtimeGlobals.require}.remotesLoadingData = {}`,\n '}',\n ]);\n}\n\nexport default getFederationGlobal;\n"],"mappings":";;;;;;AAMA,MAAM,EAAE,aAAa,gFACE,UAAU,CAChC;AAED,SAAS,oBACP,UACA,gBACA,SACA,eACA,0BACQ;CACR,MAAM,mBAAmBA,6DAAyB,eAAe;CACjE,MAAM,8BAA8B,KAAK,UAAU;EACjD,GAAG;EACH,SAAS,yBAAyB,QAAQ,QACvC,WAAW,OAAO,iBAAiB,SACrC;EACF,CAAC;CACF,MAAM,cAAc,KAAK,UACvB,yBAAyB,QAAQ,QAAQ,KAAK,WAAW;EACvD,MAAM,OAA+B;GACnC,OAAO,OAAO,SAAS;GACvB,MAAM,OAAO;GAEb,OAAO,OAAO,SAAS;GAEvB,YAAY,OAAO;GACnB,cAAc,OAAO;GACtB;EACD,MAAM,MAAM,OAAO,QAAQ,OAAO,SAAS;AAC3C,MAAI,SAAS,EAAE;AACf,MAAI,KAAK,KAAK,KAAK;AACnB,SAAO;IACN,EAAE,CAAgB,CACtB;AAED,QAAO,SAAS,SAAS;EACvB,OAAO,iBAAiB;EACxB,SAAS,OAAO;GACd,GAAG,iBAAiB;GACpB,SAAS,OAAO;IACd,gBAAgB,4BAA4B;IAC5C,2CAA2C,QAAQ;IACnD,kBAAkB,KAAK,UAAU,iBAAiB,GAAG,CAAC;IACtD,oDAAoD,YAAY,oBAAoB,eAAe,QAAQ;IAC5G,CAAC;GACF;GACD,CAAC;EACF,GAAG,eAAe,QAAQ;EAC1B,GAAG,eAAe,QAAQ;EAC1B;EACD,CAAC"}

View File

@@ -0,0 +1,27 @@
import { moduleFederationPlugin } from "@module-federation/sdk";
import webpack from "webpack";
import RuntimeGlobals from "webpack/lib/RuntimeGlobals";
import { init } from "@module-federation/runtime-tools";
//#region src/lib/container/runtime/utils.d.ts
type Remotes = Parameters<typeof init>[0]['remotes'];
interface NormalizedRuntimeInitOptionsWithOutShared {
name: string;
remotes: Array<Remotes[0] & {
externalType: moduleFederationPlugin.ExternalsType;
}>;
}
type EntryStaticNormalized = Awaited<ReturnType<Extract<webpack.WebpackOptionsNormalized['entry'], () => any>>>;
interface ModifyEntryOptions {
compiler: webpack.Compiler;
prependEntry?: (entry: EntryStaticNormalized) => void;
staticEntry?: EntryStaticNormalized;
}
declare function getFederationGlobalScope(runtimeGlobals: typeof RuntimeGlobals): string;
declare function normalizeRuntimeInitOptionsWithOutShared(options: moduleFederationPlugin.ModuleFederationPluginOptions): NormalizedRuntimeInitOptionsWithOutShared;
declare function modifyEntry(options: ModifyEntryOptions): void;
declare function createHash(contents: string): string;
declare const normalizeToPosixPath: (p: string) => string;
//#endregion
export { NormalizedRuntimeInitOptionsWithOutShared, createHash, getFederationGlobalScope, modifyEntry, normalizeRuntimeInitOptionsWithOutShared, normalizeToPosixPath };
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,93 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
const require_lib_container_options = require('../options.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
let upath = require("upath");
upath = require_runtime.__toESM(upath);
let path = require("path");
path = require_runtime.__toESM(path);
let crypto = require("crypto");
crypto = require_runtime.__toESM(crypto);
//#region src/lib/container/runtime/utils.ts
const extractUrlAndGlobal = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/extractUrlAndGlobal"));
function getFederationGlobalScope(runtimeGlobals) {
return `${runtimeGlobals.require || "__webpack_require__"}.federation`;
}
function normalizeRuntimeInitOptionsWithOutShared(options) {
const parsedOptions = require_lib_container_options.parseOptions(options.remotes || [], (item) => ({
external: Array.isArray(item) ? item : [item],
shareScope: options.shareScope || "default"
}), (item) => ({
external: Array.isArray(item.external) ? item.external : [item.external],
shareScope: item.shareScope || options.shareScope || "default"
}));
const remoteOptions = [];
parsedOptions.forEach((parsedOption) => {
const [alias, remoteInfos] = parsedOption;
const { external, shareScope } = remoteInfos;
external.forEach((externalItem) => {
try {
const entry = externalItem;
if (/\s/.test(entry)) return;
const [url, globalName] = extractUrlAndGlobal(externalItem);
remoteOptions.push({
alias,
name: globalName,
entry: url,
shareScope,
externalType: "script"
});
} catch (err) {
const getExternalTypeFromExternal = (external) => {
if (/^[a-z0-9-]+ /.test(external)) {
const idx = external.indexOf(" ");
return [external.slice(0, idx), external.slice(idx + 1)];
}
return null;
};
remoteOptions.push({
alias,
name: "",
entry: "",
shareScope,
externalType: getExternalTypeFromExternal(externalItem) || "unknown"
});
return;
}
});
});
return {
name: options.name,
remotes: remoteOptions,
shareStrategy: options.shareStrategy || "version-first"
};
}
function modifyEntry(options) {
const { compiler, staticEntry, prependEntry } = options;
const operator = (oriEntry, newEntry) => Object.assign(oriEntry, newEntry);
if (typeof compiler.options.entry === "function") {
const prevEntryFn = compiler.options.entry;
compiler.options.entry = async () => {
let res = await prevEntryFn();
if (staticEntry) res = operator(res, staticEntry);
if (prependEntry) prependEntry(res);
return res;
};
} else {
if (staticEntry) compiler.options.entry = operator(compiler.options.entry, staticEntry);
if (prependEntry) prependEntry(compiler.options.entry);
}
}
function createHash(contents) {
return crypto.default.createHash("md5").update(contents).digest("hex");
}
const normalizeToPosixPath = (p) => upath.default.normalizeSafe(path.default.normalize(p || ""));
//#endregion
exports.createHash = createHash;
exports.getFederationGlobalScope = getFederationGlobalScope;
exports.modifyEntry = modifyEntry;
exports.normalizeRuntimeInitOptionsWithOutShared = normalizeRuntimeInitOptionsWithOutShared;
exports.normalizeToPosixPath = normalizeToPosixPath;
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
import * as webpack$1 from "webpack";
//#region src/lib/sharing/ConsumeSharedFallbackDependency.d.ts
declare const dependencies: typeof webpack$1.dependencies;
declare class ConsumeSharedFallbackDependency extends dependencies.ModuleDependency {
layer?: string | null;
/**
* @param {string} request the request
* @param {string | null} layer the layer for the fallback module
*/
constructor(request: string, layer?: string | null);
get type(): string;
get category(): string;
}
//#endregion
export { ConsumeSharedFallbackDependency as default };
//# sourceMappingURL=ConsumeSharedFallbackDependency.d.ts.map

View File

@@ -0,0 +1,30 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/sharing/ConsumeSharedFallbackDependency.ts
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
const { dependencies } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
var ConsumeSharedFallbackDependency = class extends dependencies.ModuleDependency {
/**
* @param {string} request the request
* @param {string | null} layer the layer for the fallback module
*/
constructor(request, layer) {
super(request);
this.layer = layer;
}
get type() {
return "consume shared fallback";
}
get category() {
return "esm";
}
};
makeSerializable(ConsumeSharedFallbackDependency, "enhanced/lib/sharing/ConsumeSharedFallbackDependency");
//#endregion
exports.default = ConsumeSharedFallbackDependency;
//# sourceMappingURL=ConsumeSharedFallbackDependency.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConsumeSharedFallbackDependency.js","names":[],"sources":["../../../../src/lib/sharing/ConsumeSharedFallbackDependency.ts"],"sourcesContent":["/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy\n*/\n\n'use strict';\nimport { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';\nconst makeSerializable = require(\n normalizeWebpackPath('webpack/lib/util/makeSerializable'),\n) as typeof import('webpack/lib/util/makeSerializable');\nconst { dependencies } = require(\n normalizeWebpackPath('webpack'),\n) as typeof import('webpack');\n\nclass ConsumeSharedFallbackDependency extends dependencies.ModuleDependency {\n layer?: string | null;\n\n /**\n * @param {string} request the request\n * @param {string | null} layer the layer for the fallback module\n */\n constructor(request: string, layer?: string | null) {\n super(request);\n this.layer = layer;\n }\n\n override get type(): string {\n return 'consume shared fallback';\n }\n\n override get category(): string {\n return 'esm';\n }\n}\n\nmakeSerializable(\n ConsumeSharedFallbackDependency,\n 'enhanced/lib/sharing/ConsumeSharedFallbackDependency',\n);\n\nexport default ConsumeSharedFallbackDependency;\n"],"mappings":";;;;;;;AAOA,MAAM,mBAAmB,gFACF,oCAAoC,CAC1D;AACD,MAAM,EAAE,iBAAiB,gFACF,UAAU,CAChC;AAED,IAAM,kCAAN,cAA8C,aAAa,iBAAiB;;;;;CAO1E,YAAY,SAAiB,OAAuB;AAClD,QAAM,QAAQ;AACd,OAAK,QAAQ;;CAGf,IAAa,OAAe;AAC1B,SAAO;;CAGT,IAAa,WAAmB;AAC9B,SAAO;;;AAIX,iBACE,iCACA,uDACD"}

View File

@@ -0,0 +1,79 @@
import { ConsumeOptions } from "@module-federation/sdk";
import * as webpack$1 from "webpack";
import { CodeGenerationContext, CodeGenerationResult, Compilation as Compilation$1, Hash, InputFileSystem, LibIdentOptions, NeedBuildContext, ObjectDeserializerContext, ObjectSerializerContext, RequestShortener, ResolverWithOptions, UpdateHashContext, WebpackError, WebpackOptions } from "webpack/lib/Module";
//#region src/lib/sharing/ConsumeSharedModule.d.ts
declare const Module$1: typeof webpack$1.Module;
declare class ConsumeSharedModule extends Module$1 {
options: ConsumeOptions;
/**
* @param {string} context context
* @param {ConsumeOptions} options consume options
*/
constructor(context: string, options: ConsumeOptions);
/**
* @returns {string} a unique identifier of the module
*/
identifier(): string;
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener: RequestShortener): string;
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options: LibIdentOptions): string | null;
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context: NeedBuildContext, callback: (error?: WebpackError | null, needsRebuild?: boolean) => void): void;
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options: WebpackOptions, compilation: Compilation$1, resolver: ResolverWithOptions, fs: InputFileSystem, callback: (error?: WebpackError) => void): void;
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes(): Set<string>;
getSourceBasicTypes(): Set<string>;
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type?: string): number;
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash: Hash, context: UpdateHashContext): void;
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({
chunkGraph,
moduleGraph,
runtimeTemplate
}: CodeGenerationContext): CodeGenerationResult;
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context: ObjectSerializerContext): void;
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context: ObjectDeserializerContext): void;
}
//#endregion
export { ConsumeSharedModule as default };
//# sourceMappingURL=ConsumeSharedModule.d.ts.map

View File

@@ -0,0 +1,194 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_Constants = require('../Constants.js');
const require_lib_sharing_utils = require('./utils.js');
const require_lib_sharing_ConsumeSharedFallbackDependency = require('./ConsumeSharedFallbackDependency.js');
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
//#region src/lib/sharing/ConsumeSharedModule.ts
const { rangeToString, stringifyHoley } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/semver"));
const { AsyncDependenciesBlock, Module, RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const { sources: webpackSources } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const makeSerializable = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/makeSerializable"));
/**
* @typedef {Object} ConsumeOptions
* @property {string=} import fallback request
* @property {string=} importResolved resolved fallback request
* @property {string} shareKey global share key
* @property {string} shareScope share scope
* @property {SemVerRange | false | undefined} requiredVersion version requirement
* @property {string} packageName package name to determine required version automatically
* @property {boolean} strictVersion don't use shared version even if version isn't valid
* @property {boolean} singleton use single global version
* @property {boolean} eager include the fallback module in a sync way
* @property {string | null=} layer Share a specific layer of the module, if the module supports layers
* @property {string | null=} issuerLayer Issuer layer in which the module should be resolved
* @property {{ version?: string; fallbackVersion?: string }} exclude Options for excluding certain versions
* @property {{ version?: string; fallbackVersion?: string }} include Options for including only certain versions
*/
const TYPES = new Set(["consume-shared"]);
const JAVASCRIPT_TYPES = new Set(["javascript"]);
var ConsumeSharedModule = class extends Module {
/**
* @param {string} context context
* @param {ConsumeOptions} options consume options
*/
constructor(context, options) {
super(require_lib_Constants.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE, context, options?.layer ?? null);
this.layer = options?.layer ?? null;
this.options = options;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
const { shareKey, shareScope, importResolved, requiredVersion, strictVersion, singleton, eager, layer } = this.options;
return `${require_lib_Constants.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE}|${Array.isArray(shareScope) ? shareScope.join("|") : shareScope}|${shareKey}|${requiredVersion && rangeToString(requiredVersion)}|${strictVersion}|${importResolved}|${singleton}|${eager}|${layer}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
const { shareKey, shareScope, importResolved, requiredVersion, strictVersion, singleton, eager, layer } = this.options;
return `consume shared module (${Array.isArray(shareScope) ? shareScope.join("|") : shareScope}) ${shareKey}@${requiredVersion ? rangeToString(requiredVersion) : "*"}${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${importResolved ? ` (fallback: ${requestShortener.shorten(importResolved)})` : ""}${eager ? " (eager)" : ""}${layer ? ` (${layer})` : ""}`;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
const { shareKey, shareScope, import: request } = this.options;
const normalizedShareScope = Array.isArray(shareScope) ? shareScope.join("|") : shareScope;
return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/consume/${normalizedShareScope}/${shareKey}${request ? `/${request}` : ""}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
callback(null, !this.buildInfo);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = {};
if (this.options.import) {
const dep = new require_lib_sharing_ConsumeSharedFallbackDependency.default(this.options.import, this.options.layer);
if (this.options.eager) this.addDependency(dep);
else {
const block = new AsyncDependenciesBlock({});
block.addDependency(dep);
this.addBlock(block);
}
}
callback();
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
getSourceBasicTypes() {
return JAVASCRIPT_TYPES;
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(JSON.stringify(this.options));
super.updateHash(hash, context);
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({ chunkGraph, moduleGraph, runtimeTemplate }) {
const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]);
const { shareScope, shareKey, strictVersion, requiredVersion, import: request, singleton, eager } = this.options;
let fallbackCode;
if (request) if (eager) {
const dep = this.dependencies[0];
fallbackCode = runtimeTemplate.syncModuleFactory({
dependency: dep,
chunkGraph,
runtimeRequirements,
request: this.options.import
});
} else {
const block = this.blocks[0];
fallbackCode = runtimeTemplate.asyncModuleFactory({
block,
chunkGraph,
runtimeRequirements,
request: this.options.import
});
}
let fn = "load";
const args = [JSON.stringify(shareScope), JSON.stringify(shareKey)];
if (requiredVersion) {
if (strictVersion) fn += "Strict";
if (singleton) fn += "Singleton";
args.push(stringifyHoley(requiredVersion));
fn += "VersionCheck";
} else if (singleton) fn += "Singleton";
if (fallbackCode) {
fn += "Fallback";
args.push(fallbackCode);
}
const sources = /* @__PURE__ */ new Map();
sources.set("consume-shared", new webpackSources.RawSource(fallbackCode || `()=>()=>{throw new Error("Can not get '${shareKey}'")}`));
const data = /* @__PURE__ */ new Map();
data.set("consume-shared", require_lib_sharing_utils.normalizeConsumeShareOptions(this.options));
return {
runtimeRequirements,
sources,
data
};
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.options);
write(this.layer);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
const options = read();
const layer = read();
this.options = options;
this.layer = layer;
super.deserialize(context);
}
};
makeSerializable(ConsumeSharedModule, "enhanced/lib/sharing/ConsumeSharedModule");
//#endregion
exports.default = ConsumeSharedModule;
//# sourceMappingURL=ConsumeSharedModule.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import ConsumeSharedModule from "./ConsumeSharedModule.js";
import { ConsumeOptions, consumeSharedPlugin } from "@module-federation/sdk";
import { Compilation, Compiler } from "webpack";
//#region src/lib/sharing/ConsumeSharedPlugin.d.ts
type ConsumeSharedPluginOptions = consumeSharedPlugin.ConsumeSharedPluginOptions;
declare class ConsumeSharedPlugin {
private _consumes;
constructor(options: ConsumeSharedPluginOptions);
createConsumeSharedModule(compilation: Compilation, context: string, request: string, config: ConsumeOptions): Promise<ConsumeSharedModule>;
apply(compiler: Compiler): void;
}
//#endregion
export { ConsumeSharedPlugin as default };
//# sourceMappingURL=ConsumeSharedPlugin.d.ts.map

View File

@@ -0,0 +1,317 @@
'use strict';
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
const require_runtime = require('../../_virtual/_rolldown/runtime.js');
const require_lib_container_options = require('../container/options.js');
const require_utils = require('../../utils.js');
const require_lib_container_runtime_FederationRuntimePlugin = require('../container/runtime/FederationRuntimePlugin.js');
const require_lib_sharing_resolveMatchedConfigs = require('./resolveMatchedConfigs.js');
const require_lib_sharing_utils = require('./utils.js');
const require_lib_sharing_ConsumeSharedFallbackDependency = require('./ConsumeSharedFallbackDependency.js');
const require_lib_sharing_ConsumeSharedModule = require('./ConsumeSharedModule.js');
const require_lib_sharing_ConsumeSharedRuntimeModule = require('./ConsumeSharedRuntimeModule.js');
const require_lib_sharing_ProvideForSharedDependency = require('./ProvideForSharedDependency.js');
const require_lib_sharing_ShareRuntimeModule = require('./ShareRuntimeModule.js');
const require_schemas_sharing_ConsumeSharedPlugin_check = require('../../schemas/sharing/ConsumeSharedPlugin.check.js');
const require_schemas_sharing_ConsumeSharedPlugin = require('../../schemas/sharing/ConsumeSharedPlugin.js');
let _module_federation_sdk = require("@module-federation/sdk");
let _module_federation_sdk_normalize_webpack_path = require("@module-federation/sdk/normalize-webpack-path");
let path = require("path");
path = require_runtime.__toESM(path);
//#region src/lib/sharing/ConsumeSharedPlugin.ts
const DIRECT_FALLBACK_REGEX = /^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/;
const ABSOLUTE_PATH_REGEX = /^(\/|[A-Za-z]:|\\\\)/;
const RELATIVE_OR_ABSOLUTE_PATH_REGEX = /^(?:\.{1,2}[\\/]|\/|[A-Za-z]:|\\\\)/;
const PACKAGE_NAME_REGEX = /^((?:@[^\\/]+[\\/])?[^\\/]+)/;
const { satisfy, parseRange } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/semver"));
const ModuleNotFoundError = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/ModuleNotFoundError"));
const { RuntimeGlobals } = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack"));
const LazySet = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/util/LazySet"));
const WebpackError = require((0, _module_federation_sdk_normalize_webpack_path.normalizeWebpackPath)("webpack/lib/WebpackError"));
const validate = require_utils.createSchemaValidation((require_schemas_sharing_ConsumeSharedPlugin_check.init_ConsumeSharedPlugin_check(), require_runtime.__toCommonJS(require_schemas_sharing_ConsumeSharedPlugin_check.ConsumeSharedPlugin_check_exports)).validate, () => (require_schemas_sharing_ConsumeSharedPlugin.init_ConsumeSharedPlugin(), require_runtime.__toCommonJS(require_schemas_sharing_ConsumeSharedPlugin.ConsumeSharedPlugin_exports)).default, {
name: "Consume Shared Plugin",
baseDataPath: "options"
});
const RESOLVE_OPTIONS = { dependencyType: "esm" };
const PLUGIN_NAME = "ConsumeSharedPlugin";
var ConsumeSharedPlugin = class {
constructor(options) {
if (typeof options !== "string") validate(options);
this._consumes = require_lib_container_options.parseOptions(options.consumes, (item, key) => {
if (Array.isArray(item)) throw new Error("Unexpected array in options");
return item === key || !(0, _module_federation_sdk.isRequiredVersion)(item) ? {
import: key,
shareScope: options.shareScope || "default",
shareKey: key,
requiredVersion: void 0,
packageName: void 0,
strictVersion: false,
singleton: false,
eager: false,
issuerLayer: void 0,
layer: void 0,
request: key,
include: void 0,
exclude: void 0,
allowNodeModulesSuffixMatch: void 0,
treeShakingMode: void 0
} : {
import: key,
shareScope: options.shareScope || "default",
shareKey: key,
requiredVersion: item,
strictVersion: true,
packageName: void 0,
singleton: false,
eager: false,
issuerLayer: void 0,
layer: void 0,
request: key,
include: void 0,
exclude: void 0,
allowNodeModulesSuffixMatch: void 0,
treeShakingMode: void 0
};
}, (item, key) => {
const request = item.request || key;
return {
import: item.import === false ? void 0 : item.import || request,
shareScope: item.shareScope || options.shareScope || "default",
shareKey: item.shareKey || request,
requiredVersion: item.requiredVersion === false ? false : item.requiredVersion,
strictVersion: typeof item.strictVersion === "boolean" ? item.strictVersion : item.import !== false && !item.singleton,
packageName: item.packageName,
singleton: !!item.singleton,
eager: !!item.eager,
exclude: item.exclude,
include: item.include,
issuerLayer: item.issuerLayer ? item.issuerLayer : void 0,
layer: item.layer ? item.layer : void 0,
request,
allowNodeModulesSuffixMatch: item.allowNodeModulesSuffixMatch,
treeShakingMode: item.treeShakingMode
};
});
}
createConsumeSharedModule(compilation, context, request, config) {
const requiredVersionWarning = (details) => {
const error = new WebpackError(`No required version specified and unable to automatically determine one. ${details}`);
error.file = `shared module ${request}`;
compilation.warnings.push(error);
};
const directFallback = config.import && DIRECT_FALLBACK_REGEX.test(config.import);
const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS);
return Promise.all([new Promise((resolve) => {
if (!config.import) return resolve(void 0);
const resolveContext = {
fileDependencies: new LazySet(),
contextDependencies: new LazySet(),
missingDependencies: new LazySet()
};
resolver.resolve({}, directFallback ? compilation.compiler.context : context, config.import, resolveContext, (err, result) => {
compilation.contextDependencies.addAll(resolveContext.contextDependencies);
compilation.fileDependencies.addAll(resolveContext.fileDependencies);
compilation.missingDependencies.addAll(resolveContext.missingDependencies);
if (err) {
compilation.errors.push(new ModuleNotFoundError(null, err, { name: `resolving fallback for shared module ${request}` }));
return resolve(void 0);
}
resolve(result);
});
}), new Promise((resolve) => {
if (config.requiredVersion !== void 0) return resolve(config.requiredVersion);
let packageName = config.packageName;
if (packageName === void 0) {
if (ABSOLUTE_PATH_REGEX.test(request)) return resolve(void 0);
const match = PACKAGE_NAME_REGEX.exec(request);
if (!match) {
requiredVersionWarning("Unable to extract the package name from request.");
return resolve(void 0);
}
packageName = match[0];
}
require_lib_sharing_utils.getDescriptionFile(compilation.inputFileSystem, context, ["package.json"], (err, result, checkedDescriptionFilePaths) => {
if (err) {
requiredVersionWarning(`Unable to read description file: ${err}`);
return resolve(void 0);
}
const { data } = result || {};
if (!data) {
if (checkedDescriptionFilePaths?.length) requiredVersionWarning([
`Unable to find required version for "${packageName}" in description file/s`,
checkedDescriptionFilePaths.join("\n"),
"It need to be in dependencies, devDependencies or peerDependencies."
].join("\n"));
else requiredVersionWarning(`Unable to find description file in ${context}.`);
return resolve(void 0);
}
if (data["name"] === packageName) return resolve(void 0);
resolve(require_lib_sharing_utils.getRequiredVersionFromDescriptionFile(data, packageName));
}, (result) => {
if (!result) return false;
const { data } = result;
const maybeRequiredVersion = require_lib_sharing_utils.getRequiredVersionFromDescriptionFile(data, packageName);
return data["name"] === packageName || typeof maybeRequiredVersion === "string";
});
})]).then(([importResolved, requiredVersion]) => {
const currentConfig = {
...config,
importResolved,
import: importResolved ? config.import : void 0,
requiredVersion
};
const consumedModule = new require_lib_sharing_ConsumeSharedModule.default(directFallback ? compilation.compiler.context : context, currentConfig);
if (config.include && typeof config.include.version === "string") {
if (!importResolved) return consumedModule;
return new Promise((resolveFilter) => {
require_lib_sharing_utils.getDescriptionFile(compilation.inputFileSystem, path.default.dirname(importResolved), ["package.json"], (err, result) => {
if (err) return resolveFilter(consumedModule);
const { data } = result || {};
if (!data || !data["version"] || data["name"] !== request) return resolveFilter(consumedModule);
if (config.include && satisfy(parseRange(config.include.version), data["version"])) {
if (config.include && config.include.version && config.singleton) require_lib_sharing_utils.addSingletonFilterWarning(compilation, config.shareKey || request, "include", "version", config.include.version, request, importResolved);
return resolveFilter(consumedModule);
}
if (config.include && typeof config.include.fallbackVersion === "string" && config.include.fallbackVersion) {
if (satisfy(parseRange(config.include.version), config.include.fallbackVersion)) return resolveFilter(consumedModule);
return resolveFilter(void 0);
}
return resolveFilter(void 0);
});
});
}
if (config.exclude && typeof config.exclude.version === "string") {
if (!importResolved) return consumedModule;
if (config.exclude && typeof config.exclude.fallbackVersion === "string" && config.exclude.fallbackVersion) {
if (satisfy(parseRange(config.exclude.version), config.exclude.fallbackVersion)) return;
return consumedModule;
}
return new Promise((resolveFilter) => {
require_lib_sharing_utils.getDescriptionFile(compilation.inputFileSystem, path.default.dirname(importResolved), ["package.json"], (err, result) => {
if (err) return resolveFilter(consumedModule);
const { data } = result || {};
if (!data || !data["version"] || data["name"] !== request) return resolveFilter(consumedModule);
if (config.exclude && typeof config.exclude.version === "string" && satisfy(parseRange(config.exclude.version), data["version"])) return resolveFilter(void 0);
if (config.exclude && config.exclude.version && config.singleton) require_lib_sharing_utils.addSingletonFilterWarning(compilation, config.shareKey || request, "exclude", "version", config.exclude.version, request, importResolved);
return resolveFilter(consumedModule);
});
});
}
return consumedModule;
});
}
apply(compiler) {
new require_lib_container_runtime_FederationRuntimePlugin.default().apply(compiler);
process.env["FEDERATION_WEBPACK_PATH"] = process.env["FEDERATION_WEBPACK_PATH"] || (0, _module_federation_sdk_normalize_webpack_path.getWebpackPath)(compiler);
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(require_lib_sharing_ConsumeSharedFallbackDependency.default, normalModuleFactory);
let unresolvedConsumes, resolvedConsumes, prefixedConsumes;
const promise = require_lib_sharing_resolveMatchedConfigs.resolveMatchedConfigs(compilation, this._consumes).then(({ resolved, unresolved, prefixed }) => {
resolvedConsumes = resolved;
unresolvedConsumes = unresolved;
prefixedConsumes = prefixed;
});
normalModuleFactory.hooks.factorize.tapPromise(PLUGIN_NAME, async (resolveData) => {
const { context, request, dependencies, contextInfo } = resolveData;
const boundCreateConsumeSharedModule = this.createConsumeSharedModule.bind(this);
return promise.then(() => {
if (dependencies[0] instanceof require_lib_sharing_ConsumeSharedFallbackDependency.default || dependencies[0] instanceof require_lib_sharing_ProvideForSharedDependency.default) return;
const { context, request, contextInfo } = resolveData;
const match = unresolvedConsumes.get(require_lib_sharing_utils.createLookupKeyForSharing(request, contextInfo.issuerLayer)) || unresolvedConsumes.get(require_lib_sharing_utils.createLookupKeyForSharing(request, void 0));
if (match !== void 0) return boundCreateConsumeSharedModule(compilation, context, request, match);
let reconstructed = null;
let modulePathAfterNodeModules = null;
if (request && !path.default.isAbsolute(request) && RELATIVE_OR_ABSOLUTE_PATH_REGEX.test(request)) {
reconstructed = path.default.join(context, request);
modulePathAfterNodeModules = require_lib_sharing_utils.extractPathAfterNodeModules(reconstructed);
if (modulePathAfterNodeModules) {
const moduleMatch = unresolvedConsumes.get(require_lib_sharing_utils.createLookupKeyForSharing(modulePathAfterNodeModules, contextInfo.issuerLayer)) || unresolvedConsumes.get(require_lib_sharing_utils.createLookupKeyForSharing(modulePathAfterNodeModules, void 0));
if (moduleMatch !== void 0 && moduleMatch.allowNodeModulesSuffixMatch) return boundCreateConsumeSharedModule(compilation, context, modulePathAfterNodeModules, moduleMatch);
}
const reconstructedMatch = unresolvedConsumes.get(require_lib_sharing_utils.createLookupKeyForSharing(reconstructed, contextInfo.issuerLayer)) || unresolvedConsumes.get(require_lib_sharing_utils.createLookupKeyForSharing(reconstructed, void 0));
if (reconstructedMatch !== void 0) return boundCreateConsumeSharedModule(compilation, context, reconstructed, reconstructedMatch);
}
for (const [prefix, options] of prefixedConsumes) {
const lookup = options.request || prefix;
if (options.issuerLayer) {
if (!contextInfo.issuerLayer) continue;
if (contextInfo.issuerLayer !== options.issuerLayer) continue;
}
if (request.startsWith(lookup)) {
const remainder = request.slice(lookup.length);
if (!require_lib_sharing_utils.testRequestFilters(remainder, options.include?.request, options.exclude?.request)) continue;
return boundCreateConsumeSharedModule(compilation, context, request, {
...options,
import: options.import ? options.import + remainder : void 0,
shareKey: options.shareKey + remainder,
layer: options.layer
});
}
}
if (modulePathAfterNodeModules) for (const [prefix, options] of prefixedConsumes) {
if (!options.allowNodeModulesSuffixMatch) continue;
if (options.issuerLayer) {
if (!contextInfo.issuerLayer) continue;
if (contextInfo.issuerLayer !== options.issuerLayer) continue;
}
const lookup = options.request || prefix;
if (modulePathAfterNodeModules.startsWith(lookup)) {
const remainder = modulePathAfterNodeModules.slice(lookup.length);
if (!require_lib_sharing_utils.testRequestFilters(remainder, options.include?.request, options.exclude?.request)) continue;
return boundCreateConsumeSharedModule(compilation, context, modulePathAfterNodeModules, {
...options,
import: options.import ? options.import + remainder : void 0,
shareKey: options.shareKey + remainder,
layer: options.layer
});
}
}
});
});
normalModuleFactory.hooks.createModule.tapPromise(PLUGIN_NAME, ({ resource }, { context, dependencies }) => {
const boundCreateConsumeSharedModule = this.createConsumeSharedModule.bind(this);
if (dependencies[0] instanceof require_lib_sharing_ConsumeSharedFallbackDependency.default || dependencies[0] instanceof require_lib_sharing_ProvideForSharedDependency.default) return Promise.resolve();
if (resource) {
const options = resolvedConsumes.get(resource);
if (options !== void 0) return boundCreateConsumeSharedModule(compilation, context, resource, options);
}
return Promise.resolve();
});
compilation.hooks.finishModules.tapAsync({
name: PLUGIN_NAME,
stage: 10
}, (modules, callback) => {
for (const module of modules) {
if (!(module instanceof require_lib_sharing_ConsumeSharedModule.default) || !module.options.import) continue;
let dependency;
if (module.options.eager) dependency = module.dependencies[0];
else dependency = module.blocks[0]?.dependencies[0];
if (dependency) {
const fallbackModule = compilation.moduleGraph.getModule(dependency);
if (fallbackModule && fallbackModule.buildMeta && fallbackModule.buildInfo) {
module.buildMeta = { ...fallbackModule.buildMeta };
module.buildInfo = { ...fallbackModule.buildInfo };
compilation.moduleGraph.getExportsInfo(module).setUnknownExportsProvided();
}
}
}
callback();
});
compilation.hooks.additionalTreeRuntimeRequirements.tap(PLUGIN_NAME, (chunk, set) => {
set.add(RuntimeGlobals.module);
set.add(RuntimeGlobals.moduleCache);
set.add(RuntimeGlobals.moduleFactoriesAddOnly);
set.add(RuntimeGlobals.shareScopeMap);
set.add(RuntimeGlobals.initializeSharing);
set.add(RuntimeGlobals.hasOwnProperty);
compilation.addRuntimeModule(chunk, new require_lib_sharing_ConsumeSharedRuntimeModule.default(set));
compilation.addRuntimeModule(chunk, new require_lib_sharing_ShareRuntimeModule.default());
});
});
}
};
//#endregion
exports.default = ConsumeSharedPlugin;
//# sourceMappingURL=ConsumeSharedPlugin.js.map

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More