@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.1 → 3.2.0-ultramodern.100

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 (145) hide show
  1. package/bin/modern.js +0 -0
  2. package/dist/cjs/baseline.js +43 -1
  3. package/dist/cjs/builder/generator/getBuilderEnvironments.js +191 -8
  4. package/dist/cjs/builder/shared/builderPlugins/adapterBasic.js +41 -5
  5. package/dist/cjs/builder/shared/builderPlugins/adapterSSR.js +3 -1
  6. package/dist/cjs/plugins/deploy/index.js +17 -6
  7. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +222 -0
  8. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +438 -0
  9. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  10. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  11. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  12. package/dist/cjs/rsbuild.js +3 -0
  13. package/dist/esm/baseline.mjs +33 -1
  14. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +180 -8
  15. package/dist/esm/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  16. package/dist/esm/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  17. package/dist/esm/plugins/deploy/index.mjs +10 -4
  18. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +178 -0
  19. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +438 -0
  20. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  21. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  22. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  23. package/dist/esm/rsbuild.mjs +5 -2
  24. package/dist/esm-node/baseline.mjs +33 -1
  25. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +185 -9
  26. package/dist/esm-node/builder/shared/builderPlugins/adapterBasic.mjs +41 -5
  27. package/dist/esm-node/builder/shared/builderPlugins/adapterSSR.mjs +3 -1
  28. package/dist/esm-node/plugins/deploy/index.mjs +10 -4
  29. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +179 -0
  30. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +438 -0
  31. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.mjs +7 -0
  32. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.mjs +185 -0
  33. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-worker-path.mjs +59 -0
  34. package/dist/esm-node/rsbuild.mjs +5 -2
  35. package/dist/types/baseline.d.ts +46 -0
  36. package/dist/types/builder/builder-rspack/index.d.ts +2 -0
  37. package/dist/types/builder/generator/adapterCopy.d.ts +3 -0
  38. package/dist/types/builder/generator/createBuilderProviderConfig.d.ts +3 -0
  39. package/dist/types/builder/generator/createCopyPattern.d.ts +16 -0
  40. package/dist/types/builder/generator/getBuilderEnvironments.d.ts +6 -0
  41. package/dist/types/builder/generator/index.d.ts +8 -0
  42. package/dist/types/builder/index.d.ts +3 -0
  43. package/dist/types/builder/shared/builderPlugins/adapterBasic.d.ts +3 -0
  44. package/dist/types/builder/shared/builderPlugins/adapterHtml.d.ts +3 -0
  45. package/dist/types/builder/shared/builderPlugins/adapterPrecompress.d.ts +3 -0
  46. package/dist/types/builder/shared/builderPlugins/adapterSSR.d.ts +3 -0
  47. package/dist/types/builder/shared/builderPlugins/builderHooks.d.ts +3 -0
  48. package/dist/types/builder/shared/builderPlugins/index.d.ts +5 -0
  49. package/dist/types/builder/shared/bundlerPlugins/HtmlAsyncChunkPlugin.d.ts +7 -0
  50. package/dist/types/builder/shared/bundlerPlugins/HtmlBottomTemplate.d.ts +9 -0
  51. package/dist/types/builder/shared/bundlerPlugins/RouterPlugin.d.ts +32 -0
  52. package/dist/types/builder/shared/bundlerPlugins/index.d.ts +3 -0
  53. package/dist/types/builder/shared/createCopyInfo.d.ts +8 -0
  54. package/dist/types/builder/shared/index.d.ts +3 -0
  55. package/dist/types/builder/shared/loaders/serverModuleLoader.d.ts +3 -0
  56. package/dist/types/builder/shared/types.d.ts +6 -0
  57. package/dist/types/commands/build.d.ts +4 -0
  58. package/dist/types/commands/deploy.d.ts +3 -0
  59. package/dist/types/commands/dev.d.ts +9 -0
  60. package/dist/types/commands/index.d.ts +10 -0
  61. package/dist/types/commands/info.d.ts +18 -0
  62. package/dist/types/commands/inspect.d.ts +4 -0
  63. package/dist/types/commands/runtime.d.ts +11 -0
  64. package/dist/types/commands/serve.d.ts +8 -0
  65. package/dist/types/compat/hooks.d.ts +7 -0
  66. package/dist/types/compat/index.d.ts +2 -0
  67. package/dist/types/compat/utils.d.ts +13 -0
  68. package/dist/types/config/default.d.ts +3 -0
  69. package/dist/types/config/index.d.ts +2 -0
  70. package/dist/types/config/initialize/index.d.ts +3 -0
  71. package/dist/types/config/initialize/inits.d.ts +4 -0
  72. package/dist/types/constants.d.ts +2 -0
  73. package/dist/types/defineConfig.d.ts +11 -0
  74. package/dist/types/esm/register-esm.d.mts +5 -0
  75. package/dist/types/esm/ts-paths-loader.d.mts +6 -0
  76. package/dist/types/exports/server.d.ts +1 -0
  77. package/dist/types/index.d.ts +17 -0
  78. package/dist/types/locale/en.d.ts +44 -0
  79. package/dist/types/locale/index.d.ts +3 -0
  80. package/dist/types/locale/zh.d.ts +44 -0
  81. package/dist/types/plugins/analyze/constants.d.ts +3 -0
  82. package/dist/types/plugins/analyze/getBundleEntry.d.ts +4 -0
  83. package/dist/types/plugins/analyze/getFileSystemEntry.d.ts +7 -0
  84. package/dist/types/plugins/analyze/getHtmlTemplate.d.ts +27 -0
  85. package/dist/types/plugins/analyze/getServerRoutes.d.ts +8 -0
  86. package/dist/types/plugins/analyze/index.d.ts +3 -0
  87. package/dist/types/plugins/analyze/isDefaultExportFunction.d.ts +1 -0
  88. package/dist/types/plugins/analyze/templates.d.ts +5 -0
  89. package/dist/types/plugins/analyze/utils.d.ts +10 -0
  90. package/dist/types/plugins/deploy/index.d.ts +6 -0
  91. package/dist/types/plugins/deploy/platforms/cloudflare.d.ts +2 -0
  92. package/dist/types/plugins/deploy/platforms/gh-pages.d.ts +2 -0
  93. package/dist/types/plugins/deploy/platforms/netlify.d.ts +2 -0
  94. package/dist/types/plugins/deploy/platforms/node.d.ts +2 -0
  95. package/dist/types/plugins/deploy/platforms/platform.d.ts +17 -0
  96. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.d.mts +4 -0
  97. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-fs-promises.d.mts +5 -0
  98. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-loadable-server.d.mts +48 -0
  99. package/dist/types/plugins/deploy/platforms/templates/cloudflare-worker-path.d.mts +21 -0
  100. package/dist/types/plugins/deploy/platforms/templates/netlify-entry.d.cts +2 -0
  101. package/dist/types/plugins/deploy/platforms/templates/netlify-entry.d.mts +2 -0
  102. package/dist/types/plugins/deploy/platforms/templates/node-entry.d.cts +1 -0
  103. package/dist/types/plugins/deploy/platforms/templates/node-entry.d.mts +1 -0
  104. package/dist/types/plugins/deploy/platforms/templates/vercel-entry.d.cts +2 -0
  105. package/dist/types/plugins/deploy/platforms/templates/vercel-entry.d.mts +2 -0
  106. package/dist/types/plugins/deploy/platforms/vercel.d.ts +2 -0
  107. package/dist/types/plugins/deploy/types.d.ts +3 -0
  108. package/dist/types/plugins/deploy/utils/generator.d.ts +24 -0
  109. package/dist/types/plugins/deploy/utils/index.d.ts +16 -0
  110. package/dist/types/plugins/initialize/index.d.ts +3 -0
  111. package/dist/types/plugins/serverBuild.d.ts +3 -0
  112. package/dist/types/plugins/serverRuntime.d.ts +3 -0
  113. package/dist/types/presetUltramodern.d.ts +6 -0
  114. package/dist/types/rsbuild.d.ts +12 -0
  115. package/dist/types/run/index.d.ts +20 -0
  116. package/dist/types/types/config/deploy.d.ts +46 -0
  117. package/dist/types/types/config/dev.d.ts +55 -0
  118. package/dist/types/types/config/experiments.d.ts +3 -0
  119. package/dist/types/types/config/html.d.ts +3 -0
  120. package/dist/types/types/config/index.d.ts +48 -0
  121. package/dist/types/types/config/output.d.ts +61 -0
  122. package/dist/types/types/config/performance.d.ts +3 -0
  123. package/dist/types/types/config/resolve.d.ts +2 -0
  124. package/dist/types/types/config/security.d.ts +2 -0
  125. package/dist/types/types/config/source.d.ts +61 -0
  126. package/dist/types/types/config/testing.d.ts +8 -0
  127. package/dist/types/types/config/tools.d.ts +21 -0
  128. package/dist/types/types/index.d.ts +10 -0
  129. package/dist/types/types/plugin.d.ts +114 -0
  130. package/dist/types/types/utils.d.ts +1 -0
  131. package/dist/types/ultramodern/designSystem.d.ts +54 -0
  132. package/dist/types/utils/config.d.ts +2 -0
  133. package/dist/types/utils/createServer.d.ts +5 -0
  134. package/dist/types/utils/env.d.ts +2 -0
  135. package/dist/types/utils/generateWatchFiles.d.ts +2 -0
  136. package/dist/types/utils/getConfigFile.d.ts +1 -0
  137. package/dist/types/utils/getSelectedEntries.d.ts +5 -0
  138. package/dist/types/utils/initAppContext.d.ts +31 -0
  139. package/dist/types/utils/loadPlugins.d.ts +13 -0
  140. package/dist/types/utils/printInstructions.d.ts +3 -0
  141. package/dist/types/utils/register.d.ts +19 -0
  142. package/dist/types/utils/restart.d.ts +2 -0
  143. package/dist/types/utils/routes.d.ts +4 -0
  144. package/dist/types/utils/types.d.ts +49 -0
  145. package/package.json +18 -17
@@ -0,0 +1,185 @@
1
+ import loadableComponent from '@loadable/component';
2
+ import React from 'react';
3
+ const internals = loadableComponent?.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED || {};
4
+ const LoadableContext = internals.Context || React.createContext(null);
5
+ const getRequiredChunkKey = internals.getRequiredChunkKey || ((namespace)=>`${namespace}__LOADABLE_REQUIRED_CHUNKS__`);
6
+ const scriptExtensions = new Set([
7
+ '.js',
8
+ '.mjs'
9
+ ]);
10
+ const styleExtensions = new Set([
11
+ '.css'
12
+ ]);
13
+ function uniqByUrl(assets) {
14
+ const seen = new Set();
15
+ return assets.filter((asset)=>{
16
+ if (seen.has(asset.url)) return false;
17
+ seen.add(asset.url);
18
+ return true;
19
+ });
20
+ }
21
+ function extname(filePath) {
22
+ const basename = String(filePath).split('/').pop() || '';
23
+ const index = basename.lastIndexOf('.');
24
+ return index > 0 ? basename.slice(index) : '';
25
+ }
26
+ function joinUrl(publicPath, filename) {
27
+ const base = publicPath || '/';
28
+ return `${base.replace(/\/+$/u, '')}/${String(filename).replace(/^\/+/u, '')}`;
29
+ }
30
+ function extraPropsToString(extraProps = {}) {
31
+ return Object.entries(extraProps).filter(([, value])=>void 0 !== value && false !== value).map(([key, value])=>true === value ? ` ${key}` : ` ${key}="${value}"`).join('');
32
+ }
33
+ function assetScriptType(filename) {
34
+ const extension = extname(filename);
35
+ if (scriptExtensions.has(extension)) return "script";
36
+ if (styleExtensions.has(extension)) return 'style';
37
+ }
38
+ function getAssetName(asset) {
39
+ return 'object' == typeof asset && asset?.name ? asset.name : asset;
40
+ }
41
+ function getAssetIntegrity(asset) {
42
+ return 'object' == typeof asset && asset?.integrity ? asset.integrity : null;
43
+ }
44
+ function getChunkGroupAssets(chunkGroup) {
45
+ const assets = chunkGroup?.assets;
46
+ if (Array.isArray(assets)) return assets;
47
+ if (assets && 'object' == typeof assets) return [
48
+ ...assets.js || [],
49
+ ...assets.css || []
50
+ ];
51
+ return [];
52
+ }
53
+ function getChunkGroupChildAssets(chunkGroup, type) {
54
+ const childAssets = chunkGroup?.childAssets?.[type];
55
+ return Array.isArray(childAssets) ? childAssets : [];
56
+ }
57
+ function chunkIncludesJs(chunkInfo) {
58
+ return (chunkInfo?.files || []).some((file)=>scriptExtensions.has(extname(file)));
59
+ }
60
+ export function ChunkExtractorManager({ extractor, children }) {
61
+ return React.createElement(LoadableContext.Provider, {
62
+ value: extractor
63
+ }, children);
64
+ }
65
+ export class ChunkExtractor {
66
+ constructor({ stats, entrypoints = [
67
+ 'main'
68
+ ], namespace = '', outputPath = '/', publicPath } = {}){
69
+ this.namespace = namespace;
70
+ this.stats = stats || {};
71
+ this.publicPath = publicPath || this.stats.publicPath || '/';
72
+ this.outputPath = outputPath || this.stats.outputPath || '/';
73
+ this.entrypoints = Array.isArray(entrypoints) ? entrypoints : [
74
+ entrypoints
75
+ ];
76
+ this.chunks = [];
77
+ }
78
+ addChunk(chunk) {
79
+ if (!this.chunks.includes(chunk)) this.chunks.push(chunk);
80
+ }
81
+ collectChunks(app) {
82
+ return React.createElement(ChunkExtractorManager, {
83
+ extractor: this
84
+ }, app);
85
+ }
86
+ getChunkGroup(chunk) {
87
+ return this.stats.namedChunkGroups?.[chunk] || {
88
+ assets: [],
89
+ childAssets: {},
90
+ chunks: []
91
+ };
92
+ }
93
+ getChunkInfo(chunkId) {
94
+ return (this.stats.chunks || []).find((chunk)=>chunk.id === chunkId);
95
+ }
96
+ resolvePublicUrl(filename) {
97
+ return joinUrl(this.publicPath, filename);
98
+ }
99
+ createChunkAsset({ filename, chunk, type, linkType }) {
100
+ const resolvedFilename = getAssetName(filename);
101
+ const scriptType = assetScriptType(resolvedFilename);
102
+ if (!scriptType) return;
103
+ return {
104
+ filename: resolvedFilename,
105
+ integrity: getAssetIntegrity(filename),
106
+ scriptType,
107
+ chunk,
108
+ url: this.resolvePublicUrl(resolvedFilename),
109
+ path: String(resolvedFilename).replace(/^\/+/u, ''),
110
+ type,
111
+ linkType
112
+ };
113
+ }
114
+ getChunkAssets(chunks) {
115
+ const one = (chunk)=>getChunkGroupAssets(this.getChunkGroup(chunk)).map((filename)=>this.createChunkAsset({
116
+ filename,
117
+ chunk,
118
+ type: 'mainAsset',
119
+ linkType: 'preload'
120
+ })).filter(Boolean);
121
+ return Array.isArray(chunks) ? uniqByUrl(chunks.flatMap(one)) : one(chunks);
122
+ }
123
+ getChunkChildAssets(chunks, type) {
124
+ const one = (chunk)=>getChunkGroupChildAssets(this.getChunkGroup(chunk), type).map((filename)=>this.createChunkAsset({
125
+ filename,
126
+ chunk,
127
+ type: 'childAsset',
128
+ linkType: type
129
+ })).filter(Boolean);
130
+ return Array.isArray(chunks) ? uniqByUrl(chunks.flatMap(one)) : one(chunks);
131
+ }
132
+ getChunkDependencies(chunks) {
133
+ const one = (chunk)=>(this.getChunkGroup(chunk).chunks || []).filter((chunkId)=>chunkIncludesJs(this.getChunkInfo(chunkId)));
134
+ return Array.isArray(chunks) ? [
135
+ ...new Set(chunks.flatMap(one))
136
+ ] : one(chunks);
137
+ }
138
+ getRequiredChunksScriptContent() {
139
+ return JSON.stringify(this.getChunkDependencies(this.chunks));
140
+ }
141
+ getRequiredChunksNamesScriptContent() {
142
+ return JSON.stringify({
143
+ namedChunks: this.chunks
144
+ });
145
+ }
146
+ getRequiredChunksScriptTag(extraProps = {}) {
147
+ const id = getRequiredChunkKey(this.namespace);
148
+ const props = `type="application/json"${extraPropsToString(extraProps)}`;
149
+ return [
150
+ `<script id="${id}" ${props}>${this.getRequiredChunksScriptContent()}</script>`,
151
+ `<script id="${id}_ext" ${props}>${this.getRequiredChunksNamesScriptContent()}</script>`
152
+ ].join('');
153
+ }
154
+ getMainAssets(scriptType) {
155
+ const assets = this.getChunkAssets([
156
+ ...this.entrypoints,
157
+ ...this.chunks
158
+ ]);
159
+ return scriptType ? assets.filter((asset)=>asset.scriptType === scriptType) : assets;
160
+ }
161
+ getScriptTags(extraProps = {}) {
162
+ const scripts = this.getMainAssets("script").map((asset)=>`<script async data-chunk="${asset.chunk}" src="${asset.url}"${extraPropsToString(extraProps)}></script>`);
163
+ return [
164
+ this.getRequiredChunksScriptTag(extraProps),
165
+ ...scripts
166
+ ].join('');
167
+ }
168
+ getStyleTags(extraProps = {}) {
169
+ return this.getMainAssets('style').map((asset)=>`<link data-chunk="${asset.chunk}" rel="stylesheet" href="${asset.url}"${extraPropsToString(extraProps)}>`).join('');
170
+ }
171
+ getLinkTags(extraProps = {}) {
172
+ const assets = [
173
+ ...this.getMainAssets(),
174
+ ...this.getChunkChildAssets([
175
+ ...this.entrypoints,
176
+ ...this.chunks
177
+ ], 'preload'),
178
+ ...this.getChunkChildAssets([
179
+ ...this.entrypoints,
180
+ ...this.chunks
181
+ ], 'prefetch')
182
+ ];
183
+ return uniqByUrl(assets).map((asset)=>`<link data-chunk="${asset.chunk}" rel="${asset.linkType}" as="${asset.scriptType}" href="${asset.url}"${extraPropsToString(extraProps)}>`).join('');
184
+ }
185
+ }
@@ -0,0 +1,59 @@
1
+ const trimSlashes = (value)=>String(value).replace(/^\/+|\/+$/gu, '');
2
+ const normalizeSeparators = (value)=>String(value).replace(/\\+/gu, '/');
3
+ export const sep = '/';
4
+ export const delimiter = ':';
5
+ export function isAbsolute(filePath) {
6
+ return normalizeSeparators(filePath).startsWith('/');
7
+ }
8
+ export function normalize(filePath) {
9
+ const normalized = normalizeSeparators(filePath);
10
+ const absolute = isAbsolute(normalized);
11
+ const parts = [];
12
+ for (const part of normalized.split('/'))if (part && '.' !== part) {
13
+ if ('..' === part) {
14
+ if (parts.length > 0 && '..' !== parts[parts.length - 1]) parts.pop();
15
+ else if (!absolute) parts.push(part);
16
+ continue;
17
+ }
18
+ parts.push(part);
19
+ }
20
+ const joined = parts.join('/');
21
+ if (absolute) return joined ? `/${joined}` : '/';
22
+ return joined || '.';
23
+ }
24
+ export function join(...segments) {
25
+ const joined = segments.map(normalizeSeparators).filter(Boolean).map((segment, index)=>0 === index ? segment : trimSlashes(segment)).filter(Boolean).join('/');
26
+ return joined ? normalize(joined) : '.';
27
+ }
28
+ export function resolve(...segments) {
29
+ const joined = join(...segments);
30
+ return joined.startsWith('/') ? joined : `/${joined}`;
31
+ }
32
+ export function dirname(filePath) {
33
+ const normalized = normalizeSeparators(filePath).replace(/\/+$/u, '');
34
+ const index = normalized.lastIndexOf('/');
35
+ if (index <= 0) return '/';
36
+ return normalized.slice(0, index);
37
+ }
38
+ export function basename(filePath, suffix = '') {
39
+ const normalized = normalizeSeparators(filePath).replace(/\/+$/u, '');
40
+ const base = normalized.slice(normalized.lastIndexOf('/') + 1);
41
+ return suffix && base.endsWith(suffix) ? base.slice(0, -suffix.length) : base;
42
+ }
43
+ export function extname(filePath) {
44
+ const base = basename(filePath);
45
+ const index = base.lastIndexOf('.');
46
+ if (index <= 0) return '';
47
+ return base.slice(index);
48
+ }
49
+ export default {
50
+ basename,
51
+ delimiter,
52
+ dirname,
53
+ extname,
54
+ isAbsolute,
55
+ join,
56
+ normalize,
57
+ resolve,
58
+ sep
59
+ };
@@ -1,16 +1,18 @@
1
1
  import { parseRspackConfig } from "@modern-js/builder";
2
+ import { INTERNAL_RUNTIME_PLUGINS } from "@modern-js/utils";
2
3
  import { builderPluginAdapterBasic, builderPluginAdapterHooks } from "./builder/shared/builderPlugins/index.mjs";
3
4
  import { DEFAULT_CONFIG_FILE } from "./constants.mjs";
4
5
  import { getConfigFile } from "./utils/getConfigFile.mjs";
6
+ import { loadInternalPlugins } from "./utils/loadPlugins.mjs";
5
7
  import { __webpack_require__ } from "./rslib-runtime.mjs";
6
8
  import * as __rspack_external__modern_js_plugin_cli_caa09fa2 from "@modern-js/plugin/cli";
7
9
  __webpack_require__.add({
8
- "@modern-js/plugin/cli?f956" (module) {
10
+ "@modern-js/plugin/cli?8936" (module) {
9
11
  module.exports = __rspack_external__modern_js_plugin_cli_caa09fa2;
10
12
  }
11
13
  });
12
14
  const MODERN_META_NAME = 'modern-js';
13
- const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?f956");
15
+ const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?8936");
14
16
  async function resolveModernRsbuildConfig(options) {
15
17
  const { cwd = process.cwd(), metaName = MODERN_META_NAME } = options;
16
18
  const configFile = options.configPath || getConfigFile(void 0, cwd);
@@ -19,6 +21,7 @@ async function resolveModernRsbuildConfig(options) {
19
21
  command: options.command,
20
22
  cwd,
21
23
  configFile,
24
+ internalPlugins: await loadInternalPlugins(cwd, INTERNAL_RUNTIME_PLUGINS),
22
25
  metaName,
23
26
  modifyModernConfig: options.modifyModernConfig
24
27
  });
@@ -1,5 +1,34 @@
1
1
  import "node:module";
2
+ import { createRequire } from "node:module";
3
+ import node_path from "node:path";
2
4
  import { mergeConfig } from "@modern-js/plugin/cli";
5
+ const resolveReactRouterPackageDir = ()=>{
6
+ const localRequire = createRequire(node_path.join(process.cwd(), 'package.json'));
7
+ try {
8
+ const reactRouterDomPackageJson = localRequire.resolve('react-router-dom/package.json', {
9
+ paths: [
10
+ process.cwd()
11
+ ]
12
+ });
13
+ const reactRouterPackageJson = localRequire.resolve('react-router/package.json', {
14
+ paths: [
15
+ node_path.dirname(reactRouterDomPackageJson)
16
+ ]
17
+ });
18
+ return node_path.dirname(reactRouterPackageJson);
19
+ } catch {
20
+ return;
21
+ }
22
+ };
23
+ const setReactRouterBridgeSafeAliases = (chain)=>{
24
+ const reactRouterPackageDir = resolveReactRouterPackageDir();
25
+ if (!reactRouterPackageDir) return;
26
+ const productionEntry = node_path.join(reactRouterPackageDir, 'dist/production/index.mjs');
27
+ const developmentEntry = node_path.join(reactRouterPackageDir, 'dist/development/index.mjs');
28
+ chain.resolve.alias.set('react-router$', productionEntry);
29
+ chain.resolve.alias.set('react-router/dist/production/index.js', productionEntry);
30
+ chain.resolve.alias.set('react-router/dist/development/index.js', developmentEntry);
31
+ };
3
32
  const createAppBaselineConfig = (options = {})=>{
4
33
  const { appId = 'app', enableBffRequestId = true, enableTelemetry = true, enableTelemetryExporters = true, otlpEndpoint = process.env.MODERN_TELEMETRY_OTLP_ENDPOINT || 'http://127.0.0.1:4318/v1/logs', victoriaMetricsEndpoint = process.env.MODERN_TELEMETRY_VICTORIA_ENDPOINT || 'http://127.0.0.1:8428/api/v1/import/prometheus', telemetryFailLoudStartup = true, enableModuleFederationSSR = true } = options;
5
34
  const server = {};
@@ -33,7 +62,10 @@ const createAppBaselineConfig = (options = {})=>{
33
62
  disableClientServer: true
34
63
  }
35
64
  },
36
- server
65
+ server,
66
+ tools: {
67
+ bundlerChain: setReactRouterBridgeSafeAliases
68
+ }
37
69
  };
38
70
  if (enableBffRequestId) baselineConfig.bff = {
39
71
  requestId: appId
@@ -1,6 +1,74 @@
1
- import "node:module";
1
+ import __rslib_shim_module__ from "node:module";
2
+ const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
3
+ import node_fs from "node:fs";
4
+ import node_path from "node:path";
2
5
  import { SERVICE_WORKER_ENVIRONMENT_NAME } from "@modern-js/builder";
3
6
  import { isProd, isSSR, isServiceWorker, isUseRsc, isUseSSRBundle } from "@modern-js/utils";
7
+ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
8
+ import { dirname as __rspack_dirname } from "node:path";
9
+ var getBuilderEnvironments_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
10
+ const BFF_EFFECT_WORKER_ENTRY_NAME = '__modern_bff_effect';
11
+ const BFF_EFFECT_WORKER_RUNTIME_QUERY = 'modern-bff-runtime';
12
+ const JS_OR_TS_EXTS = [
13
+ '.ts',
14
+ '.tsx',
15
+ '.js',
16
+ '.jsx',
17
+ '.mjs',
18
+ '.cjs'
19
+ ];
20
+ const CLOUDFLARE_WORKER_COMPAT_TEMPLATE_DIR = node_path.resolve(getBuilderEnvironments_dirname, '../../plugins/deploy/platforms/templates');
21
+ function findExistingFile(candidates) {
22
+ return candidates.find((candidate)=>node_fs.existsSync(candidate));
23
+ }
24
+ function resolvePackageEntry(packageName, paths) {
25
+ try {
26
+ return node_fs.realpathSync(require.resolve(packageName, {
27
+ paths
28
+ }));
29
+ } catch {
30
+ return;
31
+ }
32
+ }
33
+ function resolvePackageFile(packageName, filePath, paths) {
34
+ try {
35
+ return node_fs.realpathSync(require.resolve(`${packageName}/${filePath}`, {
36
+ paths
37
+ }));
38
+ } catch {
39
+ const packageEntry = resolvePackageEntry(packageName, paths);
40
+ if (!packageEntry) return;
41
+ const packageRoot = findPackageRoot(packageEntry, packageName);
42
+ const packageFile = packageRoot ? node_path.join(packageRoot, filePath) : void 0;
43
+ return packageFile && node_fs.existsSync(packageFile) ? node_fs.realpathSync(packageFile) : void 0;
44
+ }
45
+ }
46
+ function findPackageRoot(entryFile, packageName) {
47
+ let directory = node_path.dirname(entryFile);
48
+ while(directory !== node_path.dirname(directory)){
49
+ const packageJsonPath = node_path.join(directory, 'package.json');
50
+ try {
51
+ const packageJson = JSON.parse(node_fs.readFileSync(packageJsonPath, 'utf-8'));
52
+ if (packageJson.name === packageName) return directory;
53
+ } catch {}
54
+ directory = node_path.dirname(directory);
55
+ }
56
+ }
57
+ function setAliasIfPresent(alias, name, value) {
58
+ if (value) alias.set(name, value);
59
+ }
60
+ function getCloudflareWorkerCompatFile(file) {
61
+ return node_path.join(CLOUDFLARE_WORKER_COMPAT_TEMPLATE_DIR, file);
62
+ }
63
+ function getEffectBffEntry(normalizedConfig, appContext) {
64
+ if (!normalizedConfig.bff || 'hono' === normalizedConfig.bff.runtimeFramework) return;
65
+ const configuredEntry = normalizedConfig.bff.effect?.entry;
66
+ const entryWithoutExtension = configuredEntry ? node_path.isAbsolute(configuredEntry) ? configuredEntry : node_path.resolve(appContext.appDirectory, configuredEntry) : node_path.resolve(appContext.apiDirectory, 'effect', 'index');
67
+ return findExistingFile(JS_OR_TS_EXTS.map((extension)=>`${entryWithoutExtension}${extension}`));
68
+ }
69
+ function isCloudflareWorkerDeploy(normalizedConfig) {
70
+ return normalizedConfig.deploy?.target === 'cloudflare' || 'cloudflare' === process.env.MODERNJS_DEPLOY;
71
+ }
4
72
  function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig) {
5
73
  const entries = {};
6
74
  const { entrypoints = [], checkedEntries } = appContext;
@@ -17,6 +85,11 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
17
85
  const v = entries[entry];
18
86
  serverEntries[entry] = v.map((entry)=>entry.replace('index.jsx', 'index.server.jsx')).map((entry)=>entry.replace('bootstrap.jsx', 'bootstrap.server.jsx'));
19
87
  }
88
+ const cloudflareWorkerServerEntries = {};
89
+ for(const entry in entries){
90
+ const v = entries[entry];
91
+ cloudflareWorkerServerEntries[entry] = v.map((entry)=>entry.replace('index.jsx', 'index.server.jsx')).map((entry)=>entry.replace('bootstrap.jsx', 'index.server.jsx'));
92
+ }
20
93
  const environments = {
21
94
  client: {
22
95
  output: {
@@ -41,14 +114,117 @@ function getBuilderEnvironments(normalizedConfig, appContext, tempBuilderConfig)
41
114
  }
42
115
  };
43
116
  const useWorkerTarget = isServiceWorker(normalizedConfig);
44
- if (useWorkerTarget) environments[SERVICE_WORKER_ENVIRONMENT_NAME] = {
45
- output: {
46
- target: 'web-worker'
47
- },
48
- source: {
49
- entry: serverEntries
50
- }
51
- };
117
+ if (useWorkerTarget) {
118
+ const useCloudflareModuleWorker = isCloudflareWorkerDeploy(normalizedConfig);
119
+ const effectBffEntry = useCloudflareModuleWorker ? getEffectBffEntry(normalizedConfig, appContext) : void 0;
120
+ const tanstackRouterSsrServerFile = useCloudflareModuleWorker ? resolvePackageFile('@tanstack/router-core', 'dist/esm/ssr/ssr-server.js', [
121
+ appContext.appDirectory,
122
+ process.cwd()
123
+ ]) : void 0;
124
+ const runtimeRscWorkerFile = useCloudflareModuleWorker ? resolvePackageFile('@modern-js/runtime', 'dist/esm/rsc/server.worker.mjs', [
125
+ appContext.appDirectory,
126
+ process.cwd()
127
+ ]) : void 0;
128
+ const renderRscWorkerFile = useCloudflareModuleWorker ? resolvePackageFile('@modern-js/render', 'dist/esm/rscWorker.mjs', [
129
+ appContext.appDirectory,
130
+ process.cwd()
131
+ ]) : void 0;
132
+ const reactFile = useCloudflareModuleWorker ? resolvePackageFile('react', 'index.js', [
133
+ appContext.appDirectory,
134
+ process.cwd()
135
+ ]) : void 0;
136
+ const reactJsxRuntimeFile = useCloudflareModuleWorker ? resolvePackageFile('react', 'jsx-runtime.js', [
137
+ appContext.appDirectory,
138
+ process.cwd()
139
+ ]) : void 0;
140
+ const reactJsxDevRuntimeFile = useCloudflareModuleWorker ? resolvePackageFile('react', 'jsx-dev-runtime.js', [
141
+ appContext.appDirectory,
142
+ process.cwd()
143
+ ]) : void 0;
144
+ const reactDomFile = useCloudflareModuleWorker ? resolvePackageFile('react-dom', 'index.js', [
145
+ appContext.appDirectory,
146
+ process.cwd()
147
+ ]) : void 0;
148
+ const reactDomServerEdgeFile = useCloudflareModuleWorker ? resolvePackageFile('react-dom', 'server.edge.js', [
149
+ appContext.appDirectory,
150
+ process.cwd()
151
+ ]) : void 0;
152
+ const loadableComponentFile = useCloudflareModuleWorker ? resolvePackageFile('@loadable/component', 'dist/esm/loadable.esm.mjs', [
153
+ appContext.appDirectory,
154
+ process.cwd(),
155
+ CLOUDFLARE_WORKER_COMPAT_TEMPLATE_DIR
156
+ ]) : void 0;
157
+ const loadableServerWorkerFile = useCloudflareModuleWorker ? getCloudflareWorkerCompatFile('cloudflare-worker-loadable-server.mjs') : void 0;
158
+ const fsPromisesWorkerFile = useCloudflareModuleWorker ? getCloudflareWorkerCompatFile('cloudflare-worker-fs-promises.mjs') : void 0;
159
+ const pathWorkerFile = useCloudflareModuleWorker ? getCloudflareWorkerCompatFile('cloudflare-worker-path.mjs') : void 0;
160
+ const baseWorkerEntries = useCloudflareModuleWorker ? cloudflareWorkerServerEntries : serverEntries;
161
+ const workerEntries = effectBffEntry ? {
162
+ ...baseWorkerEntries,
163
+ [BFF_EFFECT_WORKER_ENTRY_NAME]: [
164
+ `${effectBffEntry}?${BFF_EFFECT_WORKER_RUNTIME_QUERY}`
165
+ ]
166
+ } : baseWorkerEntries;
167
+ environments[SERVICE_WORKER_ENVIRONMENT_NAME] = {
168
+ output: {
169
+ target: useCloudflareModuleWorker ? 'web' : 'web-worker',
170
+ ...useCloudflareModuleWorker ? {
171
+ module: true
172
+ } : {}
173
+ },
174
+ source: {
175
+ entry: workerEntries
176
+ },
177
+ tools: {
178
+ htmlPlugin: false,
179
+ ...useCloudflareModuleWorker ? {
180
+ bundlerChain: (chain)=>{
181
+ chain.merge({
182
+ experiments: {
183
+ outputModule: true
184
+ }
185
+ });
186
+ chain.output.module(true).library({
187
+ type: 'module'
188
+ }).chunkFormat('module').chunkLoading('import').workerChunkLoading('import');
189
+ chain.target('webworker');
190
+ chain.plugins.delete('plugin-module-federation');
191
+ if (tanstackRouterSsrServerFile) {
192
+ chain.resolve.alias.set('@tanstack/router-core/ssr/server$', tanstackRouterSsrServerFile);
193
+ chain.resolve.alias.set('@tanstack/router-core/ssr/server', tanstackRouterSsrServerFile);
194
+ }
195
+ if (runtimeRscWorkerFile) {
196
+ chain.resolve.alias.set('@modern-js/runtime/rsc/server$', runtimeRscWorkerFile);
197
+ chain.resolve.alias.set('@modern-js/runtime/rsc/server', runtimeRscWorkerFile);
198
+ }
199
+ if (renderRscWorkerFile) {
200
+ chain.resolve.alias.set('@modern-js/render/rsc$', renderRscWorkerFile);
201
+ chain.resolve.alias.set('@modern-js/render/rsc', renderRscWorkerFile);
202
+ chain.resolve.alias.set('@modern-js/render/rsc-worker$', renderRscWorkerFile);
203
+ }
204
+ setAliasIfPresent(chain.resolve.alias, 'react$', reactFile);
205
+ setAliasIfPresent(chain.resolve.alias, 'react/jsx-runtime$', reactJsxRuntimeFile);
206
+ setAliasIfPresent(chain.resolve.alias, 'react/jsx-dev-runtime$', reactJsxDevRuntimeFile);
207
+ setAliasIfPresent(chain.resolve.alias, 'react-dom$', reactDomFile);
208
+ setAliasIfPresent(chain.resolve.alias, 'react-dom/server.edge$', reactDomServerEdgeFile);
209
+ setAliasIfPresent(chain.resolve.alias, '@loadable/component$', loadableComponentFile);
210
+ setAliasIfPresent(chain.resolve.alias, '@loadable/server$', loadableServerWorkerFile);
211
+ setAliasIfPresent(chain.resolve.alias, 'fs/promises$', fsPromisesWorkerFile);
212
+ setAliasIfPresent(chain.resolve.alias, 'node:fs/promises$', fsPromisesWorkerFile);
213
+ setAliasIfPresent(chain.resolve.alias, 'path$', pathWorkerFile);
214
+ setAliasIfPresent(chain.resolve.alias, 'node:path$', pathWorkerFile);
215
+ chain.resolve.alias.set('react-server-dom-rspack/server.node$', 'react-server-dom-rspack/server.edge');
216
+ chain.resolve.alias.set('react-server-dom-rspack/server.node', 'react-server-dom-rspack/server.edge');
217
+ chain.resolve.alias.set('react-server-dom-rspack/client.node$', 'react-server-dom-rspack/client.edge');
218
+ chain.resolve.alias.set('react-server-dom-rspack/client.node', 'react-server-dom-rspack/client.edge');
219
+ chain.resolve.fallback.set('async_hooks', false);
220
+ chain.resolve.fallback.set('node:async_hooks', false);
221
+ chain.resolve.fallback.set('fs', false);
222
+ chain.resolve.fallback.set('node:fs', false);
223
+ }
224
+ } : {}
225
+ }
226
+ };
227
+ }
52
228
  return {
53
229
  environments,
54
230
  builderConfig: tempBuilderConfig
@@ -9,8 +9,11 @@ const builderPluginAdapterBasic = (options)=>({
9
9
  setup (api) {
10
10
  api.modifyBundlerChain((chain, { target, CHAIN_ID, environment })=>{
11
11
  const isServiceWorker = environment.name === SERVICE_WORKER_ENVIRONMENT_NAME;
12
- if ('node' === target || isServiceWorker) applyNodeCompat(isServiceWorker, chain);
13
- if ('web' === target) {
12
+ const isWebTargetServiceWorker = isServiceWorker && 'web' === target;
13
+ if ('node' === target || isServiceWorker) applyNodeCompat(isServiceWorker, chain, {
14
+ includeNodeExtensions: !isWebTargetServiceWorker
15
+ });
16
+ if ('web' === target && !isServiceWorker) {
14
17
  const bareServerModuleReg = /\.(server|node)\.[tj]sx?$/;
15
18
  const depExt = 'mjs';
16
19
  chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(bareServerModuleReg);
@@ -26,8 +29,40 @@ const builderPluginAdapterBasic = (options)=>({
26
29
  });
27
30
  api.modifyRspackConfig((config, { target, environment })=>{
28
31
  const isServiceWorker = environment.name === SERVICE_WORKER_ENVIRONMENT_NAME;
32
+ const isWebTargetServiceWorker = isServiceWorker && 'web' === target;
29
33
  if ('node' === target || isServiceWorker) {
30
- const extensionAlias = {
34
+ const extensionAlias = isWebTargetServiceWorker ? {
35
+ '.js': [
36
+ '.worker.js',
37
+ '.server.js',
38
+ '.js'
39
+ ],
40
+ '.jsx': [
41
+ '.worker.jsx',
42
+ '.server.jsx',
43
+ '.jsx'
44
+ ],
45
+ '.ts': [
46
+ '.worker.ts',
47
+ '.server.ts',
48
+ '.ts'
49
+ ],
50
+ '.tsx': [
51
+ '.worker.tsx',
52
+ '.server.tsx',
53
+ '.tsx'
54
+ ],
55
+ '.mjs': [
56
+ '.worker.mjs',
57
+ '.server.mjs',
58
+ '.mjs'
59
+ ],
60
+ '.json': [
61
+ '.worker.json',
62
+ '.server.json',
63
+ '.json'
64
+ ]
65
+ } : {
31
66
  '.js': [
32
67
  '.node.js',
33
68
  '.server.js',
@@ -68,7 +103,8 @@ const builderPluginAdapterBasic = (options)=>({
68
103
  });
69
104
  }
70
105
  });
71
- function applyNodeCompat(isServiceWorker, chain) {
106
+ function applyNodeCompat(isServiceWorker, chain, options = {}) {
107
+ const { includeNodeExtensions = true } = options;
72
108
  const nodeExts = [
73
109
  '.node.js',
74
110
  '.node.jsx',
@@ -87,7 +123,7 @@ function applyNodeCompat(isServiceWorker, chain) {
87
123
  '.worker.ts',
88
124
  '.worker.tsx'
89
125
  ];
90
- for (const ext of nodeExts)chain.resolve.extensions.prepend(ext);
126
+ if (includeNodeExtensions) for (const ext of nodeExts)chain.resolve.extensions.prepend(ext);
91
127
  if (isServiceWorker) for (const ext of webWorkerExts)chain.resolve.extensions.prepend(ext);
92
128
  }
93
129
  export { builderPluginAdapterBasic };
@@ -96,9 +96,10 @@ function applyFilterEntriesBySSRConfig({ isProd, chain, appNormalizedConfig }) {
96
96
  });
97
97
  }
98
98
  async function applySSRLoaderEntry(chain, optinos, isServer) {
99
- const { appContext } = optinos;
99
+ const { appContext, normalizedConfig } = optinos;
100
100
  const { internalDirectory } = appContext;
101
101
  const { entrypoints } = appContext;
102
+ const isRsc = isUseRsc(normalizedConfig);
102
103
  await Promise.all(entrypoints.map(async (entrypoint)=>{
103
104
  const { entryName } = entrypoint;
104
105
  const serverLoadersFile = getServerCombinedModuleFile(internalDirectory, entryName);
@@ -106,6 +107,7 @@ async function applySSRLoaderEntry(chain, optinos, isServer) {
106
107
  await fs.access(serverLoadersFile, fs.constants.F_OK);
107
108
  chain.entry(`${entryName}-server-loaders`).add(serverLoadersFile);
108
109
  } catch (err) {}
110
+ else if (isRsc) chain.entry(`${entryName}-server-loaders`).add("data:text/javascript,export%20{};");
109
111
  }));
110
112
  }
111
113
  function applySSRDataLoader(chain, options) {