@module-federation/data-prefetch 1.0.16 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -1
  3. package/dist/LICENSE +21 -0
  4. package/dist/babel.cjs +95 -0
  5. package/dist/babel.d.ts +1 -0
  6. package/dist/babel.js +5 -0
  7. package/dist/cli/babel.cjs +115 -0
  8. package/dist/cli/babel.d.ts +2 -4
  9. package/dist/cli/babel.js +50 -82
  10. package/dist/cli/index.cjs +217 -0
  11. package/dist/cli/index.d.ts +5 -8
  12. package/dist/cli/index.js +150 -197
  13. package/dist/cli.cjs +95 -0
  14. package/dist/cli.d.ts +1 -0
  15. package/dist/cli.js +5 -0
  16. package/dist/common/constant.cjs +51 -0
  17. package/dist/common/constant.d.ts +1 -0
  18. package/dist/common/constant.js +5 -0
  19. package/dist/common/index.cjs +95 -0
  20. package/dist/common/index.js +5 -0
  21. package/dist/common/node-utils.cjs +100 -0
  22. package/dist/common/node-utils.d.ts +2 -0
  23. package/dist/common/node-utils.js +35 -0
  24. package/dist/common/runtime-utils.cjs +84 -0
  25. package/dist/common/runtime-utils.d.ts +5 -0
  26. package/dist/common/runtime-utils.js +29 -0
  27. package/dist/constant.cjs +51 -0
  28. package/dist/constant.d.ts +1 -0
  29. package/dist/constant.js +5 -0
  30. package/dist/index.cjs +106 -0
  31. package/dist/index.d.ts +2 -5
  32. package/dist/index.js +3 -346
  33. package/dist/logger/index.cjs +60 -0
  34. package/dist/logger/index.d.ts +2 -0
  35. package/dist/logger/index.js +10 -0
  36. package/dist/plugin.cjs +234 -0
  37. package/dist/plugin.d.ts +3 -5
  38. package/dist/plugin.js +167 -340
  39. package/dist/prefetch.cjs +197 -0
  40. package/dist/{prefetch-4e9646e4.d.ts → prefetch.d.ts} +14 -17
  41. package/dist/prefetch.js +149 -0
  42. package/dist/react/hooks.cjs +144 -0
  43. package/dist/react/hooks.d.ts +11 -0
  44. package/dist/react/hooks.js +86 -0
  45. package/dist/react/index.cjs +95 -0
  46. package/dist/react/index.d.ts +1 -16
  47. package/dist/react/index.js +2 -283
  48. package/dist/react/utils.cjs +65 -0
  49. package/dist/react/utils.d.ts +1 -0
  50. package/dist/react/utils.js +15 -0
  51. package/dist/react.cjs +95 -0
  52. package/dist/react.d.ts +1 -0
  53. package/dist/react.js +5 -0
  54. package/dist/universal/index.cjs +81 -0
  55. package/dist/universal/index.d.ts +2 -8
  56. package/dist/universal/index.js +24 -196
  57. package/dist/universal.cjs +95 -0
  58. package/dist/universal.d.ts +1 -0
  59. package/dist/universal.js +5 -0
  60. package/package.json +76 -40
  61. package/CHANGELOG.md +0 -9
  62. package/__tests__/babel.spec.ts +0 -75
  63. package/__tests__/prefetch.spec.ts +0 -138
  64. package/__tests__/react.spec.ts +0 -119
  65. package/dist/esm/chunk-AJPO2B2T.js +0 -30
  66. package/dist/esm/chunk-EZUCZHGV.js +0 -11
  67. package/dist/esm/chunk-ISLXMAIA.js +0 -155
  68. package/dist/esm/chunk-KI4QGPIS.js +0 -32
  69. package/dist/esm/chunk-TTJJJ2WZ.js +0 -7
  70. package/dist/esm/chunk-VVZ6XIM6.js +0 -166
  71. package/dist/esm/cli/babel.js +0 -57
  72. package/dist/esm/cli/index.js +0 -178
  73. package/dist/esm/index.js +0 -13
  74. package/dist/esm/plugin.js +0 -12
  75. package/dist/esm/react/index.js +0 -94
  76. package/dist/esm/shared/index.js +0 -27
  77. package/dist/esm/universal/index.js +0 -9
  78. package/dist/shared/index.d.ts +0 -5
  79. package/dist/shared/index.js +0 -48
  80. package/jest.config.js +0 -29
  81. package/project.json +0 -21
  82. package/src/cli/babel.ts +0 -94
  83. package/src/cli/index.ts +0 -171
  84. package/src/common/constant.ts +0 -1
  85. package/src/common/node-utils.ts +0 -24
  86. package/src/common/runtime-utils.ts +0 -34
  87. package/src/index.ts +0 -2
  88. package/src/logger/index.ts +0 -3
  89. package/src/plugin.ts +0 -191
  90. package/src/prefetch.ts +0 -207
  91. package/src/react/hooks.ts +0 -95
  92. package/src/react/index.ts +0 -1
  93. package/src/react/utils.ts +0 -11
  94. package/src/shared/index.ts +0 -26
  95. package/src/universal/index.ts +0 -27
  96. package/tsconfig.json +0 -27
  97. package/tsup.config.ts +0 -35
  98. /package/{src/common/index.ts → dist/common/index.d.ts} +0 -0
@@ -1,57 +0,0 @@
1
- import "../chunk-EZUCZHGV.js";
2
-
3
- // src/cli/babel.ts
4
- import path from "path";
5
- var attribute = "id";
6
- var hookId = "usePrefetch";
7
- var importPackage = "@module-federation/data-prefetch/react";
8
- var babel_default = (babel, options) => {
9
- const t = babel.types;
10
- let shouldHandle = false;
11
- let scope = "";
12
- const { name, exposes } = options;
13
- if (!exposes) {
14
- return {};
15
- }
16
- const exposesKey = Object.keys(exposes);
17
- const processedExposes = exposesKey.map((expose) => ({
18
- key: expose.replace(".", ""),
19
- value: path.resolve(
20
- typeof exposes[expose] === "string" ? exposes[expose] : exposes[expose].import
21
- )
22
- }));
23
- return {
24
- visitor: {
25
- ImportDeclaration(nodePath, state) {
26
- const source = nodePath.node.source.value;
27
- const { specifiers } = nodePath.node;
28
- const { filename } = state.file.opts;
29
- if (source === importPackage) {
30
- shouldHandle = specifiers.some(
31
- (specifier) => specifier.imported && specifier.imported.name === hookId && processedExposes.find(
32
- (expose) => expose.value === filename && (scope = expose.key)
33
- )
34
- );
35
- }
36
- },
37
- CallExpression(nodePath) {
38
- if (shouldHandle && t.isIdentifier(nodePath.node.callee, { name: hookId }) && nodePath.node.arguments.length > 0) {
39
- const objectExpression = nodePath.node.arguments[0];
40
- if (objectExpression && t.isObjectExpression(objectExpression) && !objectExpression.properties.find(
41
- (p) => p.key.name === attribute
42
- )) {
43
- objectExpression.properties.push(
44
- t.objectProperty(
45
- t.identifier(attribute),
46
- t.stringLiteral(name + scope)
47
- )
48
- );
49
- }
50
- }
51
- }
52
- }
53
- };
54
- };
55
- export {
56
- babel_default as default
57
- };
@@ -1,178 +0,0 @@
1
- import {
2
- getPrefetchId
3
- } from "../chunk-AJPO2B2T.js";
4
- import {
5
- __require
6
- } from "../chunk-EZUCZHGV.js";
7
-
8
- // src/cli/index.ts
9
- import path2 from "path";
10
- import fs2 from "fs-extra";
11
- import {
12
- encodeName,
13
- MFPrefetchCommon
14
- } from "@module-federation/sdk";
15
- import { normalizeWebpackPath } from "@module-federation/sdk/normalize-webpack-path";
16
-
17
- // src/common/constant.ts
18
- var TEMP_DIR = ".mf";
19
-
20
- // src/common/node-utils.ts
21
- import path from "path";
22
- import fs from "fs-extra";
23
- var fileExistsWithCaseSync = (filepath) => {
24
- const dir = path.dirname(filepath);
25
- if (filepath === "/" || filepath === ".") {
26
- return true;
27
- }
28
- const filenames = fs.readdirSync(dir);
29
- if (filenames.indexOf(path.basename(filepath)) === -1) {
30
- return false;
31
- }
32
- return fileExistsWithCaseSync(dir);
33
- };
34
- var fixPrefetchPath = (exposePath) => {
35
- const pathExt = [".js", ".ts"];
36
- const extReg = /\.(ts|js|tsx|jsx)$/;
37
- if (extReg.test(exposePath)) {
38
- return pathExt.map((ext) => exposePath.replace(extReg, `.prefetch${ext}`));
39
- } else {
40
- return pathExt.map((ext) => exposePath + `.prefetch${ext}`);
41
- }
42
- };
43
-
44
- // src/cli/index.ts
45
- var { RuntimeGlobals, Template } = __require(normalizeWebpackPath("webpack"));
46
- function getFederationGlobalScope(runtimeGlobals) {
47
- return `${runtimeGlobals.require || "__webpack_require__"}.federation`;
48
- }
49
- var PrefetchPlugin = class {
50
- constructor(options) {
51
- this.options = options;
52
- this._reWriteExports = "";
53
- }
54
- apply(compiler) {
55
- var _a, _b;
56
- const { name, exposes } = this.options;
57
- if (!exposes) {
58
- return;
59
- }
60
- if (!compiler.options.context) {
61
- throw new Error("compiler.options.context is not defined");
62
- }
63
- const { runtimePlugins } = this.options;
64
- if (!Array.isArray(runtimePlugins)) {
65
- this.options.runtimePlugins = [];
66
- }
67
- const runtimePath = path2.resolve(__dirname, "../esm/plugin.js");
68
- const sharedPath = path2.resolve(__dirname, "../esm/shared/index.js");
69
- if (!((_a = this.options.runtimePlugins) == null ? void 0 : _a.includes(runtimePath))) {
70
- this.options.runtimePlugins.push(runtimePath);
71
- }
72
- if (!((_b = this.options.runtimePlugins) == null ? void 0 : _b.includes(sharedPath))) {
73
- this.options.runtimePlugins.push(sharedPath);
74
- }
75
- const encodedName = encodeName(name);
76
- const asyncEntryPath = path2.resolve(
77
- compiler.options.context,
78
- `node_modules/${TEMP_DIR}/${encodedName}/bootstrap.js`
79
- );
80
- if (fs2.existsSync(asyncEntryPath)) {
81
- fs2.unlinkSync(asyncEntryPath);
82
- }
83
- if (!this.options.dataPrefetch) {
84
- return;
85
- }
86
- const prefetchs = [];
87
- const exposeAlias = Object.keys(exposes);
88
- exposeAlias.forEach((alias) => {
89
- let exposePath;
90
- const exposeValue = exposes[alias];
91
- if (typeof exposeValue === "string") {
92
- exposePath = exposeValue;
93
- } else {
94
- exposePath = exposeValue.import[0];
95
- }
96
- const targetPaths = fixPrefetchPath(exposePath);
97
- for (const pathItem of targetPaths) {
98
- const absolutePath = path2.resolve(compiler.options.context, pathItem);
99
- if (fileExistsWithCaseSync(absolutePath)) {
100
- prefetchs.push(pathItem);
101
- const absoluteAlias = alias.replace(".", "");
102
- this._reWriteExports += `export * as ${getPrefetchId(
103
- `${name}${absoluteAlias}`
104
- )} from '${absolutePath}';
105
- `;
106
- break;
107
- }
108
- }
109
- });
110
- if (!this._reWriteExports) {
111
- return;
112
- }
113
- const tempDirRealPath = path2.resolve(
114
- compiler.options.context,
115
- "node_modules",
116
- TEMP_DIR
117
- );
118
- if (!fs2.existsSync(tempDirRealPath)) {
119
- fs2.mkdirSync(tempDirRealPath);
120
- }
121
- if (!fs2.existsSync(`${tempDirRealPath}/${encodedName}`)) {
122
- fs2.mkdirSync(`${tempDirRealPath}/${encodedName}`);
123
- }
124
- fs2.writeFileSync(asyncEntryPath, this._reWriteExports);
125
- new compiler.webpack.DefinePlugin({
126
- FederationDataPrefetch: JSON.stringify(asyncEntryPath)
127
- }).apply(compiler);
128
- }
129
- static addRuntime(compiler, options) {
130
- const encodedName = encodeName(options.name);
131
- if (!compiler.options.context) {
132
- throw new Error("compiler.options.context is not defined");
133
- }
134
- const prefetchEntry = path2.resolve(
135
- compiler.options.context,
136
- `node_modules/.mf/${encodedName}/bootstrap.js`
137
- );
138
- const federationGlobal = getFederationGlobalScope(
139
- RuntimeGlobals || {}
140
- );
141
- return Template.asString([
142
- fs2.existsSync(prefetchEntry) ? Template.indent([
143
- "function injectPrefetch() {",
144
- `globalThis.__FEDERATION__ = globalThis.__FEDERATION__ || {};`,
145
- `globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}'] = globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}'] || {`,
146
- `entryLoading: {},`,
147
- `instance: new Map(),`,
148
- `__PREFETCH_EXPORTS__: {},`,
149
- `};`,
150
- `globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}']['${MFPrefetchCommon.exportsKey}'] = globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}']['${MFPrefetchCommon.exportsKey}'] || {};`,
151
- `globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}']['${MFPrefetchCommon.exportsKey}']['${options.name}'] = import('${prefetchEntry}');`,
152
- "}",
153
- `${federationGlobal}.prefetch = injectPrefetch`
154
- ]) : "",
155
- Template.indent([
156
- `if(!${federationGlobal}.isMFRemote && ${federationGlobal}.prefetch){`,
157
- `${federationGlobal}.prefetch()`,
158
- "}"
159
- ])
160
- ]);
161
- }
162
- static setRemoteIdentifier() {
163
- const federationGlobal = getFederationGlobalScope(
164
- RuntimeGlobals || {}
165
- );
166
- return Template.indent([`${federationGlobal}.isMFRemote = true;`]);
167
- }
168
- static removeRemoteIdentifier() {
169
- const federationGlobal = getFederationGlobalScope(
170
- RuntimeGlobals || {}
171
- );
172
- return Template.indent([`${federationGlobal}.isMFRemote = false;`]);
173
- }
174
- };
175
- export {
176
- PrefetchPlugin,
177
- getFederationGlobalScope
178
- };
package/dist/esm/index.js DELETED
@@ -1,13 +0,0 @@
1
- import {
2
- prefetchPlugin
3
- } from "./chunk-VVZ6XIM6.js";
4
- import "./chunk-TTJJJ2WZ.js";
5
- import {
6
- MFDataPrefetch
7
- } from "./chunk-ISLXMAIA.js";
8
- import "./chunk-AJPO2B2T.js";
9
- import "./chunk-EZUCZHGV.js";
10
- export {
11
- MFDataPrefetch,
12
- prefetchPlugin
13
- };
@@ -1,12 +0,0 @@
1
- import {
2
- plugin_default,
3
- prefetchPlugin
4
- } from "./chunk-VVZ6XIM6.js";
5
- import "./chunk-TTJJJ2WZ.js";
6
- import "./chunk-ISLXMAIA.js";
7
- import "./chunk-AJPO2B2T.js";
8
- import "./chunk-EZUCZHGV.js";
9
- export {
10
- plugin_default as default,
11
- prefetchPlugin
12
- };
@@ -1,94 +0,0 @@
1
- import {
2
- prefetch
3
- } from "../chunk-KI4QGPIS.js";
4
- import {
5
- logger_default
6
- } from "../chunk-TTJJJ2WZ.js";
7
- import {
8
- MFDataPrefetch
9
- } from "../chunk-ISLXMAIA.js";
10
- import {
11
- getScope
12
- } from "../chunk-AJPO2B2T.js";
13
- import "../chunk-EZUCZHGV.js";
14
-
15
- // src/react/hooks.ts
16
- import { useEffect as useEffect2, useState } from "react";
17
-
18
- // src/react/utils.ts
19
- import { useEffect, useRef } from "react";
20
- var useFirstMounted = () => {
21
- const ref = useRef(true);
22
- useEffect(() => {
23
- ref.current = false;
24
- }, []);
25
- return ref.current;
26
- };
27
-
28
- // src/react/hooks.ts
29
- var usePrefetch = (options) => {
30
- const isFirstMounted = useFirstMounted();
31
- if (isFirstMounted) {
32
- const startTiming = performance.now();
33
- logger_default.info(
34
- `2. Start Get Prefetch Data: ${options.id} - ${options.functionId || "default"} - ${startTiming}`
35
- );
36
- }
37
- const { id, functionId, deferId } = options;
38
- const prefetchInfo = {
39
- id,
40
- functionId
41
- };
42
- const mfScope = getScope();
43
- let state;
44
- const prefetchResult = prefetch(options);
45
- if (deferId) {
46
- if (prefetchResult instanceof Promise) {
47
- state = prefetchResult.then(
48
- (deferredData) => deferredData.data[deferId]
49
- );
50
- } else {
51
- state = prefetchResult.data[deferId];
52
- }
53
- } else {
54
- state = prefetchResult;
55
- }
56
- const [prefetchState, setPrefetchState] = useState(
57
- state
58
- );
59
- const prefetchInstance = MFDataPrefetch.getInstance(mfScope);
60
- useEffect2(() => {
61
- const useEffectTiming = performance.now();
62
- logger_default.info(
63
- `3. Start Execute UseEffect: ${options.id} - ${options.functionId || "default"} - ${useEffectTiming}`
64
- );
65
- return () => {
66
- prefetchInstance == null ? void 0 : prefetchInstance.markOutdate(prefetchInfo, true);
67
- };
68
- }, []);
69
- const refreshExecutor = (refetchParams) => {
70
- const refetchOptions = {
71
- ...options
72
- };
73
- if (refetchParams) {
74
- refetchOptions.refetchParams = refetchParams;
75
- }
76
- prefetchInstance == null ? void 0 : prefetchInstance.markOutdate(prefetchInfo, true);
77
- const newVal = prefetch(refetchOptions);
78
- let newState;
79
- if (deferId) {
80
- if (newVal instanceof Promise) {
81
- newState = newVal.then((deferredData) => deferredData.data[deferId]);
82
- } else {
83
- newState = newVal.data[deferId];
84
- }
85
- } else {
86
- newState = newVal;
87
- }
88
- setPrefetchState(newState);
89
- };
90
- return [prefetchState, refreshExecutor];
91
- };
92
- export {
93
- usePrefetch
94
- };
@@ -1,27 +0,0 @@
1
- import "../chunk-EZUCZHGV.js";
2
-
3
- // src/shared/index.ts
4
- var sharedStrategy = () => ({
5
- name: "shared-strategy",
6
- beforeInit(args) {
7
- const { userOptions } = args;
8
- const shared = userOptions.shared;
9
- if (shared) {
10
- Object.keys(shared).forEach((sharedKey) => {
11
- const sharedConfigs = shared[sharedKey];
12
- const arraySharedConfigs = Array.isArray(sharedConfigs) ? sharedConfigs : [sharedConfigs];
13
- arraySharedConfigs.forEach((s) => {
14
- s.strategy = "loaded-first";
15
- });
16
- });
17
- console.warn(
18
- `[Module Federation Data Prefetch]: Your shared strategy is set to 'loaded-first', this is a necessary condition for data prefetch`
19
- );
20
- }
21
- return args;
22
- }
23
- });
24
- var shared_default = sharedStrategy;
25
- export {
26
- shared_default as default
27
- };
@@ -1,9 +0,0 @@
1
- import {
2
- prefetch
3
- } from "../chunk-KI4QGPIS.js";
4
- import "../chunk-ISLXMAIA.js";
5
- import "../chunk-AJPO2B2T.js";
6
- import "../chunk-EZUCZHGV.js";
7
- export {
8
- prefetch
9
- };
@@ -1,5 +0,0 @@
1
- import { FederationRuntimePlugin } from '@module-federation/runtime';
2
-
3
- declare const sharedStrategy: () => FederationRuntimePlugin;
4
-
5
- export { sharedStrategy as default };
@@ -1,48 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/shared/index.ts
21
- var shared_exports = {};
22
- __export(shared_exports, {
23
- default: () => shared_default
24
- });
25
- module.exports = __toCommonJS(shared_exports);
26
- var sharedStrategy = () => ({
27
- name: "shared-strategy",
28
- beforeInit(args) {
29
- const { userOptions } = args;
30
- const shared = userOptions.shared;
31
- if (shared) {
32
- Object.keys(shared).forEach((sharedKey) => {
33
- const sharedConfigs = shared[sharedKey];
34
- const arraySharedConfigs = Array.isArray(sharedConfigs) ? sharedConfigs : [sharedConfigs];
35
- arraySharedConfigs.forEach((s) => {
36
- s.strategy = "loaded-first";
37
- });
38
- });
39
- console.warn(
40
- `[Module Federation Data Prefetch]: Your shared strategy is set to 'loaded-first', this is a necessary condition for data prefetch`
41
- );
42
- }
43
- return args;
44
- }
45
- });
46
- var shared_default = sharedStrategy;
47
- // Annotate the CommonJS export names for ESM import in node:
48
- 0 && (module.exports = {});
package/jest.config.js DELETED
@@ -1,29 +0,0 @@
1
- // For a detailed explanation regarding each configuration property, visit:
2
- // https://jestjs.io/docs/en/configuration.html
3
-
4
- module.exports = {
5
- clearMocks: true,
6
- cacheDirectory: './jest/cache',
7
- coverageDirectory: './jest/coverage',
8
- testEnvironment: 'jsdom',
9
- coveragePathIgnorePatterns: ['__tests__', '/node_modules/'],
10
- coverageProvider: 'v8',
11
- coverageReporters: ['cobertura', 'clover', 'json', 'lcov', 'text'],
12
- globals: {
13
- __DEV__: true,
14
- __TEST__: true,
15
- __BROWSER__: false,
16
- __VERSION__: '"unknow"',
17
- },
18
- preset: 'ts-jest',
19
- transformIgnorePatterns: [
20
- // Change MODULE_NAME_HERE to your module that isn't being compiled
21
- '/node_modules/(?!((@byted/garfish-)|(byted-tea-sdk))).+\\.js$',
22
- ],
23
- transform: {
24
- '^.+\\.(t|j)sx?$': ['@swc/jest', { swcrc: false }],
25
- },
26
- rootDir: __dirname,
27
- testMatch: ['<rootDir>__tests__/**/**.spec.[jt]s?(x)'],
28
- testPathIgnorePatterns: ['/node_modules/', '/dev/'],
29
- };
package/project.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "name": "module-federation/data-prefetch",
3
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
4
- "sourceRoot": "packages/data-prefetch/src",
5
- "projectType": "library",
6
- "targets": {
7
- "build": {
8
- "executor": "nx:run-commands",
9
- "options": {
10
- "commands": ["npm run build --prefix packages/data-prefetch"]
11
- }
12
- },
13
- "test": {
14
- "executor": "nx:run-commands",
15
- "options": {
16
- "commands": ["npm run test --prefix packages/data-prefetch"]
17
- }
18
- }
19
- },
20
- "tags": ["type:pkg"]
21
- }
package/src/cli/babel.ts DELETED
@@ -1,94 +0,0 @@
1
- // no used now
2
- import path from 'path';
3
- import type { moduleFederationPlugin } from '@module-federation/sdk';
4
-
5
- const attribute = 'id';
6
- const hookId = 'usePrefetch';
7
- const importPackage = '@module-federation/data-prefetch/react';
8
-
9
- interface BabelPluginOptions {
10
- hook_id: string;
11
- import_pkg: string;
12
- attribute: string;
13
- name: string;
14
- exposes: moduleFederationPlugin.ModuleFederationPluginOptions['exposes'];
15
- }
16
-
17
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
18
- export default (babel: { types: any }, options: BabelPluginOptions) => {
19
- const t = babel.types;
20
- let shouldHandle = false;
21
- let scope = '';
22
- const { name, exposes } = options;
23
- if (!exposes) {
24
- return {};
25
- }
26
- const exposesKey = Object.keys(exposes);
27
- const processedExposes = exposesKey.map((expose) => ({
28
- key: expose.replace('.', ''),
29
- value: path.resolve(
30
- // @ts-ignore
31
- typeof exposes[expose] === 'string'
32
- ? // @ts-ignore
33
- exposes[expose]
34
- : // @ts-ignore
35
- exposes[expose].import,
36
- ),
37
- }));
38
-
39
- return {
40
- visitor: {
41
- ImportDeclaration(
42
- nodePath: {
43
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
44
- node: { source: { value: any }; specifiers: any };
45
- },
46
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
47
- state: { file: { opts: { filename: any } } },
48
- ) {
49
- const source = nodePath.node.source.value;
50
- const { specifiers } = nodePath.node;
51
- const { filename } = state.file.opts;
52
-
53
- if (source === importPackage) {
54
- shouldHandle = specifiers.some(
55
- (specifier: { imported: { name: string } }) =>
56
- specifier.imported &&
57
- specifier.imported.name === hookId &&
58
- processedExposes.find(
59
- // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
60
- (expose) => expose.value === filename && (scope = expose.key),
61
- ),
62
- );
63
- }
64
- },
65
-
66
- CallExpression(nodePath: {
67
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
68
- node: { callee: any; arguments: string | any[] };
69
- }) {
70
- if (
71
- shouldHandle &&
72
- t.isIdentifier(nodePath.node.callee, { name: hookId }) &&
73
- nodePath.node.arguments.length > 0
74
- ) {
75
- const objectExpression = nodePath.node.arguments[0];
76
- if (
77
- objectExpression &&
78
- t.isObjectExpression(objectExpression) &&
79
- !objectExpression.properties.find(
80
- (p: { key: { name: string } }) => p.key.name === attribute,
81
- )
82
- ) {
83
- objectExpression.properties.push(
84
- t.objectProperty(
85
- t.identifier(attribute),
86
- t.stringLiteral(name + scope),
87
- ),
88
- );
89
- }
90
- }
91
- },
92
- },
93
- };
94
- };