@rsdoctor/core 2.0.0-alpha.1 → 2.0.0-beta.0

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 (177) hide show
  1. package/dist/26.js +26174 -0
  2. package/dist/630.js +1280 -0
  3. package/dist/630.js.LICENSE.txt +7 -0
  4. package/dist/build-utils/build/chunks/assetsModules.d.ts +7 -1
  5. package/dist/build-utils/build/loader/probeLoader.d.ts +7 -2
  6. package/dist/build-utils/build/server.d.ts +1 -2
  7. package/dist/build-utils/build/utils/parseBundle.d.ts +1 -1
  8. package/dist/index.d.ts +5 -5
  9. package/dist/index.js +1908 -7
  10. package/dist/inner-plugins/constants.d.ts +1 -1
  11. package/dist/inner-plugins/plugins/base.d.ts +2 -2
  12. package/dist/inner-plugins/plugins/errors.d.ts +1 -0
  13. package/dist/inner-plugins/plugins/plugins.d.ts +1 -1
  14. package/dist/inner-plugins/plugins/summary.d.ts +3 -2
  15. package/dist/inner-plugins/utils/sdk.d.ts +2 -1
  16. package/dist/logger.d.ts +2 -2
  17. package/dist/probe-loader.js +2 -0
  18. package/dist/proxy-loader.d.ts +1 -0
  19. package/dist/proxy-loader.js +48 -0
  20. package/dist/rslib-runtime.js +28 -0
  21. package/dist/rspack-plugin/constants.d.ts +1 -1
  22. package/dist/rspack-plugin/multiple.d.ts +5 -3
  23. package/dist/rspack-plugin/plugin.d.ts +43 -17
  24. package/dist/rspack-plugin/session.d.ts +20 -0
  25. package/dist/rules/rules/ecma-version-check/htmlParserStub.d.ts +3 -0
  26. package/dist/rules/rules/ecma-version-check/types.d.ts +13 -2
  27. package/dist/sdk/multiple/controller.d.ts +13 -2
  28. package/dist/sdk/multiple/primary.d.ts +12 -4
  29. package/dist/sdk/server/apis/base.d.ts +1 -1
  30. package/dist/sdk/server/socket/api.d.ts +1 -1
  31. package/dist/sdk/utils/date.d.ts +1 -0
  32. package/dist/types/loader.d.ts +1 -1
  33. package/package.json +23 -117
  34. package/dist/build-utils/build/chunks/assetsModules.js +0 -9
  35. package/dist/build-utils/build/chunks/index.js +0 -3
  36. package/dist/build-utils/build/chunks/rspack/transform.js +0 -44
  37. package/dist/build-utils/build/envinfo.js +0 -60
  38. package/dist/build-utils/build/file/cache.js +0 -24
  39. package/dist/build-utils/build/file/index.js +0 -5
  40. package/dist/build-utils/build/file/sharding.js +0 -38
  41. package/dist/build-utils/build/index.js +0 -12
  42. package/dist/build-utils/build/json.js +0 -67
  43. package/dist/build-utils/build/loader/index.js +0 -3
  44. package/dist/build-utils/build/loader/probeLoader.js +0 -44
  45. package/dist/build-utils/build/loader/probeLoaderPlugin.js +0 -32
  46. package/dist/build-utils/build/module-graph/index.js +0 -2
  47. package/dist/build-utils/build/module-graph/parser.js +0 -13
  48. package/dist/build-utils/build/module-graph/rspack/transform.js +0 -111
  49. package/dist/build-utils/build/module-graph/utils.js +0 -60
  50. package/dist/build-utils/build/process.js +0 -18
  51. package/dist/build-utils/build/server.js +0 -107
  52. package/dist/build-utils/build/utils/index.js +0 -4
  53. package/dist/build-utils/build/utils/loader.js +0 -267
  54. package/dist/build-utils/build/utils/parseBundle.js +0 -238
  55. package/dist/build-utils/build/utils/plugin.js +0 -21
  56. package/dist/build-utils/index.js +0 -13
  57. package/dist/collection.d.ts +0 -1
  58. package/dist/collection.js +0 -2
  59. package/dist/common/file.js +0 -8
  60. package/dist/common/global-config.js +0 -33
  61. package/dist/common/index.d.ts +0 -4
  62. package/dist/common/index.js +0 -6
  63. package/dist/common-browser.d.ts +0 -1
  64. package/dist/common-browser.js +0 -2
  65. package/dist/error/error.js +0 -143
  66. package/dist/error/index.js +0 -3
  67. package/dist/error/transform.js +0 -138
  68. package/dist/error/utils.js +0 -23
  69. package/dist/graph/index.d.ts +0 -1
  70. package/dist/graph/index.js +0 -2
  71. package/dist/inner-plugins/constants.js +0 -19
  72. package/dist/inner-plugins/index.js +0 -3
  73. package/dist/inner-plugins/loaders/proxy.js +0 -65
  74. package/dist/inner-plugins/plugins/base.js +0 -20
  75. package/dist/inner-plugins/plugins/bundle.js +0 -63
  76. package/dist/inner-plugins/plugins/ensureModulesChunkGraph.js +0 -74
  77. package/dist/inner-plugins/plugins/errors.js +0 -65
  78. package/dist/inner-plugins/plugins/index.js +0 -11
  79. package/dist/inner-plugins/plugins/loader.js +0 -108
  80. package/dist/inner-plugins/plugins/plugins.js +0 -40
  81. package/dist/inner-plugins/plugins/progress.js +0 -35
  82. package/dist/inner-plugins/plugins/resolver.js +0 -57
  83. package/dist/inner-plugins/plugins/rspack.js +0 -99
  84. package/dist/inner-plugins/plugins/rules.js +0 -64
  85. package/dist/inner-plugins/plugins/sourcemapTool.js +0 -230
  86. package/dist/inner-plugins/plugins/summary.js +0 -92
  87. package/dist/inner-plugins/utils/circleDetect.js +0 -16
  88. package/dist/inner-plugins/utils/config.js +0 -141
  89. package/dist/inner-plugins/utils/index.js +0 -8
  90. package/dist/inner-plugins/utils/loader.js +0 -134
  91. package/dist/inner-plugins/utils/normalize-config.js +0 -77
  92. package/dist/inner-plugins/utils/openBrowser.js +0 -55
  93. package/dist/inner-plugins/utils/plugin-common.js +0 -94
  94. package/dist/inner-plugins/utils/plugin.js +0 -70
  95. package/dist/inner-plugins/utils/sdk.js +0 -19
  96. package/dist/logger.js +0 -51
  97. package/dist/rspack-plugin/constants.js +0 -23
  98. package/dist/rspack-plugin/index.js +0 -3
  99. package/dist/rspack-plugin/multiple.js +0 -39
  100. package/dist/rspack-plugin/plugin.js +0 -133
  101. package/dist/rule-utils/document/document.js +0 -46
  102. package/dist/rule-utils/document/index.js +0 -4
  103. package/dist/rule-utils/document/server.js +0 -13
  104. package/dist/rule-utils/document/types.js +0 -1
  105. package/dist/rule-utils/index.js +0 -3
  106. package/dist/rule-utils/parser/asserts.js +0 -105
  107. package/dist/rule-utils/parser/index.js +0 -5
  108. package/dist/rule-utils/parser/parser.js +0 -24
  109. package/dist/rule-utils/parser/types.js +0 -8
  110. package/dist/rule-utils/parser/utils.js +0 -106
  111. package/dist/rules/index.js +0 -4
  112. package/dist/rules/linter.js +0 -36
  113. package/dist/rules/rule.js +0 -101
  114. package/dist/rules/rules/cjs-require/index.js +0 -50
  115. package/dist/rules/rules/cjs-require/types.js +0 -1
  116. package/dist/rules/rules/cross-chunks-package/index.js +0 -41
  117. package/dist/rules/rules/cross-chunks-package/types.js +0 -1
  118. package/dist/rules/rules/cross-chunks-package/utils.js +0 -7
  119. package/dist/rules/rules/default-import-check/index.js +0 -83
  120. package/dist/rules/rules/default-import-check/types.js +0 -1
  121. package/dist/rules/rules/default-import-check/utils.js +0 -52
  122. package/dist/rules/rules/duplicate-package/index.js +0 -39
  123. package/dist/rules/rules/duplicate-package/types.js +0 -24
  124. package/dist/rules/rules/duplicate-package/utils.js +0 -38
  125. package/dist/rules/rules/ecma-version-check/index.js +0 -53
  126. package/dist/rules/rules/ecma-version-check/types.js +0 -1
  127. package/dist/rules/rules/ecma-version-check/utils.js +0 -6
  128. package/dist/rules/rules/esm-resolved-to-cjs/index.js +0 -193
  129. package/dist/rules/rules/esm-resolved-to-cjs/types.js +0 -1
  130. package/dist/rules/rules/index.js +0 -22
  131. package/dist/rules/rules/loader-performance-optimization/index.js +0 -86
  132. package/dist/rules/rules/loader-performance-optimization/types.js +0 -1
  133. package/dist/rules/rules/loader-performance-optimization/utils.js +0 -10
  134. package/dist/rules/rules/module-mixed-chunks/index.js +0 -52
  135. package/dist/rules/rules/module-mixed-chunks/types.js +0 -1
  136. package/dist/rules/rules/side-effects-only-imports/index.js +0 -81
  137. package/dist/rules/rules/side-effects-only-imports/types.js +0 -1
  138. package/dist/rules/utils.js +0 -10
  139. package/dist/sdk/index.js +0 -3
  140. package/dist/sdk/multiple/controller.js +0 -42
  141. package/dist/sdk/multiple/index.js +0 -3
  142. package/dist/sdk/multiple/primary.js +0 -64
  143. package/dist/sdk/multiple/server.js +0 -14
  144. package/dist/sdk/sdk/core.js +0 -163
  145. package/dist/sdk/sdk/index.js +0 -435
  146. package/dist/sdk/sdk/types.js +0 -1
  147. package/dist/sdk/server/apis/alerts.js +0 -30
  148. package/dist/sdk/server/apis/base.js +0 -22
  149. package/dist/sdk/server/apis/bundle-diff.js +0 -51
  150. package/dist/sdk/server/apis/data.js +0 -44
  151. package/dist/sdk/server/apis/fs.js +0 -28
  152. package/dist/sdk/server/apis/graph.js +0 -116
  153. package/dist/sdk/server/apis/index.js +0 -11
  154. package/dist/sdk/server/apis/loader.js +0 -120
  155. package/dist/sdk/server/apis/plugin.js +0 -39
  156. package/dist/sdk/server/apis/project.js +0 -59
  157. package/dist/sdk/server/apis/renderer.js +0 -33
  158. package/dist/sdk/server/apis/resolver.js +0 -38
  159. package/dist/sdk/server/client.js +0 -8
  160. package/dist/sdk/server/fakeServer.js +0 -12
  161. package/dist/sdk/server/index.js +0 -292
  162. package/dist/sdk/server/json-body.js +0 -150
  163. package/dist/sdk/server/router.js +0 -83
  164. package/dist/sdk/server/security.js +0 -47
  165. package/dist/sdk/server/socket/api.js +0 -22
  166. package/dist/sdk/server/socket/index.js +0 -166
  167. package/dist/sdk/server/utils.js +0 -19
  168. package/dist/sdk/utils/base.js +0 -22
  169. package/dist/sdk/utils/constant.js +0 -4
  170. package/dist/sdk/utils/index.js +0 -4
  171. package/dist/sdk/utils/openBrowser.js +0 -53
  172. package/dist/sdk/utils/upload.js +0 -6
  173. package/dist/sdk.js +0 -2
  174. package/dist/types/index.js +0 -4
  175. package/dist/types/loader.js +0 -1
  176. package/dist/types/plugin.js +0 -1
  177. package/dist/types/rules.js +0 -1
@@ -1,163 +0,0 @@
1
- import "node:module";
2
- import { Constants, Manifest } from "@rsdoctor/shared/types";
3
- import { EnvInfo, File, Json } from "../../build-utils/index.js";
4
- import node_fs from "node:fs";
5
- import node_path from "node:path";
6
- import { createHash, randomUUID } from "node:crypto";
7
- import node_process from "node:process";
8
- import { AsyncSeriesHook } from "tapable";
9
- import { Algorithm, decycle } from "../../common/index.js";
10
- import { logger } from "../../logger.js";
11
- import { transformDataUrls } from "../utils/index.js";
12
- class SDKCore {
13
- get outputDir() {
14
- return this._outputDir;
15
- }
16
- get name() {
17
- return this._name;
18
- }
19
- async bootstrap() {
20
- const [cpu, memory, nodeVersion, yarnVersion, npmVersion, pnpmVersion] = await Promise.all([
21
- EnvInfo.getCPUInfo(),
22
- EnvInfo.getMemoryInfo(),
23
- EnvInfo.getNodeVersion(),
24
- EnvInfo.getYarnVersion(),
25
- EnvInfo.getNpmVersion(),
26
- EnvInfo.getPnpmVersion()
27
- ]);
28
- this._envinfo = {
29
- ...this._envinfo,
30
- cpu,
31
- memory,
32
- nodeVersion,
33
- yarnVersion,
34
- npmVersion,
35
- pnpmVersion
36
- };
37
- const hash = createHash('md5').update([
38
- this.name,
39
- this.root,
40
- JSON.stringify(this._envinfo),
41
- Date.now()
42
- ].join('_')).digest('hex');
43
- this.setHash(hash);
44
- }
45
- async dispose() {}
46
- setOutputDir(outputDir) {
47
- this._outputDir = outputDir;
48
- }
49
- setName(name) {
50
- this._name = name;
51
- }
52
- setHash(hash) {
53
- this.hash = hash;
54
- }
55
- getHash() {
56
- return this.hash;
57
- }
58
- getClientRoutes() {
59
- return [
60
- ...this._clientRoutes
61
- ];
62
- }
63
- addClientRoutes(routes) {
64
- routes.forEach((route)=>{
65
- this._clientRoutes.add(route);
66
- });
67
- this.onDataReport();
68
- }
69
- async writePieces(storeData, _options) {
70
- const { outputDir } = this;
71
- const manifest = node_path.resolve(outputDir, Constants.RsdoctorOutputManifest);
72
- this.diskManifestPath = manifest;
73
- await File.fse.ensureDir(outputDir);
74
- const urlsPromiseList = [];
75
- for (const key of Object.keys(storeData)){
76
- const data = storeData[key];
77
- if ('object' != typeof data) {
78
- urlsPromiseList.push({
79
- name: key,
80
- files: data
81
- });
82
- continue;
83
- }
84
- const jsonStr = await (async ()=>{
85
- try {
86
- if ('configs' === key) return JSON.stringify(decycle(data));
87
- return JSON.stringify(data);
88
- } catch {
89
- return Json.stringify(data);
90
- }
91
- })();
92
- if (Array.isArray(jsonStr)) {
93
- let fileOffset = 0;
94
- for (const str of jsonStr){
95
- const result = await this.writeToFolder(str, outputDir, key, fileOffset);
96
- fileOffset += result.files.length;
97
- urlsPromiseList.push(result);
98
- }
99
- } else urlsPromiseList.push(this.writeToFolder(jsonStr, outputDir, key));
100
- }
101
- const dataUrls = await Promise.all(urlsPromiseList);
102
- logger.debug(`SDKCore.writePieces extraConfig: ${JSON.stringify(this.extraConfig)}`, '[SDKCore.writePieces]');
103
- this.cloudData = {
104
- client: {
105
- enableRoutes: this.getClientRoutes()
106
- },
107
- data: transformDataUrls(dataUrls)
108
- };
109
- }
110
- async writeManifest() {
111
- const { cloudData: data, diskManifestPath } = this;
112
- const dataStr = JSON.stringify(data, null, 2);
113
- logger.debug(`SDKCore.writeManifest extraConfig: ${this.extraConfig}`, '[SDKCore.writeManifest]');
114
- const dir = node_path.dirname(diskManifestPath);
115
- const base = node_path.basename(diskManifestPath);
116
- const tmpPath = node_path.join(dir, `${base}.${Date.now()}.${randomUUID()}.tmp`);
117
- await File.fse.outputFile(tmpPath, dataStr);
118
- node_fs.renameSync(tmpPath, diskManifestPath);
119
- return diskManifestPath;
120
- }
121
- async saveManifest(data, options) {
122
- await this.writePieces(data, options);
123
- const manifestDiskPath = await this.writeManifest();
124
- await this.hooks.afterSaveManifest.promise({
125
- manifestWithShardingFiles: this.cloudData,
126
- manifestDiskPath
127
- });
128
- return manifestDiskPath;
129
- }
130
- writeToFolder(jsonStr, dir, key, index) {
131
- const sharding = new File.FileSharding(Algorithm.compressText(jsonStr));
132
- const folder = node_path.resolve(dir, key);
133
- const writer = sharding.writeStringToFolder(folder, '', index);
134
- return writer.then((item)=>{
135
- const res = {
136
- name: key,
137
- files: item.map((el)=>({
138
- path: node_path.resolve(folder, el.filename),
139
- basename: el.filename,
140
- content: el.content
141
- }))
142
- };
143
- return res;
144
- });
145
- }
146
- constructor({ name, root }){
147
- this.hooks = {
148
- afterSaveManifest: new AsyncSeriesHook([
149
- 'result'
150
- ])
151
- };
152
- this._envinfo = {};
153
- this._clientRoutes = new Set([
154
- Manifest.RsdoctorManifestClientRoutes.Overall
155
- ]);
156
- this.diskManifestPath = '';
157
- this._name = name;
158
- this.root = root;
159
- this.pid = node_process.pid;
160
- this._outputDir = node_path.join(this.outputDir || this.root, Constants.RsdoctorOutputFolder);
161
- }
162
- }
163
- export { SDKCore };
@@ -1,435 +0,0 @@
1
- import "node:module";
2
- import node_fs from "node:fs";
3
- import fs_extra from "fs-extra";
4
- import path_0 from "path";
5
- import { createRequire } from "module";
6
- import { DevToolError } from "../../error/index.js";
7
- import { Constants, SDK } from "@rsdoctor/shared/types";
8
- import { SourceMapConsumer } from "source-map";
9
- import { ChunkGraph, ModuleGraph, PackageGraph } from "../../graph/index.js";
10
- import { logger } from "../../logger.js";
11
- import { RsdoctorServer } from "../server/index.js";
12
- import { RsdoctorFakeServer } from "../server/fakeServer.js";
13
- import { SDKCore } from "./core.js";
14
- import { Algorithm, Lodash, decycle } from "../../common/index.js";
15
- import { findRoot } from "../utils/index.js";
16
- export * from "../utils/openBrowser.js";
17
- export * from "../utils/base.js";
18
- const sdk_require = createRequire(import.meta.url);
19
- class RsdoctorSDK extends SDKCore {
20
- async bootstrap() {
21
- logger.debug(`${Date.now()}`, '[RsdoctorSDK][bootstrap start]');
22
- if (this.server) await this.server.bootstrap();
23
- await super.bootstrap();
24
- logger.debug(`${Date.now()} ${this.server.origin}`, '[RsdoctorSDK][bootstrap end]');
25
- }
26
- async dispose() {
27
- logger.debug(`${Date.now()}`, '[RsdoctorSDK][dispose start]');
28
- if (this.server) await this.server.dispose();
29
- await super.dispose();
30
- logger.debug(`${Date.now()}`, '[RsdoctorSDK][dispose end]');
31
- }
32
- async applyErrorFix(id) {
33
- const { _errors: errors } = this;
34
- const error = errors.find((err)=>err.id === id);
35
- if (!error || !error.path || !error.fixData || error.fixData.isFixed) return;
36
- const { path: filePath, fixData } = error;
37
- const sameFileErrors = errors.filter((item)=>item.path === filePath && item !== error);
38
- let content = (await node_fs.promises.readFile(filePath, 'utf-8')).toString();
39
- const startTxt = content.substring(0, fixData.start);
40
- const endTxt = content.substring(fixData.end, content.length);
41
- const offset = (fixData.newText ?? '').length - (fixData.end - fixData.start);
42
- content = startTxt + fixData.newText + endTxt;
43
- for (const other of sameFileErrors){
44
- const { fixData: otherFixData } = other;
45
- if (otherFixData) {
46
- if (otherFixData.start >= fixData.end) {
47
- otherFixData.start += offset;
48
- otherFixData.end += offset;
49
- }
50
- }
51
- }
52
- await node_fs.promises.writeFile(filePath, content);
53
- }
54
- clear() {
55
- this._errors = [];
56
- this._loader = [];
57
- this._resolver = [];
58
- this._plugin = {};
59
- this._moduleGraph = new ModuleGraph();
60
- this._chunkGraph = new ChunkGraph();
61
- }
62
- clearSourceMapCache() {
63
- this._rawSourceMapCache = new Map();
64
- this._sourceMap = new Map();
65
- }
66
- async getSourceMap(file) {
67
- const { _sourceMap: sourceMap, _rawSourceMapCache: rawMap } = this;
68
- if (sourceMap.has(file)) return sourceMap.get(file);
69
- const rawData = rawMap.get(file);
70
- if (!rawData || rawData.version < 0 || !rawData.sourcesContent?.[0] || !rawData.mappings) return Promise.resolve(void 0);
71
- try {
72
- const result = await new SourceMapConsumer(rawData);
73
- sourceMap.set(file, result);
74
- return result;
75
- } catch {
76
- return Promise.resolve(void 0);
77
- }
78
- }
79
- reportSourceMap(data) {
80
- this._rawSourceMapCache.set(data.file, data);
81
- }
82
- reportConfiguration(config) {
83
- config.root ??= this.root;
84
- this._configs.push(config);
85
- this.onDataReport();
86
- }
87
- reportError(errors) {
88
- errors.forEach((item)=>{
89
- this._errors.push(DevToolError.from(item, {
90
- code: this.name
91
- }));
92
- });
93
- this.onDataReport();
94
- }
95
- reportLoader(data) {
96
- data.forEach((item)=>{
97
- if (this.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) item.loaders.forEach((_loader)=>{
98
- _loader.input = void 0;
99
- _loader.result = void 0;
100
- });
101
- let match = this._loader.find((e)=>e.resource.path === item.resource.path);
102
- if (match) match.loaders.push(...item.loaders);
103
- else {
104
- match = item;
105
- this._loader.push(item);
106
- }
107
- match.loaders.sort((a, b)=>{
108
- if (a.startAt !== b.startAt) return a.startAt - b.startAt;
109
- if (a.isPitch) {
110
- if (b.isPitch) return a.loaderIndex - b.loaderIndex;
111
- return -1;
112
- }
113
- if (b.isPitch) return 1;
114
- return b.loaderIndex - a.loaderIndex;
115
- });
116
- });
117
- this.onDataReport();
118
- }
119
- reportLoaderStartOrEnd(data) {
120
- const _builtinLoader = data.loaders[0];
121
- if (_builtinLoader.startAt) this._loaderStart.push(data);
122
- else if (_builtinLoader.endAt) {
123
- const matchLoaderStart = this._loaderStart.find((e)=>e.resource.path === data.resource.path && e.loaders[0].loader === _builtinLoader.loader);
124
- if (matchLoaderStart) {
125
- matchLoaderStart.loaders[0].result = _builtinLoader.result;
126
- matchLoaderStart.loaders[0].endAt = _builtinLoader.endAt;
127
- this.reportLoader([
128
- matchLoaderStart
129
- ]);
130
- }
131
- }
132
- }
133
- reportResolver(data) {
134
- data.forEach((item)=>this._resolver.push(item));
135
- this.onDataReport();
136
- }
137
- reportPlugin(data) {
138
- Object.keys(data).forEach((hook)=>{
139
- if (this._plugin[hook]) data[hook].forEach((item)=>{
140
- this._plugin[hook].push(item || void 0);
141
- });
142
- else this._plugin[hook] = data[hook];
143
- });
144
- this.onDataReport();
145
- }
146
- reportModuleGraph(data) {
147
- logger.debug(`data size: ${data.size()}`, '[SDK.reportModuleGraph][start]');
148
- this._moduleGraph.fromInstance(data);
149
- this.createPackageGraph();
150
- this.onDataReport();
151
- logger.debug(`sdk._moduleGraph size: ${this._moduleGraph.size()}`, '[SDK reportModuleGraph][end]');
152
- }
153
- reportPackageGraph(data) {
154
- logger.debug('[SDK.reportPackageGraph][start]');
155
- if (!this._packageGraph) this._packageGraph = data;
156
- this.onDataReport();
157
- logger.debug(`sdk._packageGraph size: ${this._packageGraph.getPackages().length}`, '[SDK reportPackageGraph][end]');
158
- }
159
- reportChunkGraph(data) {
160
- this._chunkGraph.addAsset(...data.getAssets());
161
- this._chunkGraph.addChunk(...data.getChunks());
162
- this._chunkGraph.addEntryPoint(...data.getEntryPoints());
163
- this.onDataReport();
164
- }
165
- reportSummaryData(part) {
166
- const keys = [
167
- 'costs'
168
- ];
169
- for (const key of keys){
170
- const v = part[key];
171
- if (v) if ('object' == typeof v) if (Array.isArray(v)) this._summary[key] = [
172
- ...this._summary[key] || [],
173
- ...v
174
- ];
175
- else this._summary[key] = {
176
- ...this._summary[key] || {},
177
- ...v
178
- };
179
- else this._summary[key] = v;
180
- }
181
- this.onDataReport();
182
- }
183
- createPackageGraph() {
184
- logger.debug(`sdk._moduleGraph size: ${this._moduleGraph.size()}`, '[SDK.createPackageGraph][start]');
185
- if (!this._packageGraph) {
186
- const pkgGraph = PackageGraph.fromModuleGraph(this._moduleGraph, this.root, (path)=>{
187
- try {
188
- const exists = node_fs.existsSync(path);
189
- if (exists) {
190
- const res = fs_extra.readJsonSync(path);
191
- return res;
192
- }
193
- } catch (error) {
194
- const { message, stack } = error;
195
- logger.debug(()=>`sdk.createPackageGraph error, path: ${path}, error message: ${stack || message}`, '[SDK.createPackageGraph][error]');
196
- }
197
- });
198
- this._packageGraph = pkgGraph;
199
- logger.debug(`sdk._packageGraph packages: ${this._packageGraph.getPackages().length}`, '[SDK.createPackageGraph][end]');
200
- }
201
- }
202
- async writeStore(options) {
203
- logger.debug("sdk.writeStore has run.", '[SDK.writeStore][end]');
204
- let htmlPath = '';
205
- if (this.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) {
206
- const clientHtmlPath = this.extraConfig.innerClientPath ? this.extraConfig.innerClientPath : sdk_require.resolve('@rsdoctor/client');
207
- if (this.extraConfig?.brief?.type?.includes('json')) {
208
- const data = this.getStoreData();
209
- const clientRoutes = this.getClientRoutes();
210
- const jsonData = {
211
- data,
212
- clientRoutes
213
- };
214
- node_fs.mkdirSync(this.outputDir, {
215
- recursive: true
216
- });
217
- node_fs.writeFileSync(path_0.resolve(this.outputDir, this.extraConfig.brief.jsonOptions?.fileName ?? 'rsdoctor-data.json'), JSON.stringify(jsonData));
218
- }
219
- if (this.extraConfig.brief?.type?.includes('html')) htmlPath = this.inlineScriptsAndStyles(clientHtmlPath);
220
- return htmlPath;
221
- }
222
- return this.saveManifest(this.getStoreData(), options || {});
223
- }
224
- getStoreData() {
225
- const ctx = this;
226
- const briefOptions = this.extraConfig?.brief;
227
- const sections = briefOptions?.jsonOptions?.sections;
228
- const isJsonType = briefOptions?.type?.includes('json');
229
- return {
230
- get hash () {
231
- return ctx.hash;
232
- },
233
- get root () {
234
- return ctx.root;
235
- },
236
- get envinfo () {
237
- return ctx._envinfo;
238
- },
239
- get pid () {
240
- return ctx.pid;
241
- },
242
- get errors () {
243
- if (isJsonType && sections && !sections.rules) return [];
244
- return ctx._errors.map((err)=>err.toData());
245
- },
246
- get configs () {
247
- return ctx._configs.slice();
248
- },
249
- get summary () {
250
- return {
251
- ...ctx._summary
252
- };
253
- },
254
- get resolver () {
255
- return ctx._resolver.slice();
256
- },
257
- get loader () {
258
- return ctx._loader.slice();
259
- },
260
- get moduleGraph () {
261
- if (isJsonType && sections && !sections.moduleGraph) return {
262
- dependencies: [],
263
- modules: [],
264
- moduleGraphModules: [],
265
- exports: [],
266
- sideEffects: [],
267
- variables: [],
268
- layers: []
269
- };
270
- return ctx._moduleGraph.toData({
271
- contextPath: ctx._configs?.[0]?.config?.context || '',
272
- briefOptions
273
- });
274
- },
275
- get chunkGraph () {
276
- if (isJsonType && sections && !sections.chunkGraph) return {
277
- assets: [],
278
- chunks: [],
279
- entrypoints: []
280
- };
281
- return ctx._chunkGraph.toData(ctx.type);
282
- },
283
- get moduleCodeMap () {
284
- if (ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) return {};
285
- return ctx._moduleGraph.toCodeData(ctx.type);
286
- },
287
- get plugin () {
288
- return {
289
- ...ctx._plugin
290
- };
291
- },
292
- get packageGraph () {
293
- return ctx._packageGraph ? ctx._packageGraph.toData() : {
294
- packages: [],
295
- dependencies: []
296
- };
297
- },
298
- get treeShaking () {
299
- if (ctx.extraConfig?.mode === SDK.IMode[SDK.IMode.brief]) return;
300
- if (!ctx.extraConfig?.features?.treeShaking) return;
301
- return ctx._moduleGraph.toTreeShakingData();
302
- },
303
- get otherReports () {
304
- return {
305
- treemapReportHtml: ''
306
- };
307
- }
308
- };
309
- }
310
- getManifestData() {
311
- const dataValue = this.getStoreData();
312
- const data = {
313
- client: {
314
- enableRoutes: this.getClientRoutes()
315
- },
316
- data: Object.keys(dataValue).reduce((t, e)=>{
317
- const _e = e;
318
- if (dataValue[_e] && 'object' == typeof dataValue[_e]) t[e] = [
319
- `${this.server.origin}${SDK.ServerAPI.API.LoadDataByKey}/${e}`
320
- ];
321
- else t[e] = dataValue[_e];
322
- return t;
323
- }, {}),
324
- __LOCAL__SERVER__: true,
325
- __SOCKET__PORT__: this.server.socketUrl.port.toString(),
326
- __SOCKET__URL__: this.server.socketUrl.socketUrl
327
- };
328
- return data;
329
- }
330
- getRuleContext(_options) {
331
- this.createPackageGraph();
332
- return {
333
- root: this.root,
334
- errors: this._errors.slice(),
335
- configs: this._configs.slice(),
336
- moduleGraph: this._moduleGraph,
337
- chunkGraph: this._chunkGraph,
338
- packageGraph: this._packageGraph,
339
- loader: this._loader.slice(),
340
- otherReports: {
341
- treemapReportHtml: ''
342
- }
343
- };
344
- }
345
- onDataReport() {
346
- this.server.broadcast();
347
- }
348
- addRsdoctorDataToHTML(storeData, htmlContent) {
349
- let compressTextScripts = `<script>window.${Constants.WINDOW_RSDOCTOR_TAG}={}</script>`;
350
- for (const key of Object.keys(storeData)){
351
- const data = storeData[key];
352
- const jsonStrFn = ()=>{
353
- try {
354
- if ('configs' === key) return JSON.stringify(decycle(data));
355
- return JSON.stringify(data);
356
- } catch (error) {
357
- console.error(error);
358
- return '';
359
- }
360
- };
361
- const compressText = Algorithm.compressText(jsonStrFn());
362
- compressTextScripts = `${compressTextScripts} <script>window.${Constants.WINDOW_RSDOCTOR_TAG}.${key}=${JSON.stringify(compressText)}</script>`;
363
- }
364
- compressTextScripts = `${compressTextScripts} <script>window.${Constants.WINDOW_RSDOCTOR_TAG}.enableRoutes=${JSON.stringify(this.getClientRoutes())}</script>`;
365
- htmlContent = htmlContent.replace('<body>', `<body>${compressTextScripts}`);
366
- return htmlContent;
367
- }
368
- inlineScriptsAndStyles(htmlFilePath) {
369
- function inlineScripts(basePath, scripts) {
370
- return scripts.map((src)=>{
371
- const scriptPath = resolveFilePath(basePath, src);
372
- try {
373
- const scriptContent = node_fs.readFileSync(scriptPath, 'utf-8');
374
- return `<script>${scriptContent}</script>`;
375
- } catch (error) {
376
- console.error(`Could not read script at ${scriptPath}:`, error);
377
- return '';
378
- }
379
- }).join('');
380
- }
381
- function resolveFilePath(basePath, filePath) {
382
- if (filePath.startsWith('/')) return path_0.resolve(basePath, filePath.slice(1));
383
- return path_0.resolve(basePath, filePath);
384
- }
385
- function inlineCss(basePath, cssFiles) {
386
- return cssFiles.map((href)=>{
387
- const cssPath = resolveFilePath(basePath, href);
388
- try {
389
- const cssContent = node_fs.readFileSync(cssPath, 'utf-8');
390
- return `<style>${cssContent}</style>`;
391
- } catch (error) {
392
- console.error(`Could not read CSS at ${cssPath}:`, error);
393
- return '';
394
- }
395
- }).join('');
396
- }
397
- let htmlContent = node_fs.readFileSync(htmlFilePath, 'utf-8');
398
- const basePath = path_0.dirname(htmlFilePath);
399
- const scriptSrcs = Array.from(htmlContent.matchAll(/<script\s+(?:defer="defer"|defer)\s+src=["'](.+?)["']><\/script>/g), (m)=>m[1]);
400
- const cssHrefs = Array.from(htmlContent.matchAll(/<link\s+href=["'](.+?)["']\s+rel="stylesheet">/g), (m)=>m[1]);
401
- htmlContent = htmlContent.replace(/<script\s+.*?src=["'].*?["']><\/script>/g, '');
402
- htmlContent = htmlContent.replace(/<link\s+.*?rel=["']stylesheet["'].*?>/g, '');
403
- const inlinedScripts = inlineScripts(basePath, scriptSrcs);
404
- const inlinedCss = inlineCss(basePath, cssHrefs);
405
- const index = htmlContent.indexOf('</body>');
406
- htmlContent = htmlContent.slice(0, index) + inlinedCss + inlinedScripts + htmlContent.slice(index);
407
- htmlContent = this.addRsdoctorDataToHTML(this.getStoreData(), htmlContent);
408
- const outputFilePath = path_0.resolve(this.outputDir, this.extraConfig?.brief?.htmlOptions?.reportHtmlName || 'rsdoctor-report.html');
409
- node_fs.mkdirSync(path_0.dirname(outputFilePath), {
410
- recursive: true
411
- });
412
- node_fs.writeFileSync(outputFilePath, htmlContent, {
413
- encoding: 'utf-8',
414
- flag: 'w'
415
- });
416
- return outputFilePath;
417
- }
418
- constructor(options){
419
- super(options), this._summary = {
420
- costs: []
421
- }, this._configs = [], this._errors = [], this._loader = [], this._loaderStart = [], this._resolver = [], this._plugin = {}, this._moduleGraph = new ModuleGraph(), this._chunkGraph = new ChunkGraph(), this._rawSourceMapCache = new Map(), this._sourceMap = new Map();
422
- const serverConfig = options.config?.server;
423
- const port = serverConfig?.port ?? options.port;
424
- this.server = options.config?.noServer ? new RsdoctorFakeServer(this, port) : new RsdoctorServer(this, port, {
425
- innerClientPath: options.config?.innerClientPath || '',
426
- printServerUrl: options.config?.printLog?.serverUrls,
427
- cors: serverConfig?.cors
428
- });
429
- this.type = Lodash.isNumber(options.type) ? options.type : SDK.ToDataType.Normal;
430
- this.extraConfig = options.config;
431
- this.root = findRoot() ?? '';
432
- }
433
- }
434
- export { resolveClientDiffHtmlPath } from "../server/client.js";
435
- export { RsdoctorSDK };
@@ -1 +0,0 @@
1
- import "node:module";
@@ -1,30 +0,0 @@
1
- import "node:module";
2
- import { SDK } from "@rsdoctor/shared/types";
3
- import { BaseAPI } from "./base.js";
4
- import { Router } from "../router.js";
5
- function _ts_decorate(decorators, target, key, desc) {
6
- var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7
- if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
8
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
9
- return c > 3 && r && Object.defineProperty(target, key, r), r;
10
- }
11
- function _ts_metadata(k, v) {
12
- if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
13
- }
14
- class AlertsAPI extends BaseAPI {
15
- async getPackageRelationAlertDetails() {
16
- const { req } = this.ctx;
17
- const { id, target } = req.body;
18
- return this.dataLoader.loadAPI(SDK.ServerAPI.API.GetPackageRelationAlertDetails, {
19
- id,
20
- target
21
- });
22
- }
23
- }
24
- _ts_decorate([
25
- Router.post(SDK.ServerAPI.API.GetPackageRelationAlertDetails),
26
- _ts_metadata("design:type", Function),
27
- _ts_metadata("design:paramtypes", []),
28
- _ts_metadata("design:returntype", Promise)
29
- ], AlertsAPI.prototype, "getPackageRelationAlertDetails", null);
30
- export { AlertsAPI };
@@ -1,22 +0,0 @@
1
- import "node:module";
2
- import { Data } from "../../../common/index.js";
3
- class BaseAPI {
4
- async loadManifest() {
5
- return this.ctx.sdk.getManifestData();
6
- }
7
- async loadData(key) {
8
- const data = this.ctx.sdk.getStoreData();
9
- const sep = '.';
10
- let res = data[key];
11
- if (key.includes(sep)) res = key.split(sep).reduce((t, k)=>t[k], data);
12
- return res;
13
- }
14
- constructor(sdk, server){
15
- this.ctx = {
16
- sdk,
17
- server
18
- };
19
- this.dataLoader = new Data.APIDataLoader(this);
20
- }
21
- }
22
- export { BaseAPI };