@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.1 → 3.9.0-ultramodern.11

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 (184) hide show
  1. package/README.md +8 -6
  2. package/dist/cjs/bff-policy/crossProjectPolicy.js +299 -0
  3. package/dist/cjs/bff-policy/index.js +62 -0
  4. package/dist/cjs/bff-policy/node.js +69 -0
  5. package/dist/cjs/bff-policy/operationContracts.js +182 -0
  6. package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
  7. package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -8
  8. package/dist/cjs/errorResponsePlugin.js +57 -0
  9. package/dist/cjs/localisedLoaderPlugin.js +62 -0
  10. package/dist/cjs/mfCache.js +6 -0
  11. package/dist/cjs/module-federation-css/plugin.js +6 -0
  12. package/dist/cjs/module-federation-css/remote.js +2 -1
  13. package/dist/cjs/serverConfig.js +18 -0
  14. package/dist/cjs/serverPlugin.js +74 -0
  15. package/dist/cjs/static-serving/plugin.js +57 -0
  16. package/dist/cjs/static-serving/responders.js +158 -0
  17. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  18. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  19. package/dist/cjs/telemetry/exporters.js +4 -4
  20. package/dist/cjs/telemetry/healthSetup.js +14 -14
  21. package/dist/cjs/telemetry/lifecycle.js +20 -21
  22. package/dist/cjs/telemetry/plugin.js +10 -4
  23. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -2
  24. package/dist/cjs/telemetryCore.js +5 -5
  25. package/dist/esm/bff-policy/crossProjectPolicy.mjs +249 -0
  26. package/dist/esm/bff-policy/index.mjs +1 -0
  27. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -8
  28. package/dist/esm/errorResponsePlugin.mjs +19 -0
  29. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  30. package/dist/esm/mfCache.mjs +6 -0
  31. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  32. package/dist/esm/module-federation-css/remote.mjs +2 -1
  33. package/dist/esm/serverConfig.mjs +0 -0
  34. package/dist/esm/serverPlugin.mjs +34 -0
  35. package/dist/esm/telemetry/exporters.mjs +2 -2
  36. package/dist/esm/telemetry/healthSetup.mjs +14 -14
  37. package/dist/esm/telemetry/lifecycle.mjs +21 -22
  38. package/dist/esm/telemetry/plugin.mjs +9 -3
  39. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -2
  40. package/dist/esm/telemetryCore.mjs +1 -1
  41. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +250 -0
  42. package/dist/esm-node/bff-policy/index.mjs +2 -0
  43. package/dist/esm-node/bff-policy/node.mjs +3 -0
  44. package/dist/esm-node/bff-policy/operationContracts.mjs +129 -0
  45. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  46. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -8
  47. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  48. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  49. package/dist/esm-node/mfCache.mjs +6 -0
  50. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  51. package/dist/esm-node/module-federation-css/remote.mjs +2 -1
  52. package/dist/esm-node/serverConfig.mjs +1 -0
  53. package/dist/esm-node/serverPlugin.mjs +35 -0
  54. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  55. package/dist/esm-node/static-serving/responders.mjs +111 -0
  56. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  57. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  58. package/dist/esm-node/telemetry/exporters.mjs +2 -2
  59. package/dist/esm-node/telemetry/healthSetup.mjs +14 -14
  60. package/dist/esm-node/telemetry/lifecycle.mjs +21 -22
  61. package/dist/esm-node/telemetry/plugin.mjs +9 -3
  62. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -2
  63. package/dist/esm-node/telemetryCore.mjs +1 -1
  64. package/dist/types/bff-policy/crossProjectPolicy.d.ts +101 -0
  65. package/dist/types/bff-policy/index.d.ts +1 -0
  66. package/dist/types/bff-policy/node.d.ts +2 -0
  67. package/dist/types/bff-policy/operationContracts.d.ts +85 -0
  68. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  69. package/dist/types/errorResponsePlugin.d.ts +3 -0
  70. package/dist/types/index.d.ts +1 -0
  71. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  72. package/dist/types/mfCache.d.ts +2 -3
  73. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  74. package/dist/types/module-federation-css/remote.d.ts +2 -0
  75. package/dist/types/serverConfig.d.ts +17 -0
  76. package/dist/types/serverPlugin.d.ts +5 -0
  77. package/dist/types/static-serving/plugin.d.ts +3 -0
  78. package/dist/types/static-serving/responders.d.ts +2 -0
  79. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  80. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  81. package/dist/types/telemetry/exporters.d.ts +1 -1
  82. package/dist/types/telemetry/healthSetup.d.ts +3 -3
  83. package/dist/types/telemetry/lifecycle.d.ts +4 -4
  84. package/dist/types/telemetry/plugin.d.ts +2 -1
  85. package/dist/types/telemetryCore.d.ts +1 -1
  86. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  87. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  88. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +101 -0
  89. package/dist/types-esm/bff-policy/index.d.mts +1 -0
  90. package/dist/types-esm/bff-policy/node.d.mts +2 -0
  91. package/dist/types-esm/bff-policy/operationContracts.d.mts +85 -0
  92. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  93. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  94. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  95. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  96. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  97. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  98. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  99. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  100. package/dist/types-esm/env.d.mts +40 -0
  101. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  102. package/dist/types-esm/index.d.mts +8 -0
  103. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  104. package/dist/types-esm/mfCache.d.mts +26 -0
  105. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  106. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  107. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  108. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  109. package/dist/types-esm/module-federation-css/remote.d.mts +22 -0
  110. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  111. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  112. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  113. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  114. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  115. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  116. package/dist/types-esm/serverConfig.d.mts +17 -0
  117. package/dist/types-esm/serverPlugin.d.mts +5 -0
  118. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  119. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  120. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  121. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  122. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  123. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  124. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  125. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  126. package/dist/types-esm/telemetry/healthSetup.d.mts +17 -0
  127. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  128. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  129. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  130. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  131. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  132. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +35 -0
  133. package/dist/types-esm/telemetry.d.mts +1 -0
  134. package/dist/types-esm/telemetryCore.d.mts +6 -0
  135. package/package.json +159 -27
  136. package/rslib.config.mts +36 -2
  137. package/rstest.config.mts +11 -0
  138. package/src/bff-policy/crossProjectPolicy.ts +754 -0
  139. package/src/bff-policy/index.ts +1 -0
  140. package/src/bff-policy/node.ts +2 -0
  141. package/src/bff-policy/operationContracts.ts +298 -0
  142. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  143. package/src/contract-gate-snapshot-store/http-store.ts +1 -11
  144. package/src/errorResponsePlugin.ts +21 -0
  145. package/src/index.ts +4 -0
  146. package/src/localisedLoaderPlugin.ts +34 -0
  147. package/src/mfCache.ts +4 -3
  148. package/src/module-federation-css/plugin.ts +4 -3
  149. package/src/module-federation-css/remote.ts +3 -1
  150. package/src/serverConfig.ts +32 -0
  151. package/src/serverPlugin.ts +38 -0
  152. package/src/static-serving/plugin.ts +16 -0
  153. package/src/static-serving/responders.ts +208 -0
  154. package/src/static-serving/staticModuleFederation.ts +255 -0
  155. package/src/static-serving/staticPrecompressed.ts +193 -0
  156. package/src/telemetry/exporters.ts +1 -1
  157. package/src/telemetry/healthSetup.ts +17 -20
  158. package/src/telemetry/lifecycle.ts +27 -39
  159. package/src/telemetry/plugin.ts +6 -4
  160. package/src/telemetry/runtimeEndpoints.ts +3 -2
  161. package/src/telemetryCore.ts +1 -1
  162. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +450 -0
  163. package/tests/bff-policy/crossProjectPolicy.test.ts +197 -0
  164. package/tests/bff-policy/operationContracts.test.ts +221 -0
  165. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  166. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +76 -0
  167. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  168. package/tests/contractGateSnapshotStore.test.ts +0 -51
  169. package/tests/env.test.ts +45 -64
  170. package/tests/localisedLoader.test.ts +120 -0
  171. package/tests/mfCache.test.ts +1 -88
  172. package/tests/moduleFederationCss.test.ts +98 -41
  173. package/tests/nativeErrorResponse.test.ts +118 -0
  174. package/tests/nativeServerAssembly.test.ts +385 -0
  175. package/tests/runtimeLifecycle.test.ts +69 -17
  176. package/tests/static-serving/ordering.test.ts +214 -0
  177. package/tests/static-serving/static.test.ts +411 -0
  178. package/tests/telemetry.test.ts +35 -198
  179. package/tests/telemetryHealthMonitor.test.ts +0 -4
  180. package/tests/telemetryHealthObservation.test.ts +302 -0
  181. package/tests/telemetryLifecycle.test.ts +7 -303
  182. package/tests/telemetryRegistryQueueMatrix.test.ts +14 -111
  183. package/tests/registration.test.ts +0 -112
  184. package/tests/telemetryAutopilot.test.ts +0 -1134
@@ -0,0 +1,250 @@
1
+ import "node:module";
2
+ const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
3
+ const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
4
+ const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
5
+ const DEFAULT_DENY_STATUS = 403;
6
+ const NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE = 'cross-project namespace allowlist requires verifyProducerIdentity';
7
+ const splitRoutePath = (routePath)=>routePath.split('/').filter(Boolean);
8
+ const isDynamicRouteSegment = (segment)=>segment.startsWith(':') || '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
9
+ const hasTrailingSlash = (routePath)=>routePath.length > 1 && routePath.endsWith('/');
10
+ const hasUnsafePathEncoding = (requestPath)=>{
11
+ let decoded = requestPath;
12
+ for(let depth = 0; depth < 8; depth += 1){
13
+ if (/%(?:2f|5c)/i.test(decoded)) return true;
14
+ try {
15
+ const next = decodeURIComponent(decoded);
16
+ if (next === decoded) return false;
17
+ decoded = next;
18
+ } catch {
19
+ return true;
20
+ }
21
+ }
22
+ return decoded.includes('%');
23
+ };
24
+ const routeSegmentsMatch = (templateSegments, requestSegments)=>{
25
+ let templateIndex = 0;
26
+ let requestIndex = 0;
27
+ while(templateIndex < templateSegments.length){
28
+ const segment = templateSegments[templateIndex];
29
+ const wildcard = '*' === segment || segment.startsWith('*') || segment.startsWith('{*');
30
+ const optional = segment.startsWith(':') && segment.endsWith('?');
31
+ if (templateIndex < templateSegments.length - 1 && (wildcard || optional)) return false;
32
+ if (wildcard) return true;
33
+ const requestSegment = requestSegments[requestIndex];
34
+ if (void 0 === requestSegment) return optional && templateIndex === templateSegments.length - 1;
35
+ if (!segment.startsWith(':') && segment !== requestSegment) return false;
36
+ templateIndex += 1;
37
+ requestIndex += 1;
38
+ }
39
+ return requestIndex === requestSegments.length;
40
+ };
41
+ const routeTemplateMatchScore = (routePath, requestPath)=>{
42
+ if (hasTrailingSlash(routePath) !== hasTrailingSlash(requestPath)) return;
43
+ const templateSegments = splitRoutePath(routePath);
44
+ const requestSegments = splitRoutePath(requestPath);
45
+ for(let prefixLength = 0; prefixLength <= templateSegments.length; prefixLength += 1){
46
+ const removedPrefix = templateSegments.slice(0, prefixLength);
47
+ if (removedPrefix.some(isDynamicRouteSegment)) break;
48
+ const mountedTemplate = templateSegments.slice(prefixLength);
49
+ if (!routeSegmentsMatch(mountedTemplate, requestSegments)) continue;
50
+ const literalSegments = mountedTemplate.filter((segment)=>!isDynamicRouteSegment(segment)).length;
51
+ const dynamicSegments = mountedTemplate.length - literalSegments;
52
+ return (0 === prefixLength ? 1000000 : 0) + 10000 * literalSegments - 100 * dynamicSegments - prefixLength;
53
+ }
54
+ };
55
+ const resolveCrossProjectRequestObservation = (request, policy)=>{
56
+ const requestMethod = String(request.method || '').trim().toUpperCase();
57
+ const routePaths = [
58
+ ...new Set(Object.keys(policy.expectedOperationContracts ?? {}).flatMap((key)=>{
59
+ if (key.startsWith('operation:')) return [];
60
+ const separator = key.indexOf(':');
61
+ if (-1 === separator || key.slice(0, separator).trim().toUpperCase() !== requestMethod) return [];
62
+ return [
63
+ key.slice(separator + 1)
64
+ ];
65
+ }))
66
+ ];
67
+ if (0 === routePaths.length) return;
68
+ if (hasUnsafePathEncoding(request.pathname)) return {
69
+ method: request.method,
70
+ routePath: request.pathname
71
+ };
72
+ const matches = routePaths.flatMap((routePath)=>{
73
+ const score = routeTemplateMatchScore(routePath, request.pathname);
74
+ return void 0 === score ? [] : [
75
+ {
76
+ routePath,
77
+ score
78
+ }
79
+ ];
80
+ });
81
+ if (0 === matches.length) return {
82
+ method: request.method,
83
+ routePath: request.pathname
84
+ };
85
+ matches.sort((left, right)=>right.score - left.score);
86
+ return {
87
+ method: request.method,
88
+ routePath: matches[1]?.score === matches[0]?.score ? request.pathname : matches[0].routePath
89
+ };
90
+ };
91
+ const normalizeHeaderName = (headerName, fallback)=>(headerName || fallback).trim().toLowerCase();
92
+ const normalizeStatusCode = (statusCode)=>{
93
+ if ('number' == typeof statusCode && Number.isFinite(statusCode) && statusCode >= 400 && statusCode <= 599) return Math.floor(statusCode);
94
+ return DEFAULT_DENY_STATUS;
95
+ };
96
+ const readHeader = (headers, headerName)=>{
97
+ const lowerHeaderName = headerName.toLowerCase();
98
+ for (const [name, value] of Object.entries(headers || {}))if (name.toLowerCase() === lowerHeaderName) {
99
+ if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : void 0;
100
+ if (null == value) return;
101
+ return String(value);
102
+ }
103
+ };
104
+ const extractNamespace = (requestId)=>requestId.split(/[/:.]/)[0]?.trim().toLowerCase();
105
+ const createViolation = (reason, message, status)=>({
106
+ code: 'BFF_CROSS_PROJECT_POLICY_DENIED',
107
+ reason,
108
+ message,
109
+ status
110
+ });
111
+ const createCrossProjectPolicyEvaluationState = (headers, policy, observedRequest)=>({
112
+ headers,
113
+ policy,
114
+ status: normalizeStatusCode(policy.denyStatus),
115
+ requireEnvelope: policy.requireEnvelope ?? true,
116
+ requireOperationContext: policy.requireOperationContext ?? true,
117
+ requireOperationContextDetails: policy.requireOperationContextDetails ?? true,
118
+ requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
119
+ requireOperationVersion: policy.requireOperationVersion ?? true,
120
+ allowUnknownOperations: policy.allowUnknownOperations ?? false,
121
+ verifyProducerIdentity: 'function' == typeof policy.verifyProducerIdentity ? policy.verifyProducerIdentity : void 0,
122
+ allowedNamespaces: (policy.allowedNamespaces || []).map((item)=>item.trim().toLowerCase()).filter(Boolean),
123
+ envelopeHeader: normalizeHeaderName(policy.envelopeHeader, BFF_ENVELOPE_HEADER),
124
+ operationContextHeader: normalizeHeaderName(policy.operationContextHeader, BFF_OPERATION_CONTEXT_HEADER),
125
+ operationContextDetailHeader: normalizeHeaderName(policy.operationContextDetailHeader, BFF_OPERATION_CONTEXT_DETAIL_HEADER),
126
+ requestId: '',
127
+ detailSchemaHash: '',
128
+ detailOperationVersion: void 0,
129
+ observedRequest: observedRequest ? {
130
+ method: String(observedRequest.method || '').trim().toUpperCase(),
131
+ routePath: String(observedRequest.routePath || '').trim()
132
+ } : void 0,
133
+ complete: false
134
+ });
135
+ const checkNamespaceAllowlistVerifier = (state)=>{
136
+ if (state.allowedNamespaces.length > 0 && void 0 === state.verifyProducerIdentity) return createViolation('producer_identity_mismatch', NAMESPACE_ALLOWLIST_REQUIRES_VERIFIER_MESSAGE, state.status);
137
+ };
138
+ const checkEnvelopeHeader = (state)=>{
139
+ const envelopeRaw = readHeader(state.headers, state.envelopeHeader);
140
+ if (!envelopeRaw) {
141
+ if (!state.requireEnvelope) {
142
+ state.complete = true;
143
+ return;
144
+ }
145
+ return createViolation('missing_envelope', `Missing cross-project envelope header "${state.envelopeHeader}"`, state.status);
146
+ }
147
+ let envelope;
148
+ try {
149
+ const parsed = JSON.parse(envelopeRaw);
150
+ if (!parsed || 'object' != typeof parsed) throw new Error('invalid envelope object');
151
+ envelope = parsed;
152
+ } catch (_error) {
153
+ return createViolation('invalid_envelope', `Invalid cross-project envelope header "${state.envelopeHeader}"`, state.status);
154
+ }
155
+ const requestId = String(envelope.requestId || '').trim();
156
+ if (!requestId) return createViolation('missing_request_id', 'Cross-project envelope does not include a valid requestId', state.status);
157
+ state.requestId = requestId;
158
+ state.claimedNamespace = extractNamespace(requestId);
159
+ state.effectiveNamespace = state.claimedNamespace;
160
+ };
161
+ const checkProducerIdentity = (state)=>{
162
+ if (!state.verifyProducerIdentity) return;
163
+ const verifiedNamespaceRaw = state.verifyProducerIdentity(state.headers);
164
+ const verifiedNamespace = 'string' == typeof verifiedNamespaceRaw ? verifiedNamespaceRaw.trim().toLowerCase() : void 0;
165
+ if (!verifiedNamespace) return createViolation('producer_identity_mismatch', 'Producer identity could not be verified for request', state.status);
166
+ if (verifiedNamespace !== state.claimedNamespace) return createViolation('producer_identity_mismatch', `Envelope namespace "${state.claimedNamespace || 'unknown'}" does not match verified producer identity "${verifiedNamespace}"`, state.status);
167
+ state.effectiveNamespace = verifiedNamespace;
168
+ };
169
+ const checkNamespaceAllowlist = (state)=>{
170
+ if (state.allowedNamespaces.length > 0) {
171
+ if (!state.effectiveNamespace || !state.allowedNamespaces.includes(state.effectiveNamespace)) return createViolation('namespace_not_allowed', `Producer namespace "${state.effectiveNamespace || 'unknown'}" not allowed`, state.status);
172
+ }
173
+ };
174
+ const checkOperationContext = (state)=>{
175
+ if (!state.requireOperationContext) {
176
+ state.complete = true;
177
+ return;
178
+ }
179
+ const operationContext = readHeader(state.headers, state.operationContextHeader);
180
+ if (!operationContext) return createViolation('missing_operation_context', `Missing operation context header "${state.operationContextHeader}"`, state.status);
181
+ if (!operationContext.startsWith(`${state.requestId}:`)) return createViolation('operation_context_mismatch', `Operation context header "${state.operationContextHeader}" does not match requestId "${state.requestId}"`, state.status);
182
+ state.operationContext = operationContext;
183
+ };
184
+ const checkOperationContextDetails = (state)=>{
185
+ const operationContextDetailsRaw = readHeader(state.headers, state.operationContextDetailHeader);
186
+ if (!operationContextDetailsRaw) {
187
+ if (state.requireOperationContextDetails) return createViolation('missing_operation_context_details', `Missing operation context details header "${state.operationContextDetailHeader}"`, state.status);
188
+ state.complete = true;
189
+ return;
190
+ }
191
+ let operationContextDetails;
192
+ try {
193
+ const parsed = JSON.parse(operationContextDetailsRaw);
194
+ if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) throw new Error('invalid operation context details object');
195
+ operationContextDetails = parsed;
196
+ } catch (_error) {
197
+ return createViolation('invalid_operation_context_details', `Invalid operation context details header "${state.operationContextDetailHeader}"`, state.status);
198
+ }
199
+ const detailRequestId = String(operationContextDetails.requestId || '').trim();
200
+ if (detailRequestId && detailRequestId !== state.requestId) return createViolation('operation_context_details_request_id_mismatch', `Operation context details requestId "${detailRequestId}" does not match envelope requestId "${state.requestId}"`, state.status);
201
+ const detailOperationId = String(operationContextDetails.operationId || '').trim();
202
+ if (state.operationContext && detailOperationId && detailOperationId !== state.operationContext) return createViolation('operation_context_mismatch', `Operation context details operationId "${detailOperationId}" does not match operation context "${state.operationContext}"`, state.status);
203
+ state.operationContextDetails = operationContextDetails;
204
+ state.detailSchemaHash = String(operationContextDetails.schemaHash || '').trim();
205
+ if (state.requireOperationSchemaHash && !state.detailSchemaHash) return createViolation('missing_operation_schema_hash', `Operation context details header "${state.operationContextDetailHeader}" must include schemaHash`, state.status);
206
+ state.detailOperationVersion = operationContextDetails.operationVersion;
207
+ if (state.requireOperationVersion && 'number' != typeof state.detailOperationVersion) return createViolation('missing_operation_version', `Operation context details header "${state.operationContextDetailHeader}" must include operationVersion`, state.status);
208
+ };
209
+ const checkOperationContract = (state)=>{
210
+ if (!state.operationContextDetails) return;
211
+ const expectedContracts = state.policy.expectedOperationContracts;
212
+ if (expectedContracts && 'object' == typeof expectedContracts) {
213
+ const method = String(state.operationContextDetails.method || '').toUpperCase();
214
+ const routePath = String(state.operationContextDetails.routePath || '').trim();
215
+ const operationId = String(state.operationContextDetails.operationId || '').trim();
216
+ const observedMethod = state.observedRequest?.method;
217
+ const observedRoutePath = state.observedRequest?.routePath;
218
+ if (observedMethod && observedRoutePath && (method !== observedMethod || routePath !== observedRoutePath)) return createViolation('operation_context_mismatch', `Client operation "${operationId || `${method}:${routePath}`}" does not match observed request "${observedMethod}:${observedRoutePath}"`, state.status);
219
+ const contractMethod = observedMethod || method;
220
+ const contractRoutePath = observedRoutePath || routePath;
221
+ const expectedContract = expectedContracts[`${contractMethod}:${contractRoutePath}`] || (state.observedRequest ? void 0 : expectedContracts[`operation:${operationId}`]);
222
+ if (expectedContract) {
223
+ const assertedOperationId = operationId || state.operationContext || '';
224
+ const canonicalRouteOperationId = `${state.requestId}:${contractMethod}:${contractRoutePath}`;
225
+ if (state.observedRequest && assertedOperationId !== expectedContract.operationId && assertedOperationId !== canonicalRouteOperationId) return createViolation('operation_context_mismatch', `Client operation "${assertedOperationId}" does not identify observed contract "${expectedContract.operationId || canonicalRouteOperationId}"`, state.status);
226
+ if (expectedContract.schemaHash && state.detailSchemaHash && expectedContract.schemaHash !== state.detailSchemaHash) return createViolation('operation_schema_hash_mismatch', `Operation schema hash mismatch for "${operationId || `${method}:${routePath}`}"`, state.status);
227
+ if ('number' == typeof expectedContract.operationVersion && 'number' == typeof state.detailOperationVersion && expectedContract.operationVersion !== state.detailOperationVersion) return createViolation('operation_version_mismatch', `Operation version mismatch for "${operationId || `${method}:${routePath}`}"`, state.status);
228
+ } else if (!state.allowUnknownOperations) return createViolation('unknown_operation_contract', `No expected operation contract found for operation "${operationId || `${method}:${routePath}`}"`, state.status);
229
+ }
230
+ };
231
+ const CROSS_PROJECT_POLICY_CHECKS = [
232
+ checkNamespaceAllowlistVerifier,
233
+ checkEnvelopeHeader,
234
+ checkProducerIdentity,
235
+ checkNamespaceAllowlist,
236
+ checkOperationContext,
237
+ checkOperationContextDetails,
238
+ checkOperationContract
239
+ ];
240
+ const evaluateCrossProjectPolicy = (headers, policy, observedRequest)=>{
241
+ if (!policy?.enabled) return null;
242
+ const state = createCrossProjectPolicyEvaluationState(headers, policy, observedRequest);
243
+ for (const check of CROSS_PROJECT_POLICY_CHECKS){
244
+ const violation = check(state);
245
+ if (violation) return violation;
246
+ if (state.complete) break;
247
+ }
248
+ return null;
249
+ };
250
+ export { BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, evaluateCrossProjectPolicy, resolveCrossProjectRequestObservation };
@@ -0,0 +1,2 @@
1
+ import "node:module";
2
+ export * from "./crossProjectPolicy.mjs";
@@ -0,0 +1,3 @@
1
+ import "node:module";
2
+ export * from "./operationContracts.mjs";
3
+ export * from "./resolveCrossProjectPolicy.mjs";
@@ -0,0 +1,129 @@
1
+ import "node:module";
2
+ import { createRequire } from "node:module";
3
+ import { createHash } from "crypto";
4
+ import "reflect-metadata";
5
+ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
6
+ var __rspack_import_meta_filename__ = __rspack_fileURLToPath(import.meta.url);
7
+ const DEFAULT_OPERATION_VERSION = 1;
8
+ const deriveOperationVersion = (packageVersion)=>{
9
+ if ('string' != typeof packageVersion) return DEFAULT_OPERATION_VERSION;
10
+ const match = packageVersion.trim().match(/^v?(\d+)\./);
11
+ if (!match) return DEFAULT_OPERATION_VERSION;
12
+ const major = Number.parseInt(match[1], 10);
13
+ return Number.isInteger(major) && major >= 0 ? major : DEFAULT_OPERATION_VERSION;
14
+ };
15
+ const stableStringify = (value)=>{
16
+ if (Array.isArray(value)) return `[${value.map((item)=>stableStringify(item)).join(',')}]`;
17
+ if (value && 'object' == typeof value) {
18
+ const entries = Object.entries(value).filter(([, entryValue])=>void 0 !== entryValue).sort(([a], [b])=>a.localeCompare(b)).map(([key, entryValue])=>`${JSON.stringify(key)}:${stableStringify(entryValue)}`);
19
+ return `{${entries.join(',')}}`;
20
+ }
21
+ return JSON.stringify(value) ?? 'null';
22
+ };
23
+ const sha256 = (text)=>createHash('sha256').update(text).digest('hex');
24
+ let cachedZodToJSONSchema;
25
+ const ZOD_SPECIFIER = "zod";
26
+ const resolveZodToJSONSchema = ()=>{
27
+ if (void 0 !== cachedZodToJSONSchema) return cachedZodToJSONSchema;
28
+ try {
29
+ const load = createRequire(__rspack_import_meta_filename__);
30
+ const zod = load(ZOD_SPECIFIER);
31
+ const candidate = zod?.toJSONSchema ?? zod?.z?.toJSONSchema;
32
+ cachedZodToJSONSchema = 'function' == typeof candidate ? candidate : null;
33
+ } catch {
34
+ cachedZodToJSONSchema = null;
35
+ }
36
+ return cachedZodToJSONSchema;
37
+ };
38
+ const INPUT_SCHEMA_METADATA_KEYS = [
39
+ 'DATA',
40
+ 'QUERY',
41
+ 'PARAMS',
42
+ 'HEADERS',
43
+ 'Files'
44
+ ];
45
+ const serializeSchema = (schema)=>{
46
+ const toJSONSchema = resolveZodToJSONSchema();
47
+ if (toJSONSchema) try {
48
+ return toJSONSchema(schema, {
49
+ io: 'input',
50
+ unrepresentable: 'any'
51
+ });
52
+ } catch {}
53
+ return {
54
+ __unserializableSchema: true
55
+ };
56
+ };
57
+ const serializeOperationSchemas = (handler)=>{
58
+ if ('function' != typeof handler) return;
59
+ const serialized = {};
60
+ for (const metadataKey of INPUT_SCHEMA_METADATA_KEYS){
61
+ let schema;
62
+ try {
63
+ schema = Reflect.getMetadata(metadataKey, handler);
64
+ } catch {
65
+ schema = void 0;
66
+ }
67
+ if (null != schema) serialized[metadataKey] = serializeSchema(schema);
68
+ }
69
+ return Object.keys(serialized).length > 0 ? serialized : void 0;
70
+ };
71
+ const createOperationContractHash = (operation, requestId)=>sha256(stableStringify({
72
+ httpMethod: String(operation.httpMethod || '').toUpperCase(),
73
+ name: operation.name,
74
+ requestId,
75
+ routePath: operation.routePath,
76
+ ...operation.schemas ? {
77
+ schemas: operation.schemas
78
+ } : {}
79
+ }));
80
+ const createOperationEntries = (handlers)=>handlers.map((item)=>({
81
+ name: item.name,
82
+ httpMethod: String(item.httpMethod || '').toUpperCase(),
83
+ routePath: item.routePath
84
+ })).sort((a, b)=>{
85
+ const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
86
+ const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
87
+ return keyA.localeCompare(keyB);
88
+ });
89
+ const createOperationSchemaHash = (operationEntries, requestId)=>sha256(stableStringify({
90
+ operations: [
91
+ ...operationEntries
92
+ ].map((item)=>({
93
+ hash: item.schemaHash ?? createOperationContractHash({
94
+ name: item.name,
95
+ httpMethod: item.httpMethod,
96
+ routePath: item.routePath
97
+ }, requestId)
98
+ })).sort((a, b)=>a.hash.localeCompare(b.hash)),
99
+ requestId
100
+ }));
101
+ const buildOperationContractMap = ({ handlers, requestId, operationVersion })=>{
102
+ const normalizedRequestId = 'string' == typeof requestId && requestId.trim().length > 0 ? requestId.trim() : 'default';
103
+ const normalizedOperationVersion = 'number' == typeof operationVersion && Number.isInteger(operationVersion) ? operationVersion : DEFAULT_OPERATION_VERSION;
104
+ const contracts = {};
105
+ handlers.forEach((item)=>{
106
+ const httpMethod = String(item.httpMethod || '').toUpperCase();
107
+ const schemaHash = createOperationContractHash({
108
+ name: item.name,
109
+ httpMethod,
110
+ routePath: item.routePath,
111
+ schemas: serializeOperationSchemas(item.handler)
112
+ }, normalizedRequestId);
113
+ const operationId = `${normalizedRequestId}:${item.name}`;
114
+ const contract = {
115
+ requestId: normalizedRequestId,
116
+ operationVersion: normalizedOperationVersion,
117
+ schemaHash,
118
+ method: httpMethod,
119
+ routePath: item.routePath,
120
+ operationId,
121
+ handlerName: item.name,
122
+ filename: item.filename
123
+ };
124
+ contracts[`${httpMethod}:${item.routePath}`] = contract;
125
+ contracts[`operation:${operationId}`] = contract;
126
+ });
127
+ return contracts;
128
+ };
129
+ export { DEFAULT_OPERATION_VERSION, buildOperationContractMap, createOperationContractHash, createOperationEntries, createOperationSchemaHash, deriveOperationVersion, serializeOperationSchemas };
@@ -0,0 +1,28 @@
1
+ import "node:module";
2
+ import { buildOperationContractMap } from "./operationContracts.mjs";
3
+ const resolveCrossProjectPolicy = (input)=>{
4
+ const { crossProjectPolicy, handlers, requestId, isCrossProjectServer, operationVersion } = input;
5
+ if (!crossProjectPolicy && !isCrossProjectServer) return;
6
+ const policy = crossProjectPolicy ?? {};
7
+ const effectiveRequestId = 'string' == typeof requestId && requestId.trim().length > 0 ? requestId : 'default';
8
+ const generatedContracts = buildOperationContractMap({
9
+ handlers,
10
+ requestId: effectiveRequestId,
11
+ operationVersion
12
+ });
13
+ return {
14
+ ...policy,
15
+ enabled: policy.enabled ?? Boolean(isCrossProjectServer),
16
+ requireEnvelope: policy.requireEnvelope ?? true,
17
+ requireOperationContext: policy.requireOperationContext ?? true,
18
+ requireOperationContextDetails: policy.requireOperationContextDetails ?? true,
19
+ requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
20
+ requireOperationVersion: policy.requireOperationVersion ?? true,
21
+ allowUnknownOperations: policy.allowUnknownOperations ?? false,
22
+ expectedOperationContracts: {
23
+ ...policy.expectedOperationContracts ?? {},
24
+ ...generatedContracts
25
+ }
26
+ };
27
+ };
28
+ export { resolveCrossProjectPolicy };
@@ -2,13 +2,6 @@ import "node:module";
2
2
  import { normalizeSnapshot } from "./resolve.mjs";
3
3
  import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./types.mjs";
4
4
  const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5000;
5
- const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
6
- 'http',
7
- '@modern-js/server-core/http',
8
- '@modern-js/server-core/contract-gate-http-store',
9
- '@modern-js/server-runtime-extensions/http',
10
- '@modern-js/server-runtime-extensions/contract-gate-http-store'
11
- ]);
12
5
  const normalizeHttpStoreOptions = (options)=>{
13
6
  const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
14
7
  if (!endpoint) throw new Error('[telemetry.health.snapshot] HTTP stateStore requires options.endpoint');
@@ -87,7 +80,7 @@ const createHttpContractGateSnapshotStore = (options)=>{
87
80
  };
88
81
  const tryResolveBuiltinSnapshotStore = (input)=>{
89
82
  const moduleName = input.stateStore.module.trim();
90
- if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) return;
83
+ if ('http' !== moduleName) return;
91
84
  return createHttpContractGateSnapshotStore(input.stateStore.options || {});
92
85
  };
93
86
  export { createHttpContractGateSnapshotStore, tryResolveBuiltinSnapshotStore };
@@ -0,0 +1,20 @@
1
+ import "node:module";
2
+ import { createSafeJsonFailureResponse } from "@modern-js/runtime-extensions/safe-failure";
3
+ const injectErrorResponsePlugin = ()=>({
4
+ name: '@modern-js/safe-error-response',
5
+ setup (api) {
6
+ api.handleError(async (input, next)=>{
7
+ const prefix = api.getServerConfig().bff?.prefix || '/api';
8
+ const prefixes = Array.isArray(prefix) ? prefix : [
9
+ prefix
10
+ ];
11
+ if (prefixes.some((value)=>input.context.req.path.startsWith(value))) return {
12
+ ...input,
13
+ response: createSafeJsonFailureResponse(input.error)
14
+ };
15
+ next?.(input);
16
+ return input;
17
+ });
18
+ }
19
+ });
20
+ export { injectErrorResponsePlugin };
@@ -0,0 +1,25 @@
1
+ import "node:module";
2
+ import { setLoaderRouteIdResolver } from "@modern-js/plugin-data-loader/runtime";
3
+ import { resolveLocalisedLoaderRouteId } from "@modern-js/runtime-extensions/localised-loader-identity";
4
+ import { getLoaderCtx } from "@modern-js/server-core";
5
+ function injectLocalisedLoaderPlugin() {
6
+ return {
7
+ name: '@modern-js/localised-loader',
8
+ setup (api) {
9
+ const handler = async (context, next)=>{
10
+ setLoaderRouteIdResolver(getLoaderCtx(context), (requestedRouteId, { routes, matchedRouteIds })=>resolveLocalisedLoaderRouteId(routes, requestedRouteId, matchedRouteIds));
11
+ await next();
12
+ };
13
+ api.onPrepare(()=>{
14
+ api.getServerContext().middlewares.push({
15
+ name: 'localised-loader-route-id',
16
+ before: [
17
+ 'render'
18
+ ],
19
+ handler
20
+ });
21
+ });
22
+ }
23
+ };
24
+ }
25
+ export { injectLocalisedLoaderPlugin };
@@ -35,6 +35,12 @@ function resolveMfAssetCacheHeaders(url, query = {}) {
35
35
  }
36
36
  const injectMfAssetCacheHeadersPlugin = ()=>({
37
37
  name: '@modern-js/inject-mf-asset-cache-headers',
38
+ pre: [
39
+ '@modern-js/inject-module-federation-css'
40
+ ],
41
+ post: [
42
+ '@modern-js/plugin-inject-rsc-manifest'
43
+ ],
38
44
  setup (api) {
39
45
  api.onPrepare(()=>{
40
46
  const { middlewares } = api.getServerContext();
@@ -3,6 +3,12 @@ import { isProd } from "@modern-js/utils";
3
3
  import { DEFAULT_REMOTE_CSS_CACHE_TTL_MS, createModuleFederationCssCollector } from "./collector.mjs";
4
4
  const injectModuleFederationCssPlugin = (options = {})=>({
5
5
  name: '@modern-js/inject-module-federation-css',
6
+ pre: [
7
+ '@modern-js/plugin-inject-resource'
8
+ ],
9
+ post: [
10
+ '@modern-js/plugin-inject-rsc-manifest'
11
+ ],
6
12
  setup (api) {
7
13
  api.onPrepare(()=>{
8
14
  const { middlewares, distDirectory: pwd } = api.getServerContext();
@@ -7,7 +7,8 @@ const fetchJsonWithTimeout = async (url, fetcher, timeout)=>{
7
7
  try {
8
8
  const response = await Promise.race([
9
9
  fetcher(url, {
10
- signal: controller.signal
10
+ signal: controller.signal,
11
+ redirect: 'error'
11
12
  }),
12
13
  new Promise((_, reject)=>{
13
14
  timeoutId = setTimeout(()=>{
@@ -0,0 +1 @@
1
+ import "node:module";
@@ -0,0 +1,35 @@
1
+ import "node:module";
2
+ import "./serverConfig.mjs";
3
+ import { injectErrorResponsePlugin } from "./errorResponsePlugin.mjs";
4
+ import { injectLocalisedLoaderPlugin } from "./localisedLoaderPlugin.mjs";
5
+ import { injectMfAssetCacheHeadersPlugin } from "./mfCache.mjs";
6
+ import { injectModuleFederationCssPlugin } from "./module-federation-css/plugin.mjs";
7
+ import { disposeServerRuntime } from "./runtimeLifecycle.mjs";
8
+ import { injectStaticServingPlugin } from "./static-serving/plugin.mjs";
9
+ import { injectTelemetryPlugin } from "./telemetry/plugin.mjs";
10
+ const ultramodernServerPlugin = ()=>({
11
+ name: '@modern-js/ultramodern-server',
12
+ usePlugins: [
13
+ injectLocalisedLoaderPlugin(),
14
+ injectErrorResponsePlugin(),
15
+ injectTelemetryPlugin(),
16
+ injectModuleFederationCssPlugin(),
17
+ injectMfAssetCacheHeadersPlugin(),
18
+ injectStaticServingPlugin(),
19
+ {
20
+ name: '@modern-js/server-runtime-lifecycle',
21
+ pre: [
22
+ '@modern-js/inject-telemetry'
23
+ ],
24
+ setup (api) {
25
+ api.onDispose(()=>{
26
+ const { serverBase } = api.getServerContext();
27
+ if (serverBase) return disposeServerRuntime(serverBase);
28
+ });
29
+ }
30
+ }
31
+ ]
32
+ });
33
+ const serverPlugin = ultramodernServerPlugin;
34
+ export default serverPlugin;
35
+ export { ultramodernServerPlugin };
@@ -0,0 +1,18 @@
1
+ import "node:module";
2
+ import { createStaticExtensionResponders } from "./responders.mjs";
3
+ function injectStaticServingPlugin() {
4
+ return {
5
+ name: '@modern-js/server-static-extensions',
6
+ post: [
7
+ '@modern-js/plugin-server-static'
8
+ ],
9
+ setup (api) {
10
+ api.updateServerContext({
11
+ staticAssetResponders: createStaticExtensionResponders()
12
+ });
13
+ }
14
+ };
15
+ }
16
+ const static_serving_plugin = injectStaticServingPlugin;
17
+ export default static_serving_plugin;
18
+ export { injectStaticServingPlugin };