@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.3 → 3.9.0-ultramodern.5

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 (171) hide show
  1. package/dist/cjs/bff-policy/crossProjectPolicy.js +309 -0
  2. package/dist/cjs/bff-policy/index.js +62 -0
  3. package/dist/cjs/bff-policy/node.js +69 -0
  4. package/dist/cjs/bff-policy/operationContracts.js +182 -0
  5. package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
  6. package/dist/cjs/errorResponsePlugin.js +57 -0
  7. package/dist/cjs/localisedLoaderPlugin.js +62 -0
  8. package/dist/cjs/mfCache.js +6 -0
  9. package/dist/cjs/module-federation-css/plugin.js +6 -0
  10. package/dist/cjs/serverConfig.js +18 -0
  11. package/dist/cjs/serverPlugin.js +74 -0
  12. package/dist/cjs/static-serving/plugin.js +57 -0
  13. package/dist/cjs/static-serving/responders.js +158 -0
  14. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  15. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  16. package/dist/cjs/telemetry/canaryCompatibility.js +73 -0
  17. package/dist/cjs/telemetry/healthSetup.js +4 -0
  18. package/dist/cjs/telemetry/lifecycle.js +15 -16
  19. package/dist/cjs/telemetry/plugin.js +10 -3
  20. package/dist/cjs/telemetry/runtimeEndpoints.js +10 -3
  21. package/dist/esm/bff-policy/crossProjectPolicy.mjs +259 -0
  22. package/dist/esm/bff-policy/index.mjs +1 -0
  23. package/dist/esm/errorResponsePlugin.mjs +19 -0
  24. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  25. package/dist/esm/mfCache.mjs +6 -0
  26. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  27. package/dist/esm/serverConfig.mjs +0 -0
  28. package/dist/esm/serverPlugin.mjs +34 -0
  29. package/dist/esm/telemetry/canaryCompatibility.mjs +35 -0
  30. package/dist/esm/telemetry/healthSetup.mjs +4 -0
  31. package/dist/esm/telemetry/lifecycle.mjs +15 -16
  32. package/dist/esm/telemetry/plugin.mjs +9 -2
  33. package/dist/esm/telemetry/runtimeEndpoints.mjs +10 -3
  34. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +260 -0
  35. package/dist/esm-node/bff-policy/index.mjs +2 -0
  36. package/dist/esm-node/bff-policy/node.mjs +3 -0
  37. package/dist/esm-node/bff-policy/operationContracts.mjs +129 -0
  38. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  39. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  40. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  41. package/dist/esm-node/mfCache.mjs +6 -0
  42. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  43. package/dist/esm-node/serverConfig.mjs +1 -0
  44. package/dist/esm-node/serverPlugin.mjs +35 -0
  45. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  46. package/dist/esm-node/static-serving/responders.mjs +111 -0
  47. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  48. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  49. package/dist/esm-node/telemetry/canaryCompatibility.mjs +36 -0
  50. package/dist/esm-node/telemetry/healthSetup.mjs +4 -0
  51. package/dist/esm-node/telemetry/lifecycle.mjs +15 -16
  52. package/dist/esm-node/telemetry/plugin.mjs +9 -2
  53. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +10 -3
  54. package/dist/types/bff-policy/crossProjectPolicy.d.ts +110 -0
  55. package/dist/types/bff-policy/index.d.ts +1 -0
  56. package/dist/types/bff-policy/node.d.ts +2 -0
  57. package/dist/types/bff-policy/operationContracts.d.ts +85 -0
  58. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  59. package/dist/types/errorResponsePlugin.d.ts +3 -0
  60. package/dist/types/index.d.ts +1 -0
  61. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  62. package/dist/types/mfCache.d.ts +2 -3
  63. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  64. package/dist/types/serverConfig.d.ts +17 -0
  65. package/dist/types/serverPlugin.d.ts +5 -0
  66. package/dist/types/static-serving/plugin.d.ts +3 -0
  67. package/dist/types/static-serving/responders.d.ts +2 -0
  68. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  69. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  70. package/dist/types/telemetry/canaryCompatibility.d.ts +19 -0
  71. package/dist/types/telemetry/healthSetup.d.ts +3 -1
  72. package/dist/types/telemetry/lifecycle.d.ts +2 -2
  73. package/dist/types/telemetry/plugin.d.ts +2 -1
  74. package/dist/types/telemetry/runtimeEndpoints.d.ts +3 -1
  75. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  76. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  77. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +110 -0
  78. package/dist/types-esm/bff-policy/index.d.mts +1 -0
  79. package/dist/types-esm/bff-policy/node.d.mts +2 -0
  80. package/dist/types-esm/bff-policy/operationContracts.d.mts +85 -0
  81. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  82. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  83. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  84. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  85. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  86. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  87. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  88. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  89. package/dist/types-esm/env.d.mts +40 -0
  90. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  91. package/dist/types-esm/index.d.mts +8 -0
  92. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  93. package/dist/types-esm/mfCache.d.mts +26 -0
  94. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  95. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  96. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  97. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  98. package/dist/types-esm/module-federation-css/remote.d.mts +20 -0
  99. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  100. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  101. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  102. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  103. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  104. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  105. package/dist/types-esm/serverConfig.d.mts +17 -0
  106. package/dist/types-esm/serverPlugin.d.mts +5 -0
  107. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  108. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  109. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  110. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  111. package/dist/types-esm/telemetry/canaryCompatibility.d.mts +19 -0
  112. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  113. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  114. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  115. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  116. package/dist/types-esm/telemetry/healthSetup.d.mts +19 -0
  117. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  118. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  119. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  120. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  121. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  122. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +37 -0
  123. package/dist/types-esm/telemetry.d.mts +1 -0
  124. package/dist/types-esm/telemetryCore.d.mts +6 -0
  125. package/package.json +158 -26
  126. package/rslib.config.mts +36 -2
  127. package/rstest.config.mts +11 -0
  128. package/src/bff-policy/crossProjectPolicy.ts +781 -0
  129. package/src/bff-policy/index.ts +1 -0
  130. package/src/bff-policy/node.ts +2 -0
  131. package/src/bff-policy/operationContracts.ts +298 -0
  132. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  133. package/src/errorResponsePlugin.ts +21 -0
  134. package/src/index.ts +4 -0
  135. package/src/localisedLoaderPlugin.ts +34 -0
  136. package/src/mfCache.ts +4 -3
  137. package/src/module-federation-css/plugin.ts +4 -3
  138. package/src/serverConfig.ts +32 -0
  139. package/src/serverPlugin.ts +38 -0
  140. package/src/static-serving/plugin.ts +16 -0
  141. package/src/static-serving/responders.ts +208 -0
  142. package/src/static-serving/staticModuleFederation.ts +255 -0
  143. package/src/static-serving/staticPrecompressed.ts +193 -0
  144. package/src/telemetry/canaryCompatibility.ts +55 -0
  145. package/src/telemetry/healthSetup.ts +9 -1
  146. package/src/telemetry/lifecycle.ts +20 -32
  147. package/src/telemetry/plugin.ts +6 -2
  148. package/src/telemetry/runtimeEndpoints.ts +13 -2
  149. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +487 -0
  150. package/tests/bff-policy/crossProjectPolicy.test.ts +1004 -0
  151. package/tests/bff-policy/operationContracts.test.ts +221 -0
  152. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  153. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +134 -0
  154. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  155. package/tests/env.test.ts +45 -64
  156. package/tests/localisedLoader.test.ts +120 -0
  157. package/tests/mfCache.test.ts +1 -88
  158. package/tests/moduleFederationCss.test.ts +4 -48
  159. package/tests/nativeErrorResponse.test.ts +199 -0
  160. package/tests/nativeServerAssembly.test.ts +402 -0
  161. package/tests/registration.test.ts +1 -86
  162. package/tests/runtimeLifecycle.test.ts +69 -17
  163. package/tests/static-serving/ordering.test.ts +214 -0
  164. package/tests/static-serving/provider.test.ts +83 -0
  165. package/tests/static-serving/static.test.ts +400 -0
  166. package/tests/telemetry.test.ts +35 -101
  167. package/tests/telemetryAutopilot.test.ts +5 -146
  168. package/tests/telemetryCanaryCompatibility.test.ts +152 -0
  169. package/tests/telemetryHealthMonitor.test.ts +0 -2
  170. package/tests/telemetryLifecycle.test.ts +11 -253
  171. package/tests/telemetryRegistryQueueMatrix.test.ts +0 -1
@@ -0,0 +1,111 @@
1
+ import "node:module";
2
+ import node_path from "node:path";
3
+ import { serveStaticAsset } from "@modern-js/server-core/node";
4
+ import { applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath } from "./staticModuleFederation.mjs";
5
+ import { applyPreCompressedAssetHeaders, resolvePreCompressedAsset } from "./staticPrecompressed.mjs";
6
+ async function respondPrecompressedAsset(context, asset, serve) {
7
+ const selected = await resolvePreCompressedAsset(context, asset.filename);
8
+ const response = selected.acceptable ? await serve({
9
+ filename: selected.selected?.filepath,
10
+ contentLength: true
11
+ }) : new Response(null, {
12
+ status: 406
13
+ });
14
+ if (null === response) return null;
15
+ context.res = response;
16
+ applyPreCompressedAssetHeaders(context, selected);
17
+ if ('.cjs' === node_path.extname(asset.filename).toLowerCase()) context.res.headers.set('Content-Type', "text/javascript; charset=UTF-8");
18
+ return context.res;
19
+ }
20
+ function createStaticExtensionResponders() {
21
+ const caches = new Map();
22
+ const getAssets = (root)=>{
23
+ let cache = caches.get(root);
24
+ if (!cache) {
25
+ cache = {
26
+ assets: null,
27
+ expires: 0,
28
+ pending: null
29
+ };
30
+ caches.set(root, cache);
31
+ }
32
+ if (cache.assets && Date.now() < cache.expires) return Promise.resolve(cache.assets);
33
+ if (cache.pending) return cache.pending;
34
+ const current = cache;
35
+ const pending = getModuleFederationAssetList(root).then((assets)=>{
36
+ current.assets = assets;
37
+ current.expires = Date.now() + 1000;
38
+ return assets;
39
+ }).finally(()=>{
40
+ current.pending = null;
41
+ });
42
+ current.pending = pending;
43
+ return pending;
44
+ };
45
+ async function serveFederated(context, asset, serve, requestPath, pathPrefix, remoteEntry) {
46
+ applyModuleFederationAssetHeaders(context);
47
+ const patchManifest = isModuleFederationManifestRequest(requestPath) && !isBackendModuleFederationManifestRequest(requestPath);
48
+ if (!patchManifest && !remoteEntry) return respondPrecompressedAsset(context, asset, serve);
49
+ const response = await serve({
50
+ contentLength: true
51
+ });
52
+ if (!response) return null;
53
+ const bytes = Buffer.from(await response.arrayBuffer());
54
+ const patched = patchManifest ? patchModuleFederationManifestPublicPath(context, bytes, pathPrefix) : patchModuleFederationRemoteEntryPublicPath(context, bytes, pathPrefix);
55
+ response.headers.set('Content-Length', String(patched.byteLength));
56
+ if ('.cjs' === node_path.extname(asset.filename).toLowerCase()) response.headers.set('Content-Type', "text/javascript; charset=UTF-8");
57
+ return new Response(Uint8Array.from(patched), {
58
+ status: response.status,
59
+ headers: response.headers
60
+ });
61
+ }
62
+ async function serveGenerated(context, root) {
63
+ if (![
64
+ 'GET',
65
+ 'HEAD'
66
+ ].includes(context.req.raw.method.toUpperCase())) return null;
67
+ let pathname;
68
+ try {
69
+ pathname = decodeURIComponent(context.req.path).replace(/\\/gu, '/');
70
+ } catch {
71
+ return null;
72
+ }
73
+ if (pathname.includes('\0') || pathname.split('/').includes('..')) return null;
74
+ const publicRoot = node_path.join(root, 'public');
75
+ const response = await serveStaticAsset(context, {
76
+ filename: node_path.resolve(publicRoot, pathname.replace(/^\/+/, '')),
77
+ kind: 'static',
78
+ root: publicRoot,
79
+ realpath: true
80
+ }, (asset, serve)=>respondPrecompressedAsset(context, asset, serve));
81
+ if (response && 'HEAD' === context.req.raw.method.toUpperCase()) return new Response(null, {
82
+ status: response.status,
83
+ headers: response.headers
84
+ });
85
+ return response;
86
+ }
87
+ return {
88
+ async respondAsset (context, asset, serve, { root, pathPrefix }) {
89
+ const requestPath = getModuleFederationRequestPath(context.req.path, pathPrefix);
90
+ if (requestPath.includes('..')) return null;
91
+ const assets = await getAssets(root);
92
+ if ('static' === asset.kind && assets.assets.has(requestPath)) return serveFederated(context, asset, serve, requestPath, pathPrefix, assets.remoteEntries.has(requestPath));
93
+ return respondPrecompressedAsset(context, asset, serve);
94
+ },
95
+ async respondPublicFallback (context, respondPublic, { root, pathPrefix }) {
96
+ const requestPath = getModuleFederationRequestPath(context.req.path, pathPrefix);
97
+ if (requestPath.includes('..')) return null;
98
+ const assets = await getAssets(root);
99
+ if (assets.assets.has(requestPath)) {
100
+ const response = await serveStaticAsset(context, {
101
+ filename: node_path.join(root, requestPath),
102
+ kind: 'static',
103
+ root
104
+ }, (asset, serve)=>serveFederated(context, asset, serve, requestPath, pathPrefix, assets.remoteEntries.has(requestPath)));
105
+ if (null !== response) return response;
106
+ }
107
+ return await respondPublic() ?? serveGenerated(context, root);
108
+ }
109
+ };
110
+ }
111
+ export { createStaticExtensionResponders };
@@ -0,0 +1,105 @@
1
+ import "node:module";
2
+ import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
+ import { fs } from "@modern-js/utils";
4
+ import path from "path";
5
+ const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
6
+ const BACKEND_MODULE_FEDERATION_MANIFEST_FILE = 'backend-mf-manifest.json';
7
+ const MODULE_FEDERATION_MANIFEST_FILES = [
8
+ MODULE_FEDERATION_MANIFEST_FILE,
9
+ BACKEND_MODULE_FEDERATION_MANIFEST_FILE
10
+ ];
11
+ const MODULE_FEDERATION_OPTIONAL_FILES = [
12
+ 'mf-stats.json'
13
+ ];
14
+ const trimLeadingSlash = (value)=>value.replace(/^\/+/, '');
15
+ const getModuleFederationRequestPath = (pathname, pathPrefix)=>{
16
+ const normalizedPrefix = `/${trimLeadingSlash(pathPrefix)}`.replace(/\/+$/u, '');
17
+ const requestPath = normalizedPrefix && (pathname === normalizedPrefix || pathname.startsWith(`${normalizedPrefix}/`)) ? pathname.slice(normalizedPrefix.length) : pathname;
18
+ return trimLeadingSlash(requestPath);
19
+ };
20
+ const isModuleFederationManifestRequest = (requestPath)=>MODULE_FEDERATION_MANIFEST_FILES.includes(requestPath);
21
+ const isBackendModuleFederationManifestRequest = (requestPath)=>requestPath === BACKEND_MODULE_FEDERATION_MANIFEST_FILE;
22
+ const applyModuleFederationAssetHeaders = (c)=>{
23
+ c.header('Access-Control-Allow-Origin', '*');
24
+ c.header('Access-Control-Allow-Headers', '*');
25
+ c.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS');
26
+ };
27
+ const joinModuleFederationAssetPath = (assetPath, assetName)=>{
28
+ if (!assetName) return '';
29
+ return trimLeadingSlash(path.posix.join(assetPath || '', assetName));
30
+ };
31
+ const appendModuleFederationAsset = (set, assetPath)=>{
32
+ if (assetPath) set.add(trimLeadingSlash(assetPath));
33
+ };
34
+ const appendModuleFederationAssets = (set, assets)=>{
35
+ assets?.js?.sync?.forEach((asset)=>appendModuleFederationAsset(set, asset));
36
+ assets?.js?.async?.forEach((asset)=>appendModuleFederationAsset(set, asset));
37
+ assets?.css?.sync?.forEach((asset)=>appendModuleFederationAsset(set, asset));
38
+ assets?.css?.async?.forEach((asset)=>appendModuleFederationAsset(set, asset));
39
+ };
40
+ const hasAbsoluteProtocol = (value)=>/^https?:\/\//i.test(value) || value.startsWith('//');
41
+ const ensureLeadingSlash = (value)=>{
42
+ if ('' === value) return '/';
43
+ return value.startsWith('/') ? value : `/${value}`;
44
+ };
45
+ const ensureTrailingSlash = (value)=>value.endsWith('/') ? value : `${value}/`;
46
+ const patchModuleFederationManifestPublicPath = (c, manifestBuffer, pathPrefix)=>{
47
+ try {
48
+ const manifest = JSON.parse(manifestBuffer.toString('utf-8'));
49
+ const publicPath = manifest.metaData?.publicPath;
50
+ if (!publicPath || hasAbsoluteProtocol(publicPath)) return manifestBuffer;
51
+ const requestURL = new URL(c.req.url);
52
+ const prefixPath = ensureTrailingSlash(ensureLeadingSlash(pathPrefix || '/'));
53
+ manifest.metaData = {
54
+ ...manifest.metaData,
55
+ publicPath: `${requestURL.origin}${prefixPath}`
56
+ };
57
+ return Buffer.from(JSON.stringify(manifest), 'utf-8');
58
+ } catch {
59
+ return manifestBuffer;
60
+ }
61
+ };
62
+ const patchModuleFederationRemoteEntryPublicPath = (c, remoteEntryBuffer, pathPrefix)=>{
63
+ const requestURL = new URL(c.req.url);
64
+ const prefixPath = ensureTrailingSlash(ensureLeadingSlash(pathPrefix || '/'));
65
+ const publicPath = `${requestURL.origin}${prefixPath}`;
66
+ const source = remoteEntryBuffer.toString('utf-8');
67
+ const patched = source.replace(/__webpack_require__\.p\s*=\s*(['"`])[^'"`]*\1;/, `__webpack_require__.p = ${JSON.stringify(publicPath)};`).replace(/__rspack_require__\.p\s*=\s*(['"`])[^'"`]*\1;/, `__rspack_require__.p = ${JSON.stringify(publicPath)};`);
68
+ if (patched === source) return remoteEntryBuffer;
69
+ return Buffer.from(patched, 'utf-8');
70
+ };
71
+ const getModuleFederationAssetList = async (pwd)=>{
72
+ const assets = new Set();
73
+ const remoteEntries = new Set();
74
+ let manifestFound = false;
75
+ for (const manifestFile of MODULE_FEDERATION_MANIFEST_FILES){
76
+ const manifestPath = path.join(pwd, manifestFile);
77
+ if (!await fs.pathExists(manifestPath)) continue;
78
+ manifestFound = true;
79
+ assets.add(manifestFile);
80
+ const manifestBuffer = await fileReader.readFileFromSystem(manifestPath, 'buffer');
81
+ if (null !== manifestBuffer) try {
82
+ const manifest = JSON.parse(manifestBuffer.toString('utf-8'));
83
+ const remoteEntry = joinModuleFederationAssetPath(manifest.metaData?.remoteEntry?.path, manifest.metaData?.remoteEntry?.name);
84
+ const dtsZip = joinModuleFederationAssetPath(manifest.metaData?.types?.path, manifest.metaData?.types?.zip);
85
+ const dtsApi = joinModuleFederationAssetPath(manifest.metaData?.types?.path, manifest.metaData?.types?.api);
86
+ if (remoteEntry) {
87
+ assets.add(remoteEntry);
88
+ remoteEntries.add(remoteEntry);
89
+ }
90
+ appendModuleFederationAsset(assets, dtsZip);
91
+ appendModuleFederationAsset(assets, dtsApi);
92
+ manifest.shared?.forEach((item)=>appendModuleFederationAssets(assets, item.assets));
93
+ manifest.remotes?.forEach((item)=>appendModuleFederationAssets(assets, item.assets));
94
+ manifest.exposes?.forEach((item)=>appendModuleFederationAssets(assets, item.assets));
95
+ } catch {}
96
+ }
97
+ if (manifestFound) {
98
+ for (const filename of MODULE_FEDERATION_OPTIONAL_FILES)if (await fs.pathExists(path.join(pwd, filename))) assets.add(filename);
99
+ }
100
+ return {
101
+ assets,
102
+ remoteEntries
103
+ };
104
+ };
105
+ export { MODULE_FEDERATION_MANIFEST_FILE, applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath };
@@ -0,0 +1,112 @@
1
+ import "node:module";
2
+ import { fs } from "@modern-js/utils";
3
+ const PRE_COMPRESSED_ASSET_EXTENSIONS = {
4
+ br: '.br',
5
+ gzip: '.gz'
6
+ };
7
+ const PRE_COMPRESSED_SUPPORTED_ENCODINGS = [
8
+ 'br',
9
+ 'gzip'
10
+ ];
11
+ const QUALITY_VALUE_PATTERN = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
12
+ const parseAcceptEncoding = (value)=>value.split(',').map((item)=>item.trim()).filter(Boolean).map((item)=>{
13
+ const [rawName, ...params] = item.split(';');
14
+ const name = rawName.trim().toLowerCase();
15
+ let q = 1;
16
+ let qualitySeen = false;
17
+ for (const param of params){
18
+ const [key, rawValue] = param.split('=').map((v)=>v.trim());
19
+ if ('q' === key.toLowerCase()) {
20
+ if (qualitySeen || null == rawValue || !QUALITY_VALUE_PATTERN.test(rawValue)) {
21
+ q = 0;
22
+ break;
23
+ }
24
+ qualitySeen = true;
25
+ q = Number(rawValue);
26
+ }
27
+ }
28
+ return {
29
+ name,
30
+ q
31
+ };
32
+ });
33
+ const getAcceptedRepresentations = (value)=>{
34
+ if (!value) return [
35
+ 'identity'
36
+ ];
37
+ const parsed = parseAcceptEncoding(value);
38
+ const qualityByEncoding = new Map();
39
+ let wildcardQuality;
40
+ for (const { name, q } of parsed){
41
+ if ('*' === name) {
42
+ wildcardQuality = q;
43
+ continue;
44
+ }
45
+ qualityByEncoding.set(name, q);
46
+ }
47
+ const getQuality = (encoding)=>{
48
+ const explicit = qualityByEncoding.get(encoding);
49
+ if (void 0 !== explicit) return explicit;
50
+ return wildcardQuality ?? 0;
51
+ };
52
+ const identityQuality = qualityByEncoding.get('identity') ?? wildcardQuality ?? 1;
53
+ return [
54
+ ...PRE_COMPRESSED_SUPPORTED_ENCODINGS.map((encoding)=>({
55
+ encoding,
56
+ quality: getQuality(encoding)
57
+ })),
58
+ {
59
+ encoding: 'identity',
60
+ quality: identityQuality
61
+ }
62
+ ].filter((item)=>item.quality > 0).sort((a, b)=>b.quality - a.quality).map((item)=>item.encoding);
63
+ };
64
+ const appendVaryHeader = (c, value)=>{
65
+ const current = c.res.headers.get('Vary');
66
+ if (!current) return void c.header('Vary', value);
67
+ const values = current.split(',').map((item)=>item.trim().toLowerCase()).filter(Boolean);
68
+ if (!values.includes(value.toLowerCase())) c.header('Vary', `${current}, ${value}`);
69
+ };
70
+ const resolvePreCompressedAsset = async (c, filepath)=>{
71
+ const brPath = `${filepath}${PRE_COMPRESSED_ASSET_EXTENSIONS.br}`;
72
+ const gzipPath = `${filepath}${PRE_COMPRESSED_ASSET_EXTENSIONS.gzip}`;
73
+ const [hasBr, hasGzip] = await Promise.all([
74
+ fs.pathExists(brPath),
75
+ fs.pathExists(gzipPath)
76
+ ]);
77
+ const hasVariant = hasBr || hasGzip;
78
+ const acceptedRepresentations = getAcceptedRepresentations(c.req.header('accept-encoding'));
79
+ for (const encoding of acceptedRepresentations){
80
+ if ('identity' === encoding) return {
81
+ selected: null,
82
+ hasVariant,
83
+ acceptable: true
84
+ };
85
+ if ('br' === encoding && hasBr) return {
86
+ selected: {
87
+ filepath: brPath,
88
+ encoding
89
+ },
90
+ hasVariant: true,
91
+ acceptable: true
92
+ };
93
+ if ('gzip' === encoding && hasGzip) return {
94
+ selected: {
95
+ filepath: gzipPath,
96
+ encoding
97
+ },
98
+ hasVariant: true,
99
+ acceptable: true
100
+ };
101
+ }
102
+ return {
103
+ selected: null,
104
+ hasVariant,
105
+ acceptable: false
106
+ };
107
+ };
108
+ const applyPreCompressedAssetHeaders = (c, preCompressedAsset)=>{
109
+ if (preCompressedAsset.hasVariant || !preCompressedAsset.acceptable) appendVaryHeader(c, 'Accept-Encoding');
110
+ if (preCompressedAsset.selected) c.header('Content-Encoding', preCompressedAsset.selected.encoding);
111
+ };
112
+ export { applyPreCompressedAssetHeaders, resolvePreCompressedAsset };
@@ -0,0 +1,36 @@
1
+ import "node:module";
2
+ const createTelemetryCanaryCompatibility = (registry)=>{
3
+ let state = 'canary';
4
+ return {
5
+ observe (evaluation) {
6
+ let action;
7
+ if ('became_healthy' === evaluation.transition && 'canary' === state) {
8
+ state = 'promoted';
9
+ action = 'promote';
10
+ } else {
11
+ if ('became_unhealthy' !== evaluation.transition || 'rolled_back' === state) return;
12
+ state = 'rolled_back';
13
+ action = 'rollback';
14
+ }
15
+ try {
16
+ registry.enqueueMetric({
17
+ name: `telemetry.canary.${action}`,
18
+ value: 1,
19
+ unit: 'count',
20
+ tags: {
21
+ action,
22
+ state,
23
+ failures: String(evaluation.failures.length)
24
+ }
25
+ });
26
+ } catch (_error) {}
27
+ },
28
+ getStatusSnapshot (snapshot) {
29
+ return {
30
+ ...snapshot,
31
+ state
32
+ };
33
+ }
34
+ };
35
+ };
36
+ export { createTelemetryCanaryCompatibility };
@@ -2,6 +2,7 @@ import "node:module";
2
2
  import { DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "../contract-gate-snapshot-store/index.mjs";
3
3
  import { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, createRuntimeFallbackSignalRuntimeState, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, resolveRuntimeFallbackSignalEndpoint } from "../runtimeFallbackSignal.mjs";
4
4
  import { TelemetryHealthMonitor } from "../telemetryCore.mjs";
5
+ import { createTelemetryCanaryCompatibility } from "./canaryCompatibility.mjs";
5
6
  function emitHealthTransitionMetric(registry, evaluation) {
6
7
  try {
7
8
  registry.enqueueMetric({
@@ -19,6 +20,7 @@ function emitHealthTransitionMetric(registry, evaluation) {
19
20
  const setupTelemetryHealthMonitoring = ({ registry, appDirectory, legacyHealthConfig })=>{
20
21
  if (!legacyHealthConfig?.enabled) return {};
21
22
  const contractGates = legacyHealthConfig.contractGates;
23
+ const canaryCompatibility = createTelemetryCanaryCompatibility(registry);
22
24
  const healthMonitor = new TelemetryHealthMonitor({
23
25
  registry,
24
26
  evaluationIntervalMs: legacyHealthConfig.evaluationIntervalMs,
@@ -30,6 +32,7 @@ const setupTelemetryHealthMonitoring = ({ registry, appDirectory, legacyHealthCo
30
32
  requiredContractGates: Object.keys(contractGates || {}),
31
33
  onTransition: (evaluation)=>{
32
34
  emitHealthTransitionMetric(registry, evaluation);
35
+ canaryCompatibility.observe(evaluation);
33
36
  }
34
37
  });
35
38
  if (contractGates) healthMonitor.setContractGates(contractGates);
@@ -58,6 +61,7 @@ const setupTelemetryHealthMonitoring = ({ registry, appDirectory, legacyHealthCo
58
61
  const runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(legacyHealthConfig.autopilot?.runtimeFallbackSignal?.auth);
59
62
  return {
60
63
  healthMonitor,
64
+ canaryCompatibility,
61
65
  gateSnapshotStorePromise,
62
66
  runtimeFallbackSignalConfig,
63
67
  runtimeStatusAuthConfig
@@ -1,4 +1,5 @@
1
1
  import "node:module";
2
+ import { logger } from "@modern-js/utils";
2
3
  import { resolveContractGateSnapshotPath } from "../contract-gate-snapshot-store/index.mjs";
3
4
  import { ContractGateSnapshotObserver } from "../contractGateSnapshotObserver.mjs";
4
5
  import { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint } from "../telemetryCore.mjs";
@@ -10,30 +11,28 @@ const ensureTelemetryBeforeExitHook = ()=>{
10
11
  process.on('beforeExit', ()=>{
11
12
  for (const close of [
12
13
  ...activeTelemetryLaneClosers
13
- ])close();
14
+ ])close().catch((error)=>logger.error(error));
14
15
  });
15
16
  };
16
17
  const registerTelemetryLifecycle = ({ api, registry, telemetryConfig, legacyHealthConfig, healthMonitor, gateSnapshotStorePromise, appDirectory })=>{
17
18
  let contractGateSnapshotObserver;
18
- let telemetryLaneClosed = false;
19
- const closeTelemetryLane = async ()=>{
20
- if (telemetryLaneClosed) return;
21
- telemetryLaneClosed = true;
22
- activeTelemetryLaneClosers.delete(closeTelemetryLane);
23
- contractGateSnapshotObserver?.stop();
24
- healthMonitor?.stop();
25
- await registry.shutdown();
19
+ let closePromise;
20
+ const closeTelemetryLane = ()=>{
21
+ closePromise ??= Promise.resolve().then(async ()=>{
22
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
23
+ contractGateSnapshotObserver?.stop();
24
+ healthMonitor?.stop();
25
+ await registry.shutdown();
26
+ });
27
+ return closePromise;
26
28
  };
29
+ api.onDispose(closeTelemetryLane);
30
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
31
+ ensureTelemetryBeforeExitHook();
27
32
  let prepared = false;
28
33
  api.onPrepare(async ()=>{
29
- if (prepared) return;
34
+ if (prepared || closePromise) return;
30
35
  prepared = true;
31
- const { nodeServer } = api.getServerContext();
32
- if (nodeServer && 'function' == typeof nodeServer.once) nodeServer.once('close', ()=>{
33
- closeTelemetryLane();
34
- });
35
- activeTelemetryLaneClosers.add(closeTelemetryLane);
36
- ensureTelemetryBeforeExitHook();
37
36
  if (telemetryConfig.exporters?.otlp?.enabled) {
38
37
  maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
39
38
  await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
@@ -1,5 +1,5 @@
1
1
  import "node:module";
2
- import { parseTraceparent } from "@modern-js/create-request/server";
2
+ import { parseTraceparent } from "@modern-js/runtime-extensions/request-context";
3
3
  import { logger } from "@modern-js/utils";
4
4
  import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
5
5
  import { TelemetryHealthMonitor, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, toTelemetryEnvelope } from "../telemetryCore.mjs";
@@ -17,6 +17,12 @@ const resolveTelemetrySloOptions = (sloConfig, warnSink = (message)=>logger.warn
17
17
  });
18
18
  const injectTelemetryPlugin = ()=>({
19
19
  name: '@modern-js/inject-telemetry',
20
+ pre: [
21
+ '@modern-js/plugin-inject-route'
22
+ ],
23
+ post: [
24
+ '@modern-js/plugin-inject-config-middleware'
25
+ ],
20
26
  setup (api) {
21
27
  const serverConfig = api.getServerConfig();
22
28
  const telemetryConfig = serverConfig?.server?.telemetry;
@@ -37,7 +43,7 @@ const injectTelemetryPlugin = ()=>({
37
43
  redactionKeys: telemetryConfig.redactionKeys,
38
44
  slo: resolveTelemetrySloOptions(telemetryConfig.slo)
39
45
  });
40
- const { healthMonitor, gateSnapshotStorePromise, runtimeFallbackSignalConfig, runtimeStatusAuthConfig } = setupTelemetryHealthMonitoring({
46
+ const { healthMonitor, canaryCompatibility, gateSnapshotStorePromise, runtimeFallbackSignalConfig, runtimeStatusAuthConfig } = setupTelemetryHealthMonitoring({
41
47
  registry,
42
48
  appDirectory,
43
49
  legacyHealthConfig: telemetryConfig.canary
@@ -46,6 +52,7 @@ const injectTelemetryPlugin = ()=>({
46
52
  middlewares.push(createRuntimeStatusMiddleware({
47
53
  registry,
48
54
  healthMonitor,
55
+ canaryCompatibility,
49
56
  runtimeFallbackSignalConfig,
50
57
  runtimeStatusAuthConfig
51
58
  }));
@@ -35,7 +35,7 @@ const createRuntimeFallbackSignalMiddleware = (signalConfig)=>({
35
35
  }
36
36
  }
37
37
  });
38
- const createRuntimeStatusMiddleware = ({ registry, healthMonitor, runtimeFallbackSignalConfig, runtimeStatusAuthConfig })=>({
38
+ const createRuntimeStatusMiddleware = ({ registry, healthMonitor, canaryCompatibility, runtimeFallbackSignalConfig, runtimeStatusAuthConfig })=>({
39
39
  name: 'telemetry-runtime-status',
40
40
  path: DEFAULT_RUNTIME_STATUS_ENDPOINT,
41
41
  method: 'get',
@@ -47,6 +47,7 @@ const createRuntimeStatusMiddleware = ({ registry, healthMonitor, runtimeFallbac
47
47
  timestamp: Date.now()
48
48
  });
49
49
  enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeStatusAuthConfig.headerName), runtimeStatusAuthConfig);
50
+ const healthSnapshot = healthMonitor?.getStatusSnapshot();
50
51
  return c.json({
51
52
  ok: true,
52
53
  timestamp: Date.now(),
@@ -54,9 +55,15 @@ const createRuntimeStatusMiddleware = ({ registry, healthMonitor, runtimeFallbac
54
55
  queueStats: registry.getQueueStats(),
55
56
  exporterHealth: registry.getExporterHealth()
56
57
  },
57
- health: healthMonitor ? {
58
+ health: healthSnapshot ? {
58
59
  enabled: true,
59
- ...healthMonitor.getStatusSnapshot()
60
+ ...healthSnapshot
61
+ } : {
62
+ enabled: false
63
+ },
64
+ canary: healthSnapshot && canaryCompatibility ? {
65
+ enabled: true,
66
+ ...canaryCompatibility.getStatusSnapshot(healthSnapshot)
60
67
  } : {
61
68
  enabled: false
62
69
  },
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Cross-project BFF policy evaluator.
3
+ *
4
+ * THREAT MODEL — read before relying on this module:
5
+ *
6
+ * Every header this evaluator inspects (envelope, operation id, operation
7
+ * context details) is constructed by the CLIENT from public, open-source
8
+ * formats. Without an out-of-band identity binding the checks below are a
9
+ * version-skew and misconfiguration gate, not an authentication or
10
+ * authorization boundary: any caller can echo an allowed `requestId` and a
11
+ * matching operation context.
12
+ *
13
+ * To use `allowedNamespaces`, supply
14
+ * {@link CrossProjectPolicyConfig.verifyProducerIdentity}: a server-side
15
+ * hook that derives the producer namespace from a VERIFIED channel (mTLS
16
+ * peer identity, gateway-authenticated JWT claims, service-mesh headers
17
+ * stripped at the edge, ...). Requests fail closed when a namespace allowlist
18
+ * is configured without this hook unless `allowClientAssertedNamespace` is
19
+ * explicitly enabled. That escape hatch keeps legacy local/demo ergonomics:
20
+ * the client-asserted namespace must match the allowlist. When the hook is
21
+ * present, the client-asserted namespace must match the verified namespace
22
+ * and the allowlist is checked against the verified value.
23
+ *
24
+ * Client-side counterparts in `@modern-js/create-request` (identity binding,
25
+ * operation contract validation) are developer-experience aids that fail
26
+ * fast in well-behaved clients; they protect nothing against a malicious
27
+ * caller.
28
+ */
29
+ export declare const BFF_ENVELOPE_HEADER = "x-modernjs-bff-envelope";
30
+ export declare const BFF_OPERATION_CONTEXT_HEADER = "x-operation-id";
31
+ export declare const BFF_OPERATION_CONTEXT_DETAIL_HEADER = "x-modernjs-bff-operation-context";
32
+ export type CrossProjectOperationContract = {
33
+ schemaHash?: string;
34
+ operationVersion?: number;
35
+ operationId?: string;
36
+ };
37
+ /**
38
+ * Request facts observed by the server adapter rather than asserted by the
39
+ * client. `routePath` is the matched route template when the router exposes
40
+ * one (for example `/api/customers/:id`), not the client-provided detail.
41
+ */
42
+ export type CrossProjectRequestObservation = {
43
+ method: string;
44
+ routePath: string;
45
+ };
46
+ export type CrossProjectRequestTarget = {
47
+ method: string;
48
+ pathname: string;
49
+ };
50
+ export type CrossProjectPolicyViolationReason = 'missing_envelope' | 'invalid_envelope' | 'missing_request_id' | 'namespace_not_allowed' | 'missing_operation_context' | 'operation_context_mismatch' | 'missing_operation_context_details' | 'invalid_operation_context_details' | 'operation_context_details_request_id_mismatch' | 'missing_operation_schema_hash' | 'missing_operation_version' | 'unknown_operation_contract' | 'operation_schema_hash_mismatch' | 'operation_version_mismatch' | 'producer_identity_mismatch';
51
+ export type CrossProjectPolicyViolation = {
52
+ code: 'BFF_CROSS_PROJECT_POLICY_DENIED';
53
+ reason: CrossProjectPolicyViolationReason;
54
+ message: string;
55
+ status: number;
56
+ };
57
+ export interface CrossProjectPolicyConfig {
58
+ enabled?: boolean;
59
+ requireEnvelope?: boolean;
60
+ requireOperationContext?: boolean;
61
+ requireOperationContextDetails?: boolean;
62
+ requireOperationSchemaHash?: boolean;
63
+ requireOperationVersion?: boolean;
64
+ allowedNamespaces?: string[];
65
+ /**
66
+ * Explicit local/demo escape hatch for legacy clients that only provide
67
+ * client-built requestId namespaces. Defaults to false. Enabling this keeps
68
+ * `allowedNamespaces` advisory and must not be used as authorization.
69
+ */
70
+ allowClientAssertedNamespace?: boolean;
71
+ envelopeHeader?: string;
72
+ operationContextHeader?: string;
73
+ operationContextDetailHeader?: string;
74
+ expectedOperationContracts?: Record<string, CrossProjectOperationContract>;
75
+ allowUnknownOperations?: boolean;
76
+ denyStatus?: number;
77
+ /**
78
+ * Server-side hook binding producer namespace to VERIFIED identity
79
+ * channel (mTLS peer, gateway-authenticated JWT, mesh identity headers).
80
+ *
81
+ * When provided, the namespace asserted by the client envelope must match
82
+ * the namespace returned by this hook, and `allowedNamespaces` is checked
83
+ * against the verified value instead of the client-asserted one. Returning
84
+ * `undefined` (identity could not be verified) denies the request.
85
+ *
86
+ * By default, `allowedNamespaces` requires this hook and fails closed
87
+ * without it. Set `allowClientAssertedNamespace` only for local/demo
88
+ * ergonomics where advisory client-asserted namespace checks are acceptable.
89
+ */
90
+ verifyProducerIdentity?: (headers: Record<string, unknown>) => string | undefined;
91
+ }
92
+ /** Serializable, fully-defaulted policy accepted by edge dispatchers. */
93
+ export type NormalizedCrossProjectPolicy = CrossProjectPolicyConfig & {
94
+ enabled: boolean;
95
+ requireEnvelope: boolean;
96
+ requireOperationContext: boolean;
97
+ requireOperationContextDetails: boolean;
98
+ requireOperationSchemaHash: boolean;
99
+ requireOperationVersion: boolean;
100
+ allowUnknownOperations: boolean;
101
+ expectedOperationContracts: Record<string, CrossProjectOperationContract>;
102
+ };
103
+ /**
104
+ * Resolves a concrete adapter request to the server-owned route template in
105
+ * the operation contract map. Effect receives requests after its BFF mount
106
+ * prefix has been stripped, so leading literal route segments may be mount
107
+ * prefixes. Ambiguous matches fail closed by retaining the concrete path.
108
+ */
109
+ export declare const resolveCrossProjectRequestObservation: (request: CrossProjectRequestTarget, policy: Pick<CrossProjectPolicyConfig, 'expectedOperationContracts'>) => CrossProjectRequestObservation | undefined;
110
+ export declare const evaluateCrossProjectPolicy: (headers: Record<string, unknown>, policy?: CrossProjectPolicyConfig, observedRequest?: CrossProjectRequestObservation) => CrossProjectPolicyViolation | null;
@@ -0,0 +1 @@
1
+ export * from './crossProjectPolicy.js';
@@ -0,0 +1,2 @@
1
+ export * from './operationContracts.js';
2
+ export * from './resolveCrossProjectPolicy.js';