@bleedingdev/modern-js-server-runtime-extensions 3.11.3-ultramodern.10 → 3.11.3-ultramodern.12

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 (51) hide show
  1. package/README.md +10 -0
  2. package/dist/cjs/env.js +5 -1
  3. package/dist/cjs/module-federation-css/plugin.js +7 -3
  4. package/dist/cjs/render-resources/channels.js +55 -0
  5. package/dist/cjs/render-resources/index.js +47 -0
  6. package/dist/cjs/render-resources/plugin.js +82 -0
  7. package/dist/cjs/serverPlugin.js +2 -0
  8. package/dist/cjs/static-serving/immutableAssetStat.js +64 -0
  9. package/dist/cjs/static-serving/plugin.js +2 -1
  10. package/dist/cjs/static-serving/responders.js +13 -8
  11. package/dist/cjs/static-serving/staticPrecompressed.js +6 -3
  12. package/dist/esm/env.mjs +5 -1
  13. package/dist/esm/module-federation-css/plugin.mjs +7 -3
  14. package/dist/esm/serverPlugin.mjs +2 -0
  15. package/dist/esm-node/env.mjs +5 -1
  16. package/dist/esm-node/module-federation-css/plugin.mjs +7 -3
  17. package/dist/esm-node/render-resources/channels.mjs +5 -0
  18. package/dist/esm-node/render-resources/index.mjs +3 -0
  19. package/dist/esm-node/render-resources/plugin.mjs +43 -0
  20. package/dist/esm-node/serverPlugin.mjs +2 -0
  21. package/dist/esm-node/static-serving/immutableAssetStat.mjs +24 -0
  22. package/dist/esm-node/static-serving/plugin.mjs +2 -1
  23. package/dist/esm-node/static-serving/responders.mjs +13 -8
  24. package/dist/esm-node/static-serving/staticPrecompressed.mjs +6 -3
  25. package/dist/types/env.d.ts +15 -0
  26. package/dist/types/module-federation-css/plugin.d.ts +3 -2
  27. package/dist/types/render-resources/channels.d.ts +27 -0
  28. package/dist/types/render-resources/index.d.ts +2 -0
  29. package/dist/types/render-resources/plugin.d.ts +3 -0
  30. package/dist/types/static-serving/immutableAssetStat.d.ts +8 -0
  31. package/dist/types/static-serving/responders.d.ts +7 -1
  32. package/dist/types/static-serving/staticPrecompressed.d.ts +1 -1
  33. package/dist/types-esm/env.d.mts +15 -0
  34. package/dist/types-esm/module-federation-css/plugin.d.mts +3 -2
  35. package/dist/types-esm/render-resources/channels.d.mts +27 -0
  36. package/dist/types-esm/render-resources/index.d.mts +2 -0
  37. package/dist/types-esm/render-resources/plugin.d.mts +3 -0
  38. package/dist/types-esm/static-serving/immutableAssetStat.d.mts +8 -0
  39. package/dist/types-esm/static-serving/responders.d.mts +7 -1
  40. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +1 -1
  41. package/package.json +27 -10
  42. package/src/env.ts +25 -0
  43. package/src/module-federation-css/plugin.ts +21 -5
  44. package/src/render-resources/channels.ts +37 -0
  45. package/src/render-resources/index.ts +7 -0
  46. package/src/render-resources/plugin.ts +56 -0
  47. package/src/serverPlugin.ts +2 -0
  48. package/src/static-serving/immutableAssetStat.ts +41 -0
  49. package/src/static-serving/plugin.ts +4 -1
  50. package/src/static-serving/responders.ts +30 -6
  51. package/src/static-serving/staticPrecompressed.ts +5 -4
@@ -1,4 +1,5 @@
1
1
  import "node:module";
2
+ import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
2
3
  import { createStaticExtensionResponders } from "./responders.mjs";
3
4
  function injectStaticServingPlugin() {
4
5
  return {
@@ -8,7 +9,7 @@ function injectStaticServingPlugin() {
8
9
  ],
9
10
  setup (api) {
10
11
  api.updateServerContext({
11
- staticAssetResponders: createStaticExtensionResponders()
12
+ staticAssetResponders: createStaticExtensionResponders(parseServerRuntimeExtensionsEnv())
12
13
  });
13
14
  }
14
15
  };
@@ -1,10 +1,11 @@
1
1
  import "node:module";
2
2
  import node_path from "node:path";
3
3
  import { serveStaticAsset } from "@modern-js/server-core/node";
4
+ import { createImmutableAssetStat } from "./immutableAssetStat.mjs";
4
5
  import { applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath } from "./staticModuleFederation.mjs";
5
6
  import { applyPreCompressedAssetHeaders, resolvePreCompressedAsset } from "./staticPrecompressed.mjs";
6
- async function respondPrecompressedAsset(context, asset, serve) {
7
- const selected = await resolvePreCompressedAsset(context, asset.filename);
7
+ async function respondPrecompressedAsset(context, asset, serve, precompressedAssets) {
8
+ const selected = await resolvePreCompressedAsset(context, asset.filename, precompressedAssets);
8
9
  const response = selected.acceptable ? await serve({
9
10
  filename: selected.selected?.filepath,
10
11
  contentLength: true
@@ -17,7 +18,9 @@ async function respondPrecompressedAsset(context, asset, serve) {
17
18
  if ('.cjs' === node_path.extname(asset.filename).toLowerCase()) context.res.headers.set('Content-Type', "text/javascript; charset=UTF-8");
18
19
  return context.res;
19
20
  }
20
- function createStaticExtensionResponders() {
21
+ function createStaticExtensionResponders({ immutableAssets, precompressedAssets }) {
22
+ const stat = immutableAssets ? createImmutableAssetStat() : void 0;
23
+ const respondPrecompressed = (context, asset, serve)=>respondPrecompressedAsset(context, asset, serve, precompressedAssets);
21
24
  const caches = new Map();
22
25
  const getAssets = (root)=>{
23
26
  let cache = caches.get(root);
@@ -34,7 +37,7 @@ function createStaticExtensionResponders() {
34
37
  const current = cache;
35
38
  const pending = getModuleFederationAssetList(root).then((assets)=>{
36
39
  current.assets = assets;
37
- current.expires = Date.now() + 1000;
40
+ current.expires = immutableAssets ? 1 / 0 : Date.now() + 1000;
38
41
  return assets;
39
42
  }).finally(()=>{
40
43
  current.pending = null;
@@ -45,7 +48,7 @@ function createStaticExtensionResponders() {
45
48
  async function serveFederated(context, asset, serve, requestPath, pathPrefix, remoteEntry) {
46
49
  applyModuleFederationAssetHeaders(context);
47
50
  const patchManifest = isModuleFederationManifestRequest(requestPath) && !isBackendModuleFederationManifestRequest(requestPath);
48
- if (!patchManifest && !remoteEntry) return respondPrecompressedAsset(context, asset, serve);
51
+ if (!patchManifest && !remoteEntry) return respondPrecompressed(context, asset, serve);
49
52
  const response = await serve({
50
53
  contentLength: true,
51
54
  revalidate: false
@@ -80,7 +83,7 @@ function createStaticExtensionResponders() {
80
83
  kind: 'static',
81
84
  root: publicRoot,
82
85
  realpath: true
83
- }, (asset, serve)=>respondPrecompressedAsset(context, asset, serve));
86
+ }, (asset, serve)=>respondPrecompressed(context, asset, serve));
84
87
  if (response && 'HEAD' === context.req.raw.method.toUpperCase()) return new Response(null, {
85
88
  status: response.status,
86
89
  headers: response.headers
@@ -88,12 +91,13 @@ function createStaticExtensionResponders() {
88
91
  return response;
89
92
  }
90
93
  return {
94
+ stat,
91
95
  async respondAsset (context, asset, serve, { root, pathPrefix }) {
92
96
  const requestPath = getModuleFederationRequestPath(context.req.path, pathPrefix);
93
97
  if (requestPath.includes('..')) return null;
94
98
  const assets = await getAssets(root);
95
99
  if ('static' === asset.kind && assets.assets.has(requestPath)) return serveFederated(context, asset, serve, requestPath, pathPrefix, assets.remoteEntries.has(requestPath));
96
- return respondPrecompressedAsset(context, asset, serve);
100
+ return respondPrecompressed(context, asset, serve);
97
101
  },
98
102
  async respondPublicFallback (context, respondPublic, { root, pathPrefix }) {
99
103
  const requestPath = getModuleFederationRequestPath(context.req.path, pathPrefix);
@@ -103,7 +107,8 @@ function createStaticExtensionResponders() {
103
107
  const response = await serveStaticAsset(context, {
104
108
  filename: node_path.join(root, requestPath),
105
109
  kind: 'static',
106
- root
110
+ root,
111
+ stat
107
112
  }, (asset, serve)=>serveFederated(context, asset, serve, requestPath, pathPrefix, assets.remoteEntries.has(requestPath)));
108
113
  if (null !== response) return response;
109
114
  }
@@ -67,13 +67,16 @@ const appendVaryHeader = (c, value)=>{
67
67
  const values = current.split(',').map((item)=>item.trim().toLowerCase()).filter(Boolean);
68
68
  if (!values.includes(value.toLowerCase())) c.header('Vary', `${current}, ${value}`);
69
69
  };
70
- const resolvePreCompressedAsset = async (c, filepath)=>{
70
+ const resolvePreCompressedAsset = async (c, filepath, probeVariants)=>{
71
71
  const brPath = `${filepath}${PRE_COMPRESSED_ASSET_EXTENSIONS.br}`;
72
72
  const gzipPath = `${filepath}${PRE_COMPRESSED_ASSET_EXTENSIONS.gzip}`;
73
- const [hasBr, hasGzip] = await Promise.all([
73
+ const [hasBr, hasGzip] = probeVariants ? await Promise.all([
74
74
  fs.pathExists(brPath),
75
75
  fs.pathExists(gzipPath)
76
- ]);
76
+ ]) : [
77
+ false,
78
+ false
79
+ ];
77
80
  const hasVariant = hasBr || hasGzip;
78
81
  const acceptedRepresentations = getAcceptedRepresentations(c.req.header('accept-encoding'));
79
82
  for (const encoding of acceptedRepresentations){
@@ -30,6 +30,21 @@ export interface ServerRuntimeExtensionsEnv {
30
30
  * (absolute, or relative to the app directory). Undefined when unset.
31
31
  */
32
32
  contractGatesFile?: string;
33
+ /**
34
+ * `MODERN_SERVER_RENDER_RESOURCES` — `lazy` defers production server bundle
35
+ * imports to the first render request; anything else keeps eager warmup.
36
+ */
37
+ renderResources: 'eager' | 'lazy';
38
+ /**
39
+ * Production with `MODERN_SERVER_IMMUTABLE_ASSETS=true`: release files never
40
+ * change while serving, so found files and the federation inventory are kept.
41
+ */
42
+ immutableAssets: boolean;
43
+ /**
44
+ * False only in production with `MODERN_SERVER_PRECOMPRESSED_ASSETS=false`:
45
+ * no `.br`/`.gz` variants are probed or served.
46
+ */
47
+ precompressedAssets: boolean;
33
48
  }
34
49
  /**
35
50
  * Parse the statically-known environment variables consumed by this package
@@ -16,7 +16,8 @@ export type ModuleFederationCssPluginOptions = {
16
16
  * being pinned at boot: remote manifests change on every remote redeploy, and
17
17
  * fetch failures must not pin an empty/partial list for the process lifetime.
18
18
  *
19
- * Existing plugin ordering places this after the native resource plugin
20
- * (which sets `serverManifest`) and before the native RSC manifest plugin.
19
+ * Existing plugin ordering places this after the native resource plugin.
20
+ * Lazy loading keeps enrichment in the page-only resource prefix, before
21
+ * configured render middleware.
21
22
  */
22
23
  export declare const injectModuleFederationCssPlugin: (options?: ModuleFederationCssPluginOptions) => ServerPlugin;
@@ -0,0 +1,27 @@
1
+ import diagnosticsChannel from 'node:diagnostics_channel';
2
+ import type { ServerContext } from '@modern-js/server-core';
3
+ /** One server bundle import, published after it settles. */
4
+ export interface RenderBundleLoadEvent {
5
+ /** The serving application's output directory, when configured. */
6
+ readonly distDirectory: ServerContext['distDirectory'];
7
+ readonly filepath: string;
8
+ readonly durationMs: number;
9
+ readonly outcome: 'loaded' | 'failed';
10
+ /** The request path that triggered the import, or `<startup>` for warmup. */
11
+ readonly triggerPath: string;
12
+ }
13
+ /** One request through the server middlewares, traced from start to settle. */
14
+ export interface ServerRequestTrace {
15
+ /** The serving application's output directory, when configured. */
16
+ readonly distDirectory: ServerContext['distDirectory'];
17
+ /** The request path, without its query. */
18
+ readonly path: string;
19
+ }
20
+ /**
21
+ * Process-wide, so every server in a process publishes here regardless of
22
+ * which module format loaded this package. Node reports a subscriber's
23
+ * exception as an uncaught exception.
24
+ */
25
+ export declare const renderBundleLoadChannel: diagnosticsChannel.Channel<RenderBundleLoadEvent, RenderBundleLoadEvent>;
26
+ /** Publishes `start` when a request enters and `asyncEnd` when it settles. */
27
+ export declare const serverRequestChannel: diagnosticsChannel.TracingChannel<ServerRequestTrace, ServerRequestTrace>;
@@ -0,0 +1,2 @@
1
+ export { type RenderBundleLoadEvent, renderBundleLoadChannel, type ServerRequestTrace, serverRequestChannel, } from './channels.js';
2
+ export { injectRenderResourcesPlugin } from './plugin.js';
@@ -0,0 +1,3 @@
1
+ import type { ServerPlugin } from '@modern-js/server-core';
2
+ export declare function injectRenderResourcesPlugin(): ServerPlugin;
3
+ export default injectRenderResourcesPlugin;
@@ -0,0 +1,8 @@
1
+ import type { StaticAssetStat } from '@modern-js/server-core/node';
2
+ export declare const IMMUTABLE_ASSET_STAT_LIMIT = 8192;
3
+ /**
4
+ * File metadata for immutable releases. Only found regular files are kept, so
5
+ * a missing path is looked up again by the next request. The oldest entry is
6
+ * dropped once the limit is reached.
7
+ */
8
+ export declare function createImmutableAssetStat(): StaticAssetStat;
@@ -1,2 +1,8 @@
1
1
  import { type ServerStaticPluginOptions } from '@modern-js/server-core/node';
2
- export declare function createStaticExtensionResponders(): ServerStaticPluginOptions;
2
+ export type StaticExtensionPolicy = {
3
+ /** Release files never change while serving: keep found files and the federation inventory. */
4
+ immutableAssets: boolean;
5
+ /** Probe and serve `.br`/`.gz` variants. */
6
+ precompressedAssets: boolean;
7
+ };
8
+ export declare function createStaticExtensionResponders({ immutableAssets, precompressedAssets, }: StaticExtensionPolicy): ServerStaticPluginOptions;
@@ -8,6 +8,6 @@ type ResolvePreCompressedAssetResult = {
8
8
  hasVariant: boolean;
9
9
  acceptable: boolean;
10
10
  };
11
- export declare const resolvePreCompressedAsset: (c: Parameters<Middleware>[0], filepath: string) => Promise<ResolvePreCompressedAssetResult>;
11
+ export declare const resolvePreCompressedAsset: (c: Parameters<Middleware>[0], filepath: string, probeVariants: boolean) => Promise<ResolvePreCompressedAssetResult>;
12
12
  export declare const applyPreCompressedAssetHeaders: (c: Parameters<Middleware>[0], preCompressedAsset: ResolvePreCompressedAssetResult) => void;
13
13
  export {};
@@ -30,6 +30,21 @@ export interface ServerRuntimeExtensionsEnv {
30
30
  * (absolute, or relative to the app directory). Undefined when unset.
31
31
  */
32
32
  contractGatesFile?: string;
33
+ /**
34
+ * `MODERN_SERVER_RENDER_RESOURCES` — `lazy` defers production server bundle
35
+ * imports to the first render request; anything else keeps eager warmup.
36
+ */
37
+ renderResources: 'eager' | 'lazy';
38
+ /**
39
+ * Production with `MODERN_SERVER_IMMUTABLE_ASSETS=true`: release files never
40
+ * change while serving, so found files and the federation inventory are kept.
41
+ */
42
+ immutableAssets: boolean;
43
+ /**
44
+ * False only in production with `MODERN_SERVER_PRECOMPRESSED_ASSETS=false`:
45
+ * no `.br`/`.gz` variants are probed or served.
46
+ */
47
+ precompressedAssets: boolean;
33
48
  }
34
49
  /**
35
50
  * Parse the statically-known environment variables consumed by this package
@@ -16,7 +16,8 @@ export type ModuleFederationCssPluginOptions = {
16
16
  * being pinned at boot: remote manifests change on every remote redeploy, and
17
17
  * fetch failures must not pin an empty/partial list for the process lifetime.
18
18
  *
19
- * Existing plugin ordering places this after the native resource plugin
20
- * (which sets `serverManifest`) and before the native RSC manifest plugin.
19
+ * Existing plugin ordering places this after the native resource plugin.
20
+ * Lazy loading keeps enrichment in the page-only resource prefix, before
21
+ * configured render middleware.
21
22
  */
22
23
  export declare const injectModuleFederationCssPlugin: (options?: ModuleFederationCssPluginOptions) => ServerPlugin;
@@ -0,0 +1,27 @@
1
+ import diagnosticsChannel from 'node:diagnostics_channel';
2
+ import type { ServerContext } from '@modern-js/server-core';
3
+ /** One server bundle import, published after it settles. */
4
+ export interface RenderBundleLoadEvent {
5
+ /** The serving application's output directory, when configured. */
6
+ readonly distDirectory: ServerContext['distDirectory'];
7
+ readonly filepath: string;
8
+ readonly durationMs: number;
9
+ readonly outcome: 'loaded' | 'failed';
10
+ /** The request path that triggered the import, or `<startup>` for warmup. */
11
+ readonly triggerPath: string;
12
+ }
13
+ /** One request through the server middlewares, traced from start to settle. */
14
+ export interface ServerRequestTrace {
15
+ /** The serving application's output directory, when configured. */
16
+ readonly distDirectory: ServerContext['distDirectory'];
17
+ /** The request path, without its query. */
18
+ readonly path: string;
19
+ }
20
+ /**
21
+ * Process-wide, so every server in a process publishes here regardless of
22
+ * which module format loaded this package. Node reports a subscriber's
23
+ * exception as an uncaught exception.
24
+ */
25
+ export declare const renderBundleLoadChannel: diagnosticsChannel.Channel<RenderBundleLoadEvent, RenderBundleLoadEvent>;
26
+ /** Publishes `start` when a request enters and `asyncEnd` when it settles. */
27
+ export declare const serverRequestChannel: diagnosticsChannel.TracingChannel<ServerRequestTrace, ServerRequestTrace>;
@@ -0,0 +1,2 @@
1
+ export { type RenderBundleLoadEvent, renderBundleLoadChannel, type ServerRequestTrace, serverRequestChannel, } from './channels.mjs';
2
+ export { injectRenderResourcesPlugin } from './plugin.mjs';
@@ -0,0 +1,3 @@
1
+ import type { ServerPlugin } from '@modern-js/server-core';
2
+ export declare function injectRenderResourcesPlugin(): ServerPlugin;
3
+ export default injectRenderResourcesPlugin;
@@ -0,0 +1,8 @@
1
+ import type { StaticAssetStat } from '@modern-js/server-core/node';
2
+ export declare const IMMUTABLE_ASSET_STAT_LIMIT = 8192;
3
+ /**
4
+ * File metadata for immutable releases. Only found regular files are kept, so
5
+ * a missing path is looked up again by the next request. The oldest entry is
6
+ * dropped once the limit is reached.
7
+ */
8
+ export declare function createImmutableAssetStat(): StaticAssetStat;
@@ -1,2 +1,8 @@
1
1
  import { type ServerStaticPluginOptions } from '@modern-js/server-core/node';
2
- export declare function createStaticExtensionResponders(): ServerStaticPluginOptions;
2
+ export type StaticExtensionPolicy = {
3
+ /** Release files never change while serving: keep found files and the federation inventory. */
4
+ immutableAssets: boolean;
5
+ /** Probe and serve `.br`/`.gz` variants. */
6
+ precompressedAssets: boolean;
7
+ };
8
+ export declare function createStaticExtensionResponders({ immutableAssets, precompressedAssets, }: StaticExtensionPolicy): ServerStaticPluginOptions;
@@ -8,6 +8,6 @@ type ResolvePreCompressedAssetResult = {
8
8
  hasVariant: boolean;
9
9
  acceptable: boolean;
10
10
  };
11
- export declare const resolvePreCompressedAsset: (c: Parameters<Middleware>[0], filepath: string) => Promise<ResolvePreCompressedAssetResult>;
11
+ export declare const resolvePreCompressedAsset: (c: Parameters<Middleware>[0], filepath: string, probeVariants: boolean) => Promise<ResolvePreCompressedAssetResult>;
12
12
  export declare const applyPreCompressedAssetHeaders: (c: Parameters<Middleware>[0], preCompressedAsset: ResolvePreCompressedAssetResult) => void;
13
13
  export {};
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "modern",
18
18
  "modern.js"
19
19
  ],
20
- "version": "3.11.3-ultramodern.10",
20
+ "version": "3.11.3-ultramodern.12",
21
21
  "types": "./dist/types/index.d.ts",
22
22
  "main": "./dist/cjs/index.js",
23
23
  "exports": {
@@ -116,6 +116,19 @@
116
116
  },
117
117
  "types": "./dist/types/static-serving/plugin.d.ts"
118
118
  },
119
+ "./render-resources": {
120
+ "node": {
121
+ "import": {
122
+ "types": "./dist/types-esm/render-resources/index.d.mts",
123
+ "default": "./dist/esm-node/render-resources/index.mjs"
124
+ },
125
+ "require": {
126
+ "types": "./dist/types/render-resources/index.d.ts",
127
+ "default": "./dist/cjs/render-resources/index.js"
128
+ }
129
+ },
130
+ "types": "./dist/types/render-resources/index.d.ts"
131
+ },
119
132
  "./server-plugin": {
120
133
  "node": {
121
134
  "import": {
@@ -197,6 +210,10 @@
197
210
  "./dist/types/static-serving/plugin.d.ts",
198
211
  "./src/static-serving/plugin.ts"
199
212
  ],
213
+ "render-resources": [
214
+ "./dist/types/render-resources/index.d.ts",
215
+ "./src/render-resources/index.ts"
216
+ ],
200
217
  "server-plugin": [
201
218
  "./dist/types/serverPlugin.d.ts",
202
219
  "./src/serverPlugin.ts"
@@ -219,19 +236,19 @@
219
236
  "node": ">=26.13.1"
220
237
  },
221
238
  "dependencies": {
222
- "@modern-js/create-request": "npm:@bleedingdev/modern-js-create-request@3.11.3-ultramodern.10",
223
- "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.11.3-ultramodern.10",
224
- "@modern-js/plugin-data-loader": "npm:@bleedingdev/modern-js-plugin-data-loader@3.11.3-ultramodern.10",
225
- "@modern-js/runtime-extensions": "npm:@bleedingdev/modern-js-runtime-extensions@3.11.3-ultramodern.10",
226
- "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.11.3-ultramodern.10",
227
- "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.11.3-ultramodern.10",
228
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.11.3-ultramodern.10",
239
+ "@modern-js/create-request": "npm:@bleedingdev/modern-js-create-request@3.11.3-ultramodern.12",
240
+ "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.11.3-ultramodern.12",
241
+ "@modern-js/plugin-data-loader": "npm:@bleedingdev/modern-js-plugin-data-loader@3.11.3-ultramodern.12",
242
+ "@modern-js/runtime-extensions": "npm:@bleedingdev/modern-js-runtime-extensions@3.11.3-ultramodern.12",
243
+ "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.11.3-ultramodern.12",
244
+ "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.11.3-ultramodern.12",
245
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.11.3-ultramodern.12",
229
246
  "@swc/helpers": "^0.5.24",
230
247
  "reflect-metadata": "^0.2.2"
231
248
  },
232
249
  "devDependencies": {
233
- "@modern-js/prod-server": "npm:@bleedingdev/modern-js-prod-server@3.11.3-ultramodern.10",
234
- "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.11.3-ultramodern.10",
250
+ "@modern-js/prod-server": "npm:@bleedingdev/modern-js-prod-server@3.11.3-ultramodern.12",
251
+ "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.11.3-ultramodern.12",
235
252
  "@rslib/core": "1.0.7",
236
253
  "@scripts/rstest-config": "2.66.7",
237
254
  "@types/node": "^26.6.6",
package/src/env.ts CHANGED
@@ -32,6 +32,21 @@ export interface ServerRuntimeExtensionsEnv {
32
32
  * (absolute, or relative to the app directory). Undefined when unset.
33
33
  */
34
34
  contractGatesFile?: string;
35
+ /**
36
+ * `MODERN_SERVER_RENDER_RESOURCES` — `lazy` defers production server bundle
37
+ * imports to the first render request; anything else keeps eager warmup.
38
+ */
39
+ renderResources: 'eager' | 'lazy';
40
+ /**
41
+ * Production with `MODERN_SERVER_IMMUTABLE_ASSETS=true`: release files never
42
+ * change while serving, so found files and the federation inventory are kept.
43
+ */
44
+ immutableAssets: boolean;
45
+ /**
46
+ * False only in production with `MODERN_SERVER_PRECOMPRESSED_ASSETS=false`:
47
+ * no `.br`/`.gz` variants are probed or served.
48
+ */
49
+ precompressedAssets: boolean;
35
50
  }
36
51
 
37
52
  const readString = (value: string | undefined): string | undefined => {
@@ -53,11 +68,21 @@ export const parseServerRuntimeExtensionsEnv = (
53
68
  ): ServerRuntimeExtensionsEnv => {
54
69
  const modernEnv = readString(env.MODERN_ENV);
55
70
  const nodeEnv = readString(env.NODE_ENV);
71
+ const production = nodeEnv === 'production';
56
72
 
57
73
  return {
58
74
  modernEnv,
59
75
  nodeEnv,
60
76
  environmentName: modernEnv || nodeEnv || DEFAULT_ENVIRONMENT_NAME,
61
77
  contractGatesFile: readString(env.MODERN_CONTRACT_GATES_FILE),
78
+ renderResources:
79
+ readString(env.MODERN_SERVER_RENDER_RESOURCES) === 'lazy'
80
+ ? 'lazy'
81
+ : 'eager',
82
+ immutableAssets:
83
+ production && readString(env.MODERN_SERVER_IMMUTABLE_ASSETS) === 'true',
84
+ precompressedAssets:
85
+ !production ||
86
+ readString(env.MODERN_SERVER_PRECOMPRESSED_ASSETS) !== 'false',
62
87
  };
63
88
  };
@@ -29,8 +29,9 @@ export type ModuleFederationCssPluginOptions = {
29
29
  * being pinned at boot: remote manifests change on every remote redeploy, and
30
30
  * fetch failures must not pin an empty/partial list for the process lifetime.
31
31
  *
32
- * Existing plugin ordering places this after the native resource plugin
33
- * (which sets `serverManifest`) and before the native RSC manifest plugin.
32
+ * Existing plugin ordering places this after the native resource plugin.
33
+ * Lazy loading keeps enrichment in the page-only resource prefix, before
34
+ * configured render middleware.
34
35
  */
35
36
  export const injectModuleFederationCssPlugin = (
36
37
  options: ModuleFederationCssPluginOptions = {},
@@ -41,7 +42,12 @@ export const injectModuleFederationCssPlugin = (
41
42
 
42
43
  setup(api) {
43
44
  api.onPrepare(() => {
44
- const { middlewares, distDirectory: pwd } = api.getServerContext();
45
+ const {
46
+ middlewares,
47
+ renderMiddlewares,
48
+ renderResources,
49
+ distDirectory: pwd,
50
+ } = api.getServerContext();
45
51
 
46
52
  if (!pwd) {
47
53
  return;
@@ -78,10 +84,20 @@ export const injectModuleFederationCssPlugin = (
78
84
  await next();
79
85
  };
80
86
 
81
- middlewares.push({
87
+ const middleware = {
82
88
  name: 'inject-module-federation-css',
83
89
  handler,
84
- });
90
+ };
91
+ if (isProd() && renderResources?.loading === 'lazy') {
92
+ // Native resource injection runs first and prepends this template
93
+ // handler. Enrich immediately after it, before application consumers.
94
+ const templates = renderMiddlewares.findIndex(
95
+ middleware => middleware.name === 'inject-html',
96
+ );
97
+ renderMiddlewares.splice(templates + 1, 0, middleware);
98
+ } else {
99
+ middlewares.push(middleware);
100
+ }
85
101
  });
86
102
  },
87
103
  });
@@ -0,0 +1,37 @@
1
+ import diagnosticsChannel from 'node:diagnostics_channel';
2
+ import type { ServerContext } from '@modern-js/server-core';
3
+
4
+ /** One server bundle import, published after it settles. */
5
+ export interface RenderBundleLoadEvent {
6
+ /** The serving application's output directory, when configured. */
7
+ readonly distDirectory: ServerContext['distDirectory'];
8
+ readonly filepath: string;
9
+ readonly durationMs: number;
10
+ readonly outcome: 'loaded' | 'failed';
11
+ /** The request path that triggered the import, or `<startup>` for warmup. */
12
+ readonly triggerPath: string;
13
+ }
14
+
15
+ /** One request through the server middlewares, traced from start to settle. */
16
+ export interface ServerRequestTrace {
17
+ /** The serving application's output directory, when configured. */
18
+ readonly distDirectory: ServerContext['distDirectory'];
19
+ /** The request path, without its query. */
20
+ readonly path: string;
21
+ }
22
+
23
+ /**
24
+ * Process-wide, so every server in a process publishes here regardless of
25
+ * which module format loaded this package. Node reports a subscriber's
26
+ * exception as an uncaught exception.
27
+ */
28
+ export const renderBundleLoadChannel =
29
+ diagnosticsChannel.channel<RenderBundleLoadEvent>(
30
+ 'modern-js:server:render-bundle-load',
31
+ );
32
+
33
+ /** Publishes `start` when a request enters and `asyncEnd` when it settles. */
34
+ export const serverRequestChannel =
35
+ diagnosticsChannel.tracingChannel<ServerRequestTrace>(
36
+ 'modern-js:server:request',
37
+ );
@@ -0,0 +1,7 @@
1
+ export {
2
+ type RenderBundleLoadEvent,
3
+ renderBundleLoadChannel,
4
+ type ServerRequestTrace,
5
+ serverRequestChannel,
6
+ } from './channels';
7
+ export { injectRenderResourcesPlugin } from './plugin';
@@ -0,0 +1,56 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import type {
3
+ Middleware,
4
+ ServerEnv,
5
+ ServerPlugin,
6
+ } from '@modern-js/server-core';
7
+ import { parseServerRuntimeExtensionsEnv } from '../env';
8
+ import {
9
+ type RenderBundleLoadEvent,
10
+ renderBundleLoadChannel,
11
+ type ServerRequestTrace,
12
+ serverRequestChannel,
13
+ } from './channels';
14
+
15
+ export function injectRenderResourcesPlugin(): ServerPlugin {
16
+ return {
17
+ name: '@modern-js/server-render-resources',
18
+ setup(api) {
19
+ const distDirectory = api.getServerContext().distDirectory;
20
+ api.updateServerContext({
21
+ renderResources: {
22
+ loading: parseServerRuntimeExtensionsEnv().renderResources,
23
+ onBundleLoad({ filepath, requestPath }) {
24
+ if (!renderBundleLoadChannel.hasSubscribers) {
25
+ return undefined;
26
+ }
27
+ const started = performance.now();
28
+ return outcome => {
29
+ renderBundleLoadChannel.publish({
30
+ distDirectory,
31
+ filepath,
32
+ durationMs: performance.now() - started,
33
+ outcome,
34
+ triggerPath: requestPath ?? '<startup>',
35
+ } satisfies RenderBundleLoadEvent);
36
+ };
37
+ },
38
+ },
39
+ });
40
+ api.onPrepare(() => {
41
+ // Node returns next() directly while nothing subscribes.
42
+ const handler: Middleware<ServerEnv> = (c, next) =>
43
+ serverRequestChannel.tracePromise(next, {
44
+ distDirectory,
45
+ path: c.req.path,
46
+ } satisfies ServerRequestTrace);
47
+ api.getServerContext().middlewares.unshift({
48
+ name: 'trace-server-request',
49
+ handler,
50
+ });
51
+ });
52
+ },
53
+ };
54
+ }
55
+
56
+ export default injectRenderResourcesPlugin;
@@ -4,6 +4,7 @@ import { injectErrorResponsePlugin } from './errorResponsePlugin';
4
4
  import { injectLocalisedLoaderPlugin } from './localisedLoaderPlugin';
5
5
  import { injectMfAssetCacheHeadersPlugin } from './mfCache';
6
6
  import { injectModuleFederationCssPlugin } from './module-federation-css/plugin';
7
+ import { injectRenderResourcesPlugin } from './render-resources/plugin';
7
8
  import { disposeServerRuntime } from './runtimeLifecycle';
8
9
  import { injectStaticServingPlugin } from './static-serving/plugin';
9
10
  import { injectTelemetryPlugin } from './telemetry/plugin';
@@ -18,6 +19,7 @@ export const ultramodernServerPlugin = (): ServerPlugin => ({
18
19
  injectModuleFederationCssPlugin(),
19
20
  injectMfAssetCacheHeadersPlugin(),
20
21
  injectStaticServingPlugin(),
22
+ injectRenderResourcesPlugin(),
21
23
  {
22
24
  name: '@modern-js/server-runtime-lifecycle',
23
25
  // Native disposal reverses registration: Effect resources close before
@@ -0,0 +1,41 @@
1
+ import type { StaticAssetStat } from '@modern-js/server-core/node';
2
+ import { fs } from '@modern-js/utils';
3
+
4
+ export const IMMUTABLE_ASSET_STAT_LIMIT = 8192;
5
+
6
+ /**
7
+ * File metadata for immutable releases. Only found regular files are kept, so
8
+ * a missing path is looked up again by the next request. The oldest entry is
9
+ * dropped once the limit is reached.
10
+ */
11
+ export function createImmutableAssetStat(): StaticAssetStat {
12
+ const stats = new Map<string, ReturnType<StaticAssetStat>>();
13
+ const forget = (filename: string, pending: ReturnType<StaticAssetStat>) => {
14
+ if (stats.get(filename) === pending) {
15
+ stats.delete(filename);
16
+ }
17
+ };
18
+ return filename => {
19
+ const cached = stats.get(filename);
20
+ if (cached) {
21
+ return cached;
22
+ }
23
+ const pending: ReturnType<StaticAssetStat> = fs.stat(filename).then(
24
+ stat => {
25
+ if (!stat.isFile()) {
26
+ forget(filename, pending);
27
+ }
28
+ return stat;
29
+ },
30
+ () => {
31
+ forget(filename, pending);
32
+ return null;
33
+ },
34
+ );
35
+ if (stats.size >= IMMUTABLE_ASSET_STAT_LIMIT) {
36
+ stats.delete(stats.keys().next().value!);
37
+ }
38
+ stats.set(filename, pending);
39
+ return pending;
40
+ };
41
+ }