@bleedingdev/modern-js-app-tools 3.2.0-ultramodern.98 → 3.4.0-ultramodern.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 (165) hide show
  1. package/dist/cjs/baseline.js +12 -92
  2. package/dist/cjs/builder/builder-rspack/index.js +9 -5
  3. package/dist/cjs/builder/generator/adapterCopy.js +9 -5
  4. package/dist/cjs/builder/generator/createBuilderProviderConfig.js +9 -5
  5. package/dist/cjs/builder/generator/createCopyPattern.js +9 -5
  6. package/dist/cjs/builder/generator/getBuilderEnvironments.js +41 -9
  7. package/dist/cjs/builder/generator/index.js +16 -5
  8. package/dist/cjs/builder/index.js +9 -5
  9. package/dist/cjs/builder/shared/builderPlugins/adapterBasic.js +9 -5
  10. package/dist/cjs/builder/shared/builderPlugins/adapterHtml.js +10 -6
  11. package/dist/cjs/builder/shared/builderPlugins/adapterPrecompress.js +9 -5
  12. package/dist/cjs/builder/shared/builderPlugins/adapterSSR.js +39 -9
  13. package/dist/cjs/builder/shared/builderPlugins/builderHooks.js +12 -8
  14. package/dist/cjs/builder/shared/builderPlugins/index.js +9 -5
  15. package/dist/cjs/builder/shared/bundlerPlugins/HtmlAsyncChunkPlugin.js +9 -5
  16. package/dist/cjs/builder/shared/bundlerPlugins/HtmlBottomTemplate.js +12 -8
  17. package/dist/cjs/builder/shared/bundlerPlugins/RouterPlugin.js +41 -8
  18. package/dist/cjs/builder/shared/bundlerPlugins/index.js +9 -5
  19. package/dist/cjs/builder/shared/createCopyInfo.js +9 -5
  20. package/dist/cjs/builder/shared/index.js +9 -5
  21. package/dist/cjs/builder/shared/lazyCompilation.js +94 -0
  22. package/dist/cjs/builder/shared/loaders/serverModuleLoader.js +12 -8
  23. package/dist/cjs/commands/build.js +9 -5
  24. package/dist/cjs/commands/deploy.js +9 -5
  25. package/dist/cjs/commands/dev.js +9 -5
  26. package/dist/cjs/commands/index.js +12 -11
  27. package/dist/cjs/commands/info.js +9 -5
  28. package/dist/cjs/commands/inspect.js +12 -8
  29. package/dist/cjs/commands/runtime.js +50 -13
  30. package/dist/cjs/commands/serve.js +9 -5
  31. package/dist/cjs/compat/hooks.js +9 -5
  32. package/dist/cjs/compat/index.js +9 -5
  33. package/dist/cjs/compat/utils.js +9 -5
  34. package/dist/cjs/config/default.js +27 -7
  35. package/dist/cjs/config/index.js +9 -5
  36. package/dist/cjs/config/initialize/index.js +9 -5
  37. package/dist/cjs/config/initialize/inits.js +9 -5
  38. package/dist/cjs/constants.js +13 -9
  39. package/dist/cjs/defineConfig.js +12 -8
  40. package/dist/cjs/esm/register-esm.js +12 -8
  41. package/dist/cjs/esm/ts-paths-loader.js +9 -5
  42. package/dist/cjs/index.js +23 -17
  43. package/dist/cjs/locale/en.js +12 -8
  44. package/dist/cjs/locale/index.js +9 -5
  45. package/dist/cjs/locale/zh.js +12 -8
  46. package/dist/cjs/plugins/analyze/constants.js +14 -10
  47. package/dist/cjs/plugins/analyze/getBundleEntry.js +9 -5
  48. package/dist/cjs/plugins/analyze/getFileSystemEntry.js +9 -5
  49. package/dist/cjs/plugins/analyze/getHtmlTemplate.js +9 -5
  50. package/dist/cjs/plugins/analyze/getServerRoutes.js +9 -5
  51. package/dist/cjs/plugins/analyze/index.js +12 -6
  52. package/dist/cjs/plugins/analyze/isDefaultExportFunction.js +10 -6
  53. package/dist/cjs/plugins/analyze/templates.js +12 -8
  54. package/dist/cjs/plugins/analyze/utils.js +9 -5
  55. package/dist/cjs/plugins/deploy/index.js +9 -5
  56. package/dist/cjs/plugins/deploy/platforms/cloudflare.js +185 -7
  57. package/dist/cjs/plugins/deploy/platforms/gh-pages.js +9 -5
  58. package/dist/cjs/plugins/deploy/platforms/netlify.js +9 -5
  59. package/dist/cjs/plugins/deploy/platforms/node.js +9 -5
  60. package/dist/cjs/plugins/deploy/platforms/templates/cloudflare-entry.mjs +141 -16
  61. package/dist/cjs/plugins/deploy/platforms/vercel.js +9 -5
  62. package/dist/cjs/plugins/deploy/utils/generator.js +9 -5
  63. package/dist/cjs/plugins/deploy/utils/index.js +19 -40
  64. package/dist/cjs/plugins/initialize/index.js +19 -6
  65. package/dist/cjs/plugins/serverBuild.js +9 -5
  66. package/dist/cjs/plugins/serverRuntime.js +12 -8
  67. package/dist/cjs/presetUltramodern.js +96 -7
  68. package/dist/cjs/rsbuild.js +55 -67
  69. package/dist/cjs/run/index.js +9 -5
  70. package/dist/cjs/types/config/cloudflareDeploy.js +18 -0
  71. package/dist/cjs/types/config/index.js +9 -5
  72. package/dist/cjs/types/config/precompress.js +18 -0
  73. package/dist/cjs/types/index.js +9 -5
  74. package/dist/cjs/ultramodern/designSystem.js +16 -12
  75. package/dist/cjs/utils/config.js +9 -5
  76. package/dist/cjs/utils/createServer.js +14 -10
  77. package/dist/cjs/utils/env.js +9 -5
  78. package/dist/cjs/utils/generateWatchFiles.js +9 -5
  79. package/dist/cjs/utils/getConfigFile.js +9 -5
  80. package/dist/cjs/utils/getSelectedEntries.js +9 -5
  81. package/dist/cjs/utils/initAppContext.js +9 -5
  82. package/dist/cjs/utils/loadPlugins.js +9 -5
  83. package/dist/cjs/utils/printInstructions.js +9 -5
  84. package/dist/cjs/utils/register.js +9 -5
  85. package/dist/cjs/utils/restart.js +9 -5
  86. package/dist/cjs/utils/routes.js +9 -5
  87. package/dist/esm/baseline.mjs +3 -77
  88. package/dist/esm/builder/generator/getBuilderEnvironments.mjs +32 -4
  89. package/dist/esm/builder/generator/index.mjs +7 -0
  90. package/dist/esm/builder/shared/builderPlugins/adapterHtml.mjs +1 -1
  91. package/dist/esm/builder/shared/builderPlugins/adapterSSR.mjs +31 -5
  92. package/dist/esm/builder/shared/bundlerPlugins/RouterPlugin.mjs +32 -3
  93. package/dist/esm/builder/shared/lazyCompilation.mjs +44 -0
  94. package/dist/esm/commands/index.mjs +2 -5
  95. package/dist/esm/commands/runtime.mjs +33 -3
  96. package/dist/esm/config/default.mjs +14 -1
  97. package/dist/esm/index.mjs +3 -2
  98. package/dist/esm/plugins/analyze/index.mjs +3 -1
  99. package/dist/esm/plugins/analyze/isDefaultExportFunction.mjs +1 -1
  100. package/dist/esm/plugins/deploy/platforms/cloudflare.mjs +176 -2
  101. package/dist/esm/plugins/deploy/platforms/templates/cloudflare-entry.mjs +141 -16
  102. package/dist/esm/plugins/deploy/utils/index.mjs +11 -36
  103. package/dist/esm/plugins/initialize/index.mjs +11 -2
  104. package/dist/esm/presetUltramodern.mjs +77 -3
  105. package/dist/esm/rsbuild.mjs +1 -8
  106. package/dist/esm/types/config/cloudflareDeploy.mjs +0 -0
  107. package/dist/esm/types/config/precompress.mjs +0 -0
  108. package/dist/esm-node/baseline.mjs +3 -77
  109. package/dist/esm-node/builder/generator/getBuilderEnvironments.mjs +32 -4
  110. package/dist/esm-node/builder/generator/index.mjs +7 -0
  111. package/dist/esm-node/builder/shared/builderPlugins/adapterHtml.mjs +1 -1
  112. package/dist/esm-node/builder/shared/builderPlugins/adapterSSR.mjs +31 -5
  113. package/dist/esm-node/builder/shared/bundlerPlugins/RouterPlugin.mjs +32 -3
  114. package/dist/esm-node/builder/shared/lazyCompilation.mjs +45 -0
  115. package/dist/esm-node/commands/index.mjs +2 -5
  116. package/dist/esm-node/commands/runtime.mjs +33 -3
  117. package/dist/esm-node/config/default.mjs +14 -1
  118. package/dist/esm-node/index.mjs +3 -2
  119. package/dist/esm-node/plugins/analyze/index.mjs +3 -1
  120. package/dist/esm-node/plugins/analyze/isDefaultExportFunction.mjs +1 -1
  121. package/dist/esm-node/plugins/deploy/platforms/cloudflare.mjs +176 -2
  122. package/dist/esm-node/plugins/deploy/platforms/templates/cloudflare-entry.mjs +141 -16
  123. package/dist/esm-node/plugins/deploy/utils/index.mjs +12 -36
  124. package/dist/esm-node/plugins/initialize/index.mjs +11 -2
  125. package/dist/esm-node/presetUltramodern.mjs +77 -3
  126. package/dist/esm-node/rsbuild.mjs +1 -8
  127. package/dist/esm-node/types/config/cloudflareDeploy.mjs +1 -0
  128. package/dist/esm-node/types/config/precompress.mjs +1 -0
  129. package/dist/types/baseline.d.ts +16 -46
  130. package/dist/types/builder/builder-rspack/index.d.ts +1 -1
  131. package/dist/types/builder/generator/index.d.ts +1 -1
  132. package/dist/types/builder/shared/bundlerPlugins/RouterPlugin.d.ts +3 -1
  133. package/dist/types/builder/shared/createCopyInfo.d.ts +1 -1
  134. package/dist/types/builder/shared/lazyCompilation.d.ts +43 -0
  135. package/dist/types/builder/shared/types.d.ts +10 -0
  136. package/dist/types/commands/index.d.ts +1 -1
  137. package/dist/types/commands/inspect.d.ts +1 -1
  138. package/dist/types/commands/runtime.d.ts +1 -0
  139. package/dist/types/config/default.d.ts +6 -0
  140. package/dist/types/locale/index.d.ts +89 -2
  141. package/dist/types/plugins/analyze/getFileSystemEntry.d.ts +2 -2
  142. package/dist/types/plugins/analyze/index.d.ts +1 -1
  143. package/dist/types/plugins/analyze/utils.d.ts +1 -1
  144. package/dist/types/plugins/deploy/index.d.ts +1 -1
  145. package/dist/types/plugins/deploy/platforms/templates/cloudflare-entry.d.mts +1 -1
  146. package/dist/types/plugins/deploy/platforms/templates/netlify-entry.d.cts +1 -1
  147. package/dist/types/plugins/deploy/platforms/templates/vercel-entry.d.cts +1 -1
  148. package/dist/types/plugins/deploy/utils/generator.d.ts +2 -2
  149. package/dist/types/plugins/deploy/utils/index.d.ts +1 -1
  150. package/dist/types/plugins/initialize/index.d.ts +1 -1
  151. package/dist/types/plugins/serverBuild.d.ts +1 -1
  152. package/dist/types/plugins/serverRuntime.d.ts +1 -1
  153. package/dist/types/presetUltramodern.d.ts +52 -2
  154. package/dist/types/rsbuild.d.ts +1 -1
  155. package/dist/types/run/index.d.ts +1 -1
  156. package/dist/types/types/config/cloudflareDeploy.d.ts +79 -0
  157. package/dist/types/types/config/deploy.d.ts +9 -15
  158. package/dist/types/types/config/output.d.ts +4 -20
  159. package/dist/types/types/config/precompress.d.ts +20 -0
  160. package/dist/types/types/plugin.d.ts +20 -0
  161. package/dist/types/utils/getConfigFile.d.ts +1 -1
  162. package/dist/types/utils/loadPlugins.d.ts +2 -2
  163. package/package.json +26 -21
  164. package/dist/esm/rslib-runtime.mjs +0 -18
  165. package/dist/esm-node/rslib-runtime.mjs +0 -19
@@ -13,7 +13,88 @@ const PUBLIC_ASSETS_DIRECTORY = 'public';
13
13
  const WORKER_BUNDLE_DIRECTORY = 'worker';
14
14
  const SERVER_BUNDLE_DIRECTORY = 'bundles';
15
15
  const BFF_EFFECT_WORKER_ENTRY = `${WORKER_BUNDLE_DIRECTORY}/__modern_bff_effect.js`;
16
- const getCompatibilityDate = ()=>new Date().toISOString().slice(0, 10);
16
+ const DEFAULT_COMPATIBILITY_DATE = '2026-06-02';
17
+ const COMPATIBILITY_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
18
+ const DEFAULT_SECURITY_HEADERS = {
19
+ referrerPolicy: 'strict-origin-when-cross-origin',
20
+ contentTypeOptions: 'nosniff',
21
+ permissionsPolicy: 'camera=(), geolocation=(), microphone=(), payment=(), usb=()'
22
+ };
23
+ const DEFAULT_CORS_ALLOWED_METHODS = [
24
+ 'GET',
25
+ 'HEAD',
26
+ 'POST',
27
+ 'PUT',
28
+ 'PATCH',
29
+ 'DELETE',
30
+ 'OPTIONS'
31
+ ];
32
+ const DEFAULT_CSP_DIRECTIVES = {
33
+ 'base-uri': [
34
+ "'self'"
35
+ ],
36
+ 'connect-src': [
37
+ "'self'",
38
+ 'https:',
39
+ 'http:',
40
+ 'wss:',
41
+ 'ws:'
42
+ ],
43
+ 'default-src': [
44
+ "'self'"
45
+ ],
46
+ 'font-src': [
47
+ "'self'",
48
+ 'data:',
49
+ 'https:',
50
+ 'http:'
51
+ ],
52
+ 'form-action': [
53
+ "'self'"
54
+ ],
55
+ 'frame-ancestors': [
56
+ "'self'"
57
+ ],
58
+ 'img-src': [
59
+ "'self'",
60
+ 'data:',
61
+ 'blob:',
62
+ 'https:',
63
+ 'http:'
64
+ ],
65
+ 'manifest-src': [
66
+ "'self'",
67
+ 'https:',
68
+ 'http:'
69
+ ],
70
+ 'object-src': [
71
+ "'none'"
72
+ ],
73
+ "script-src": [
74
+ "'self'",
75
+ "'unsafe-inline'",
76
+ "'unsafe-eval'",
77
+ 'https:',
78
+ 'http:',
79
+ 'blob:'
80
+ ],
81
+ 'style-src': [
82
+ "'self'",
83
+ "'unsafe-inline'",
84
+ 'https:',
85
+ 'http:'
86
+ ],
87
+ 'worker-src': [
88
+ "'self'",
89
+ 'blob:'
90
+ ]
91
+ };
92
+ const getCompatibilityDate = (modernConfig)=>{
93
+ const configuredDate = modernConfig.deploy?.worker?.compatibilityDate?.trim();
94
+ const compatibilityDate = configuredDate || DEFAULT_COMPATIBILITY_DATE;
95
+ if (!COMPATIBILITY_DATE_PATTERN.test(compatibilityDate)) throw new Error(`deploy.worker.compatibilityDate must use YYYY-MM-DD, received ${JSON.stringify(compatibilityDate)}.`);
96
+ return compatibilityDate;
97
+ };
17
98
  const getWorkerName = (appDirectory)=>{
18
99
  const basename = node_path.basename(appDirectory);
19
100
  return basename.replace(/[^a-zA-Z0-9-_]/g, '-') || 'modern-cloudflare-worker';
@@ -22,6 +103,98 @@ const getConfiguredWorkerName = (appDirectory, modernConfig)=>{
22
103
  const configuredName = modernConfig.deploy?.worker?.name?.trim();
23
104
  return configuredName || getWorkerName(appDirectory);
24
105
  };
106
+ const normalizeDirectiveValues = (value)=>{
107
+ const values = Array.isArray(value) ? value : [
108
+ value
109
+ ];
110
+ return [
111
+ ...new Set(values.map((entry)=>entry.trim()).filter(Boolean))
112
+ ];
113
+ };
114
+ const appendDirectiveValues = (directives, name, values)=>{
115
+ if (!values?.length) return;
116
+ directives[name] = normalizeDirectiveValues([
117
+ ...directives[name] ?? [],
118
+ ...values
119
+ ]);
120
+ };
121
+ const createContentSecurityPolicy = (config)=>{
122
+ const mode = config?.mode ?? 'report-only';
123
+ if ('off' === mode) return {
124
+ mode,
125
+ directives: {},
126
+ reason: config?.reason
127
+ };
128
+ const directives = Object.fromEntries(Object.entries(DEFAULT_CSP_DIRECTIVES).map(([name, values])=>[
129
+ name,
130
+ [
131
+ ...values
132
+ ]
133
+ ]));
134
+ for (const [name, value] of Object.entries(config?.directives ?? {}))if (false === value) delete directives[name];
135
+ else directives[name] = normalizeDirectiveValues(value);
136
+ if (config?.frameAncestors === false) delete directives['frame-ancestors'];
137
+ else if (config?.frameAncestors) directives['frame-ancestors'] = normalizeDirectiveValues(config.frameAncestors);
138
+ appendDirectiveValues(directives, "script-src", config?.additionalScriptSrc);
139
+ appendDirectiveValues(directives, 'style-src', config?.additionalStyleSrc);
140
+ appendDirectiveValues(directives, 'connect-src', config?.additionalConnectSrc);
141
+ appendDirectiveValues(directives, 'img-src', config?.additionalImgSrc);
142
+ if (config?.reportUri) directives['report-uri'] = [
143
+ config.reportUri
144
+ ];
145
+ return {
146
+ mode,
147
+ directives,
148
+ reason: config?.reason
149
+ };
150
+ };
151
+ const createNoindexPolicy = (noindex)=>{
152
+ if (false === noindex) return {
153
+ workersDev: false,
154
+ localhost: false,
155
+ previewHostnames: []
156
+ };
157
+ if (true === noindex || void 0 === noindex) return {
158
+ workersDev: true,
159
+ localhost: true,
160
+ previewHostnames: []
161
+ };
162
+ return {
163
+ workersDev: noindex.workersDev ?? true,
164
+ localhost: noindex.localhost ?? true,
165
+ previewHostnames: noindex.previewHostnames ?? [],
166
+ reason: noindex.reason
167
+ };
168
+ };
169
+ const createCloudflareWorkerCorsPolicy = (cors)=>({
170
+ assets: cors?.assets ?? true,
171
+ allowedOrigins: normalizeDirectiveValues(cors?.allowedOrigins ?? []),
172
+ allowedMethods: cors?.allowedMethods?.length ? normalizeDirectiveValues(cors.allowedMethods.map((method)=>method.toUpperCase())) : DEFAULT_CORS_ALLOWED_METHODS,
173
+ allowedHeaders: cors?.allowedHeaders?.length ? normalizeDirectiveValues(cors.allowedHeaders) : [
174
+ '*'
175
+ ],
176
+ reason: cors?.reason
177
+ });
178
+ const createCloudflareWorkerSecurityPolicy = (modernConfig)=>{
179
+ const security = modernConfig.deploy?.worker?.security;
180
+ if (security?.enabled === false) return {
181
+ enabled: false,
182
+ cors: createCloudflareWorkerCorsPolicy(security.cors),
183
+ reason: security.reason
184
+ };
185
+ return {
186
+ enabled: true,
187
+ headers: {
188
+ referrerPolicy: security?.headers?.referrerPolicy ?? DEFAULT_SECURITY_HEADERS.referrerPolicy,
189
+ contentTypeOptions: security?.headers?.contentTypeOptions ?? DEFAULT_SECURITY_HEADERS.contentTypeOptions,
190
+ permissionsPolicy: security?.headers?.permissionsPolicy ?? DEFAULT_SECURITY_HEADERS.permissionsPolicy
191
+ },
192
+ contentSecurityPolicy: createContentSecurityPolicy(security?.contentSecurityPolicy),
193
+ noindex: createNoindexPolicy(security?.noindex),
194
+ cors: createCloudflareWorkerCorsPolicy(security?.cors),
195
+ reason: security?.reason
196
+ };
197
+ };
25
198
  const readRouteSpec = async (outputDirectory)=>{
26
199
  const routeSpecPath = node_path.join(outputDirectory, ROUTE_SPEC_OUTPUT);
27
200
  if (!await fs.pathExists(routeSpecPath)) return {
@@ -77,6 +250,7 @@ const createWorkerManifest = async (outputDirectory, modernConfig)=>{
77
250
  loadableStats: LOADABLE_STATS_FILE,
78
251
  routeManifest: ROUTE_MANIFEST_FILE
79
252
  },
253
+ security: createCloudflareWorkerSecurityPolicy(modernConfig),
80
254
  bff: isEffectBff && primaryBffPrefix && effectBffWorkerExists ? {
81
255
  runtimeFramework: 'effect',
82
256
  prefix: primaryBffPrefix,
@@ -149,7 +323,7 @@ const createCloudflarePreset = ({ appContext, modernConfig })=>{
149
323
  $schema: 'node_modules/wrangler/config-schema.json',
150
324
  name: workerName,
151
325
  main: WORKER_ENTRY,
152
- compatibility_date: getCompatibilityDate(),
326
+ compatibility_date: getCompatibilityDate(modernConfig),
153
327
  compatibility_flags: [
154
328
  'nodejs_compat',
155
329
  'global_fetch_strictly_public'
@@ -3,27 +3,129 @@ const MODERN_WORKER_MANIFEST = p_workerManifest;
3
3
  const WORKER_MODULE_LOADERS = p_workerModuleLoaders;
4
4
  const workerModulePromises = new Map();
5
5
  const remoteJsonPromises = new Map();
6
- const CORS_HEADERS = {
6
+ const CORS_POLICY = MODERN_WORKER_MANIFEST.security?.cors || {};
7
+ const ASSET_CORS_ENABLED = false !== CORS_POLICY.assets;
8
+ const APP_CORS_ALLOWED_ORIGINS = (CORS_POLICY.allowedOrigins || []).map((origin)=>String(origin).toLowerCase());
9
+ const APP_CORS_ALLOWED_METHODS = (CORS_POLICY.allowedMethods?.length ? CORS_POLICY.allowedMethods : [
10
+ 'GET',
11
+ 'HEAD',
12
+ 'POST',
13
+ 'PUT',
14
+ 'PATCH',
15
+ 'DELETE',
16
+ 'OPTIONS'
17
+ ]).join(', ');
18
+ const APP_CORS_ALLOWED_HEADERS = (CORS_POLICY.allowedHeaders?.length ? CORS_POLICY.allowedHeaders : [
19
+ '*'
20
+ ]).join(', ');
21
+ const ASSET_CORS_HEADERS = {
7
22
  'access-control-allow-headers': '*',
8
23
  'access-control-allow-methods': 'GET, HEAD, OPTIONS',
9
24
  'access-control-allow-origin': '*'
10
25
  };
11
26
  globalThis.__dirname ??= '/';
12
27
  globalThis.__filename ??= '/index.js';
13
- function withCorsHeaders(response) {
28
+ function getAllowedAppCorsOrigin(request) {
29
+ if (0 === APP_CORS_ALLOWED_ORIGINS.length) return null;
30
+ const origin = request.headers.get('origin');
31
+ if (!origin) return null;
32
+ if (APP_CORS_ALLOWED_ORIGINS.includes('*')) return '*';
33
+ return APP_CORS_ALLOWED_ORIGINS.includes(origin.toLowerCase()) ? origin : null;
34
+ }
35
+ function appendVaryOrigin(headers) {
36
+ const vary = headers.get('vary');
37
+ if (!vary) return void headers.set('vary', 'origin');
38
+ const varyValues = vary.split(',').map((value)=>value.trim().toLowerCase());
39
+ if (!varyValues.includes('origin')) headers.set('vary', `${vary}, origin`);
40
+ }
41
+ function withAppCorsHeaders(response, request) {
42
+ const allowedOrigin = getAllowedAppCorsOrigin(request);
43
+ if (!allowedOrigin) return response;
14
44
  const headers = new Headers(response.headers);
15
- for (const [name, value] of Object.entries(CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
45
+ if (!headers.has('access-control-allow-origin')) headers.set('access-control-allow-origin', allowedOrigin);
46
+ if ('*' !== allowedOrigin) appendVaryOrigin(headers);
16
47
  return new Response(response.body, {
17
48
  headers,
18
49
  status: response.status,
19
50
  statusText: response.statusText
20
51
  });
21
52
  }
53
+ function withAssetCorsHeaders(response) {
54
+ if (!ASSET_CORS_ENABLED) return response;
55
+ const headers = new Headers(response.headers);
56
+ for (const [name, value] of Object.entries(ASSET_CORS_HEADERS))if (!headers.has(name)) headers.set(name, value);
57
+ return new Response(response.body, {
58
+ headers,
59
+ status: response.status,
60
+ statusText: response.statusText
61
+ });
62
+ }
63
+ function setHeaderIfEnabled(headers, name, value) {
64
+ if (false === value || 'string' != typeof value || '' === value.trim()) return;
65
+ if (!headers.has(name)) headers.set(name, value);
66
+ }
67
+ function renderContentSecurityPolicy(directives) {
68
+ return Object.entries(directives || {}).filter(([, values])=>Array.isArray(values) && values.length > 0).sort(([left], [right])=>left.localeCompare(right)).map(([name, values])=>`${name} ${values.join(' ')}`).join('; ');
69
+ }
70
+ function isHtmlResponse(response) {
71
+ return (response.headers.get('content-type') || '').includes('text/html');
72
+ }
73
+ function matchesPreviewHostname(hostname, pattern) {
74
+ const normalizedHostname = hostname.toLowerCase();
75
+ const normalizedPattern = String(pattern || '').toLowerCase();
76
+ if (!normalizedPattern) return false;
77
+ if (normalizedPattern.startsWith('*.')) return normalizedHostname.endsWith(normalizedPattern.slice(1));
78
+ return normalizedHostname === normalizedPattern;
79
+ }
80
+ function shouldNoindex(request, noindex) {
81
+ if (!noindex || false === noindex) return false;
82
+ const { hostname } = new URL(request.url);
83
+ const normalizedHostname = hostname.toLowerCase();
84
+ if (false !== noindex.localhost && ('localhost' === normalizedHostname || '127.0.0.1' === normalizedHostname || '[::1]' === normalizedHostname)) return true;
85
+ if (false !== noindex.workersDev && normalizedHostname.endsWith('.workers.dev')) return true;
86
+ return (noindex.previewHostnames || []).some((pattern)=>matchesPreviewHostname(normalizedHostname, pattern));
87
+ }
88
+ function withCloudflareSecurityHeaders(response, request) {
89
+ const security = MODERN_WORKER_MANIFEST.security;
90
+ if (!security || false === security.enabled) return response;
91
+ const headers = new Headers(response.headers);
92
+ const configuredHeaders = security.headers || {};
93
+ setHeaderIfEnabled(headers, 'referrer-policy', configuredHeaders.referrerPolicy);
94
+ setHeaderIfEnabled(headers, 'x-content-type-options', configuredHeaders.contentTypeOptions);
95
+ setHeaderIfEnabled(headers, 'permissions-policy', configuredHeaders.permissionsPolicy);
96
+ const csp = security.contentSecurityPolicy;
97
+ const cspHeader = csp?.mode === 'enforce' ? 'content-security-policy' : 'content-security-policy-report-only';
98
+ const cspValue = renderContentSecurityPolicy(csp?.directives);
99
+ if (isHtmlResponse(response) && csp?.mode !== 'off' && cspValue && !headers.has(cspHeader)) headers.set(cspHeader, cspValue);
100
+ if (shouldNoindex(request, security.noindex)) headers.set('x-robots-tag', 'noindex, nofollow');
101
+ return new Response(response.body, {
102
+ headers,
103
+ status: response.status,
104
+ statusText: response.statusText
105
+ });
106
+ }
107
+ function createRenderableRequest(request) {
108
+ if ('HEAD' !== request.method) return request;
109
+ return new Request(request, {
110
+ method: 'GET'
111
+ });
112
+ }
113
+ function finalizeResponseForRequest(response, request) {
114
+ const securedResponse = withCloudflareSecurityHeaders(response, request);
115
+ if ('HEAD' !== request.method) return securedResponse;
116
+ const headers = new Headers(securedResponse.headers);
117
+ headers.delete('content-length');
118
+ return new Response(null, {
119
+ headers,
120
+ status: securedResponse.status,
121
+ statusText: securedResponse.statusText
122
+ });
123
+ }
22
124
  function isFingerprintedAssetPathname(pathname) {
23
125
  return /(?:^|\/)[^/]+\.[a-f0-9]{8,}\.(?:css|js|mjs|json|svg|png|jpe?g|webp|avif|gif|woff2?|ttf)$/iu.test(pathname);
24
126
  }
25
127
  function withAssetHeaders(response, request) {
26
- const corsResponse = withCorsHeaders(response);
128
+ const corsResponse = withAssetCorsHeaders(response);
27
129
  const headers = new Headers(corsResponse.headers);
28
130
  const { pathname } = new URL(request.url);
29
131
  if (isFingerprintedAssetPathname(pathname)) headers.set('cache-control', 'public, max-age=31536000, immutable');
@@ -33,10 +135,30 @@ function withAssetHeaders(response, request) {
33
135
  statusText: corsResponse.statusText
34
136
  });
35
137
  }
36
- function createCorsPreflightResponse(request) {
138
+ async function createCorsPreflightResponse(request, env) {
37
139
  if ('OPTIONS' !== request.method) return null;
140
+ const allowedOrigin = getAllowedAppCorsOrigin(request);
141
+ if (allowedOrigin) {
142
+ const headers = new Headers({
143
+ 'access-control-allow-headers': APP_CORS_ALLOWED_HEADERS,
144
+ 'access-control-allow-methods': APP_CORS_ALLOWED_METHODS,
145
+ 'access-control-allow-origin': allowedOrigin
146
+ });
147
+ if ('*' !== allowedOrigin) headers.set('vary', 'origin');
148
+ return new Response(null, {
149
+ headers,
150
+ status: 204
151
+ });
152
+ }
153
+ if (!ASSET_CORS_ENABLED) return null;
154
+ const assets = env?.[ASSETS_BINDING];
155
+ if (!assets || 'function' != typeof assets.fetch) return null;
156
+ const assetResponse = await assets.fetch(new Request(request.url, {
157
+ method: 'HEAD'
158
+ }));
159
+ if (!assetResponse || 404 === assetResponse.status) return null;
38
160
  return new Response(null, {
39
- headers: CORS_HEADERS,
161
+ headers: ASSET_CORS_HEADERS,
40
162
  status: 204
41
163
  });
42
164
  }
@@ -417,22 +539,25 @@ async function dispatchBffRequest(request, env) {
417
539
  }
418
540
  export default {
419
541
  async fetch (request, env, ctx) {
420
- const corsPreflightResponse = createCorsPreflightResponse(request);
421
- if (corsPreflightResponse) return corsPreflightResponse;
542
+ const corsPreflightResponse = await createCorsPreflightResponse(request, env);
543
+ if (corsPreflightResponse) return finalizeResponseForRequest(corsPreflightResponse, request);
422
544
  const assetResponse = await fetchAsset(request, env);
423
- if (assetResponse) return assetResponse;
545
+ if (assetResponse) return finalizeResponseForRequest(assetResponse, request);
424
546
  const bffResponse = await dispatchBffRequest(request, env);
425
- if (bffResponse) return withCorsHeaders(bffResponse);
547
+ if (bffResponse) return finalizeResponseForRequest(withAppCorsHeaders(bffResponse, request), request);
426
548
  const route = findRoute(request);
427
549
  const { pathname } = new URL(request.url);
428
- if (isAssetLikePathname(pathname) && !routeMatchesExactly(route, pathname)) return withCorsHeaders(new Response('Not found', {
550
+ if (isAssetLikePathname(pathname) && !routeMatchesExactly(route, pathname)) return finalizeResponseForRequest(withAppCorsHeaders(new Response('Not found', {
429
551
  status: 404
430
- }));
431
- if (route?.worker) return withCorsHeaders(await dispatchRouteWorker(route, request, env, ctx));
552
+ }), request), request);
553
+ if (route?.worker) {
554
+ const renderableRequest = createRenderableRequest(request);
555
+ return finalizeResponseForRequest(withAppCorsHeaders(await dispatchRouteWorker(route, renderableRequest, env, ctx), request), request);
556
+ }
432
557
  const htmlResponse = await fetchRouteHtml(route, request, env);
433
- if (htmlResponse) return htmlResponse;
434
- return withCorsHeaders(new Response('Not found', {
558
+ if (htmlResponse) return finalizeResponseForRequest(htmlResponse, request);
559
+ return finalizeResponseForRequest(withAppCorsHeaders(new Response('Not found', {
435
560
  status: 404
436
- }));
561
+ }), request), request);
437
562
  }
438
563
  };
@@ -1,10 +1,12 @@
1
1
  import "node:module";
2
2
  import { createRequire } from "node:module";
3
- import { ROUTE_SPEC_FILE, SERVER_DIR, fs, getMeta } from "@modern-js/utils";
3
+ import { pathToFileURL } from "node:url";
4
+ import { ROUTE_SPEC_FILE, SERVER_DIR, dynamicImport, fs, getMeta } from "@modern-js/utils";
4
5
  import path from "path";
5
6
  import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
6
7
  import { dirname as __rspack_dirname } from "node:path";
7
8
  var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
9
+ var utils_filename = __rspack_fileURLToPath(import.meta.url);
8
10
  const normalizePath = (filePath)=>filePath.replace(/\\/g, '/');
9
11
  const getProjectUsage = (appDirectory, distDirectory, metaName)=>{
10
12
  const routeJSON = path.join(distDirectory, ROUTE_SPEC_FILE);
@@ -29,43 +31,17 @@ const getProjectUsage = (appDirectory, distDirectory, metaName)=>{
29
31
  };
30
32
  const getTemplatePath = (file)=>path.join(utils_dirname, '../platforms/templates', file);
31
33
  const readTemplate = async (file)=>(await fs.readFile(getTemplatePath(file))).toString();
32
- const localRequire = createRequire(path.join(utils_dirname, 'package.json'));
33
- const findNearestPackageJson = (resolvedEntry)=>{
34
- let currentDir = path.dirname(resolvedEntry);
35
- while(currentDir !== path.dirname(currentDir)){
36
- const manifestPath = path.join(currentDir, 'package.json');
37
- if (fs.existsSync(manifestPath)) return manifestPath;
38
- currentDir = path.dirname(currentDir);
39
- }
40
- };
41
- const splitPackageSpecifier = (entry)=>{
42
- const segments = entry.split('/');
43
- if (entry.startsWith('@')) {
44
- const [scope, name, ...rest] = segments;
45
- return {
46
- packageName: `${scope}/${name}`,
47
- exportKey: rest.length > 0 ? `./${rest.join('/')}` : '.'
48
- };
49
- }
50
- const [name, ...rest] = segments;
51
- return {
52
- packageName: name,
53
- exportKey: rest.length > 0 ? `./${rest.join('/')}` : '.'
54
- };
55
- };
56
34
  const resolveESMDependency = async (entry)=>{
35
+ const conditions = new Set([
36
+ 'node',
37
+ 'import',
38
+ 'module',
39
+ 'default'
40
+ ]);
57
41
  try {
58
- const { packageName, exportKey } = splitPackageSpecifier(entry);
59
- const resolvedEntry = localRequire.resolve(entry);
60
- const packageJsonPath = findNearestPackageJson(localRequire.resolve(packageName));
61
- if (!packageJsonPath) return normalizePath(resolvedEntry);
62
- const packageDir = path.dirname(packageJsonPath);
63
- const packageJson = fs.readJSONSync(packageJsonPath);
64
- const exportConfig = packageJson.exports?.[exportKey];
65
- if ('string' == typeof exportConfig) return normalizePath(path.join(packageDir, exportConfig));
66
- const esmExportPath = exportConfig?.node?.import || exportConfig?.import || exportConfig?.default;
67
- if ('string' == typeof esmExportPath) return normalizePath(path.join(packageDir, esmExportPath));
68
- return normalizePath(resolvedEntry);
42
+ const resolverPath = pathToFileURL(createRequire(utils_filename).resolve('import-meta-resolve')).href;
43
+ const { moduleResolve } = await dynamicImport(resolverPath);
44
+ return normalizePath(moduleResolve(entry, pathToFileURL(`${utils_dirname}/`), conditions, false).pathname.replace(/^\/(\w):/, '$1:'));
69
45
  } catch (err) {}
70
46
  };
71
47
  export { getProjectUsage, getTemplatePath, normalizePath, readTemplate, resolveESMDependency };
@@ -1,6 +1,6 @@
1
1
  import "node:module";
2
2
  import { ensureAbsolutePath, getPort, isDev, isDevCommand } from "@modern-js/utils";
3
- import { createDefaultConfig } from "../../config/index.mjs";
3
+ import { createDefaultConfig, isLazyCompilationSafeByDefault } from "../../config/index.mjs";
4
4
  const initialize = ()=>({
5
5
  name: '@modern-js/plugin-initialize',
6
6
  post: [
@@ -12,7 +12,16 @@ const initialize = ()=>({
12
12
  setup (api) {
13
13
  api.config(()=>{
14
14
  const appContext = api.getAppContext();
15
- return createDefaultConfig(appContext);
15
+ const userConfig = api.getConfig();
16
+ const defaultConfig = createDefaultConfig(appContext);
17
+ if (userConfig.dev?.lazyCompilation === void 0 && isLazyCompilationSafeByDefault(userConfig)) defaultConfig.dev = {
18
+ ...defaultConfig.dev,
19
+ lazyCompilation: {
20
+ imports: true,
21
+ entries: false
22
+ }
23
+ };
24
+ return defaultConfig;
16
25
  });
17
26
  api.modifyResolvedConfig(async (resolved)=>{
18
27
  let appContext = api.getAppContext();
@@ -1,5 +1,79 @@
1
1
  import "node:module";
2
- import { createAppBaselineConfig, withAppBaseline } from "./baseline.mjs";
3
- const createPresetUltramodernConfig = (options = {})=>createAppBaselineConfig(options);
4
- const presetUltramodern = (config, options = {})=>withAppBaseline(config, options);
2
+ import node_fs from "node:fs";
3
+ import node_path from "node:path";
4
+ import { mergeConfig } from "@modern-js/plugin/cli";
5
+ const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
6
+ const DEFAULT_VICTORIA_METRICS_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
7
+ const resolveReactRouterPackageDir = (appDirectory)=>{
8
+ const resolveNodeModulePackageJson = (packageName, fromDirectory)=>{
9
+ let currentDirectory = node_path.resolve(fromDirectory);
10
+ while(true){
11
+ const packageJson = node_path.join(currentDirectory, 'node_modules', packageName, 'package.json');
12
+ if (node_fs.existsSync(packageJson)) return node_fs.realpathSync(packageJson);
13
+ const parentDirectory = node_path.dirname(currentDirectory);
14
+ if (parentDirectory === currentDirectory) return;
15
+ currentDirectory = parentDirectory;
16
+ }
17
+ };
18
+ const reactRouterPackageJson = resolveNodeModulePackageJson('react-router', appDirectory);
19
+ if (reactRouterPackageJson) return node_path.dirname(reactRouterPackageJson);
20
+ const reactRouterDomPackageJson = resolveNodeModulePackageJson('react-router-dom', appDirectory);
21
+ if (!reactRouterDomPackageJson) return;
22
+ const nestedReactRouterPackageJson = resolveNodeModulePackageJson('react-router', node_path.dirname(reactRouterDomPackageJson));
23
+ if (nestedReactRouterPackageJson) return node_path.dirname(nestedReactRouterPackageJson);
24
+ };
25
+ const setReactRouterBridgeSafeAliases = (chain, { isProd })=>{
26
+ const chainContext = chain.get('context');
27
+ const appDirectory = 'string' == typeof chainContext && chainContext.length > 0 ? chainContext : process.cwd();
28
+ const reactRouterPackageDir = resolveReactRouterPackageDir(appDirectory);
29
+ if (!reactRouterPackageDir) return;
30
+ const productionEntry = node_path.join(reactRouterPackageDir, 'dist/production/index.mjs');
31
+ const developmentEntry = node_path.join(reactRouterPackageDir, 'dist/development/index.mjs');
32
+ chain.resolve.alias.set('react-router$', isProd ? productionEntry : developmentEntry);
33
+ chain.resolve.alias.set('react-router/dist/production/index.js', productionEntry);
34
+ chain.resolve.alias.set('react-router/dist/development/index.js', developmentEntry);
35
+ };
36
+ const createPresetUltramodernConfig = (options = {})=>{
37
+ const { appId = 'app', enableBffRequestId = true, enableTelemetry = true, enableTelemetryExporters, otlpEndpoint = process.env.MODERN_TELEMETRY_OTLP_ENDPOINT, victoriaMetricsEndpoint = process.env.MODERN_TELEMETRY_VICTORIA_ENDPOINT, telemetryFailLoudStartup = true, enableModuleFederationSSR = true } = options;
38
+ const server = {};
39
+ if (enableTelemetry) {
40
+ server.telemetry = {
41
+ enabled: true,
42
+ failLoudStartup: telemetryFailLoudStartup
43
+ };
44
+ if (false !== enableTelemetryExporters) {
45
+ const exporters = {};
46
+ if (true === enableTelemetryExporters || otlpEndpoint) exporters.otlp = {
47
+ enabled: true,
48
+ endpoint: otlpEndpoint || DEFAULT_OTLP_ENDPOINT
49
+ };
50
+ if (true === enableTelemetryExporters || victoriaMetricsEndpoint) exporters.victoriaMetrics = {
51
+ enabled: true,
52
+ endpoint: victoriaMetricsEndpoint || DEFAULT_VICTORIA_METRICS_ENDPOINT
53
+ };
54
+ if (Object.keys(exporters).length > 0) server.telemetry.exporters = exporters;
55
+ }
56
+ }
57
+ if (enableModuleFederationSSR) server.ssr = {
58
+ mode: 'stream',
59
+ moduleFederationAppSSR: true
60
+ };
61
+ const presetConfig = {
62
+ output: {
63
+ precompress: true
64
+ },
65
+ server,
66
+ tools: {
67
+ bundlerChain: setReactRouterBridgeSafeAliases
68
+ }
69
+ };
70
+ if (enableBffRequestId) presetConfig.bff = {
71
+ requestId: appId
72
+ };
73
+ return presetConfig;
74
+ };
75
+ const presetUltramodern = (config, options = {})=>mergeConfig([
76
+ createPresetUltramodernConfig(options),
77
+ config
78
+ ]);
5
79
  export { createPresetUltramodernConfig, presetUltramodern };
@@ -1,19 +1,12 @@
1
1
  import "node:module";
2
2
  import { parseRspackConfig } from "@modern-js/builder";
3
+ import { createConfigOptions } from "@modern-js/plugin/cli";
3
4
  import { INTERNAL_RUNTIME_PLUGINS } from "@modern-js/utils";
4
5
  import { builderPluginAdapterBasic, builderPluginAdapterHooks } from "./builder/shared/builderPlugins/index.mjs";
5
6
  import { DEFAULT_CONFIG_FILE } from "./constants.mjs";
6
7
  import { getConfigFile } from "./utils/getConfigFile.mjs";
7
8
  import { loadInternalPlugins } from "./utils/loadPlugins.mjs";
8
- import { __webpack_require__ } from "./rslib-runtime.mjs";
9
- import * as __rspack_external__modern_js_plugin_cli_caa09fa2 from "@modern-js/plugin/cli";
10
- __webpack_require__.add({
11
- "@modern-js/plugin/cli?8936" (module) {
12
- module.exports = __rspack_external__modern_js_plugin_cli_caa09fa2;
13
- }
14
- });
15
9
  const MODERN_META_NAME = 'modern-js';
16
- const { createConfigOptions: createConfigOptions } = __webpack_require__("@modern-js/plugin/cli?8936");
17
10
  async function resolveModernRsbuildConfig(options) {
18
11
  const { cwd = process.cwd(), metaName = MODERN_META_NAME } = options;
19
12
  const configFile = options.configPath || getConfigFile(void 0, cwd);
@@ -0,0 +1 @@
1
+ import "node:module";
@@ -0,0 +1 @@
1
+ import "node:module";