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

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 (179) hide show
  1. package/README.md +5 -5
  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/serverConfig.js +18 -0
  13. package/dist/cjs/serverPlugin.js +74 -0
  14. package/dist/cjs/static-serving/plugin.js +57 -0
  15. package/dist/cjs/static-serving/responders.js +158 -0
  16. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  17. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  18. package/dist/cjs/telemetry/exporters.js +4 -4
  19. package/dist/cjs/telemetry/healthSetup.js +14 -14
  20. package/dist/cjs/telemetry/lifecycle.js +20 -21
  21. package/dist/cjs/telemetry/plugin.js +10 -4
  22. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -2
  23. package/dist/cjs/telemetryCore.js +5 -5
  24. package/dist/esm/bff-policy/crossProjectPolicy.mjs +249 -0
  25. package/dist/esm/bff-policy/index.mjs +1 -0
  26. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -8
  27. package/dist/esm/errorResponsePlugin.mjs +19 -0
  28. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  29. package/dist/esm/mfCache.mjs +6 -0
  30. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  31. package/dist/esm/serverConfig.mjs +0 -0
  32. package/dist/esm/serverPlugin.mjs +34 -0
  33. package/dist/esm/telemetry/exporters.mjs +2 -2
  34. package/dist/esm/telemetry/healthSetup.mjs +14 -14
  35. package/dist/esm/telemetry/lifecycle.mjs +21 -22
  36. package/dist/esm/telemetry/plugin.mjs +9 -3
  37. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -2
  38. package/dist/esm/telemetryCore.mjs +1 -1
  39. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +250 -0
  40. package/dist/esm-node/bff-policy/index.mjs +2 -0
  41. package/dist/esm-node/bff-policy/node.mjs +3 -0
  42. package/dist/esm-node/bff-policy/operationContracts.mjs +129 -0
  43. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  44. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -8
  45. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  46. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  47. package/dist/esm-node/mfCache.mjs +6 -0
  48. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  49. package/dist/esm-node/serverConfig.mjs +1 -0
  50. package/dist/esm-node/serverPlugin.mjs +35 -0
  51. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  52. package/dist/esm-node/static-serving/responders.mjs +111 -0
  53. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  54. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  55. package/dist/esm-node/telemetry/exporters.mjs +2 -2
  56. package/dist/esm-node/telemetry/healthSetup.mjs +14 -14
  57. package/dist/esm-node/telemetry/lifecycle.mjs +21 -22
  58. package/dist/esm-node/telemetry/plugin.mjs +9 -3
  59. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -2
  60. package/dist/esm-node/telemetryCore.mjs +1 -1
  61. package/dist/types/bff-policy/crossProjectPolicy.d.ts +101 -0
  62. package/dist/types/bff-policy/index.d.ts +1 -0
  63. package/dist/types/bff-policy/node.d.ts +2 -0
  64. package/dist/types/bff-policy/operationContracts.d.ts +85 -0
  65. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  66. package/dist/types/errorResponsePlugin.d.ts +3 -0
  67. package/dist/types/index.d.ts +1 -0
  68. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  69. package/dist/types/mfCache.d.ts +2 -3
  70. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  71. package/dist/types/serverConfig.d.ts +17 -0
  72. package/dist/types/serverPlugin.d.ts +5 -0
  73. package/dist/types/static-serving/plugin.d.ts +3 -0
  74. package/dist/types/static-serving/responders.d.ts +2 -0
  75. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  76. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  77. package/dist/types/telemetry/exporters.d.ts +1 -1
  78. package/dist/types/telemetry/healthSetup.d.ts +3 -3
  79. package/dist/types/telemetry/lifecycle.d.ts +4 -4
  80. package/dist/types/telemetry/plugin.d.ts +2 -1
  81. package/dist/types/telemetryCore.d.ts +1 -1
  82. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  83. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  84. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +101 -0
  85. package/dist/types-esm/bff-policy/index.d.mts +1 -0
  86. package/dist/types-esm/bff-policy/node.d.mts +2 -0
  87. package/dist/types-esm/bff-policy/operationContracts.d.mts +85 -0
  88. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  89. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  90. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  91. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  92. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  93. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  94. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  95. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  96. package/dist/types-esm/env.d.mts +40 -0
  97. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  98. package/dist/types-esm/index.d.mts +8 -0
  99. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  100. package/dist/types-esm/mfCache.d.mts +26 -0
  101. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  102. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  103. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  104. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  105. package/dist/types-esm/module-federation-css/remote.d.mts +20 -0
  106. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  107. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  108. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  109. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  110. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  111. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  112. package/dist/types-esm/serverConfig.d.mts +17 -0
  113. package/dist/types-esm/serverPlugin.d.mts +5 -0
  114. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  115. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  116. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  117. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  118. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  119. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  120. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  121. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  122. package/dist/types-esm/telemetry/healthSetup.d.mts +17 -0
  123. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  124. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  125. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  126. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  127. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  128. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +35 -0
  129. package/dist/types-esm/telemetry.d.mts +1 -0
  130. package/dist/types-esm/telemetryCore.d.mts +6 -0
  131. package/package.json +159 -27
  132. package/rslib.config.mts +36 -2
  133. package/rstest.config.mts +11 -0
  134. package/src/bff-policy/crossProjectPolicy.ts +754 -0
  135. package/src/bff-policy/index.ts +1 -0
  136. package/src/bff-policy/node.ts +2 -0
  137. package/src/bff-policy/operationContracts.ts +298 -0
  138. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  139. package/src/contract-gate-snapshot-store/http-store.ts +1 -11
  140. package/src/errorResponsePlugin.ts +21 -0
  141. package/src/index.ts +4 -0
  142. package/src/localisedLoaderPlugin.ts +34 -0
  143. package/src/mfCache.ts +4 -3
  144. package/src/module-federation-css/plugin.ts +4 -3
  145. package/src/serverConfig.ts +32 -0
  146. package/src/serverPlugin.ts +38 -0
  147. package/src/static-serving/plugin.ts +16 -0
  148. package/src/static-serving/responders.ts +208 -0
  149. package/src/static-serving/staticModuleFederation.ts +255 -0
  150. package/src/static-serving/staticPrecompressed.ts +193 -0
  151. package/src/telemetry/exporters.ts +1 -1
  152. package/src/telemetry/healthSetup.ts +17 -20
  153. package/src/telemetry/lifecycle.ts +27 -39
  154. package/src/telemetry/plugin.ts +6 -4
  155. package/src/telemetry/runtimeEndpoints.ts +3 -2
  156. package/src/telemetryCore.ts +1 -1
  157. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +450 -0
  158. package/tests/bff-policy/crossProjectPolicy.test.ts +197 -0
  159. package/tests/bff-policy/operationContracts.test.ts +221 -0
  160. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  161. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +76 -0
  162. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  163. package/tests/contractGateSnapshotStore.test.ts +0 -51
  164. package/tests/env.test.ts +45 -64
  165. package/tests/localisedLoader.test.ts +120 -0
  166. package/tests/mfCache.test.ts +1 -88
  167. package/tests/moduleFederationCss.test.ts +4 -48
  168. package/tests/nativeErrorResponse.test.ts +118 -0
  169. package/tests/nativeServerAssembly.test.ts +385 -0
  170. package/tests/runtimeLifecycle.test.ts +69 -17
  171. package/tests/static-serving/ordering.test.ts +214 -0
  172. package/tests/static-serving/static.test.ts +411 -0
  173. package/tests/telemetry.test.ts +35 -198
  174. package/tests/telemetryHealthMonitor.test.ts +0 -4
  175. package/tests/telemetryHealthObservation.test.ts +302 -0
  176. package/tests/telemetryLifecycle.test.ts +7 -303
  177. package/tests/telemetryRegistryQueueMatrix.test.ts +14 -111
  178. package/tests/registration.test.ts +0 -112
  179. package/tests/telemetryAutopilot.test.ts +0 -1134
@@ -0,0 +1 @@
1
+ export * from './crossProjectPolicy';
@@ -0,0 +1,2 @@
1
+ export * from './operationContracts';
2
+ export * from './resolveCrossProjectPolicy';
@@ -0,0 +1,298 @@
1
+ import { createRequire } from 'node:module';
2
+ import { createHash } from 'crypto';
3
+ import 'reflect-metadata';
4
+
5
+ // Structural handler protocol; native operators retain ownership of metadata.
6
+ type ApiHandler = (...args: any) => any | Promise<any>;
7
+
8
+ export type OperationContractEntry = {
9
+ name: string;
10
+ httpMethod: string;
11
+ routePath: string;
12
+ };
13
+
14
+ export type OperationContractDefinition = {
15
+ requestId: string;
16
+ operationVersion: number;
17
+ schemaHash: string;
18
+ method: string;
19
+ routePath: string;
20
+ operationId: string;
21
+ handlerName: string;
22
+ filename?: string;
23
+ };
24
+
25
+ export type OperationContractMap = Record<string, OperationContractDefinition>;
26
+
27
+ export const DEFAULT_OPERATION_VERSION = 1;
28
+
29
+ /**
30
+ * Derives the operation version from a producer package version: the semver
31
+ * major is the contract version, so consumers regenerated against an older
32
+ * producer major fail the `operation_version_mismatch` gate instead of
33
+ * silently calling an incompatible API.
34
+ *
35
+ * Falls back to {@link DEFAULT_OPERATION_VERSION} when no parseable version
36
+ * is available.
37
+ */
38
+ export const deriveOperationVersion = (packageVersion?: unknown): number => {
39
+ if (typeof packageVersion !== 'string') {
40
+ return DEFAULT_OPERATION_VERSION;
41
+ }
42
+ const match = packageVersion.trim().match(/^v?(\d+)\./);
43
+ if (!match) {
44
+ return DEFAULT_OPERATION_VERSION;
45
+ }
46
+ const major = Number.parseInt(match[1]!, 10);
47
+ return Number.isInteger(major) && major >= 0
48
+ ? major
49
+ : DEFAULT_OPERATION_VERSION;
50
+ };
51
+
52
+ /** JSON.stringify with recursively sorted object keys for stable hashing. */
53
+ const stableStringify = (value: unknown): string => {
54
+ if (Array.isArray(value)) {
55
+ return `[${value.map(item => stableStringify(item)).join(',')}]`;
56
+ }
57
+ if (value && typeof value === 'object') {
58
+ const entries = Object.entries(value as Record<string, unknown>)
59
+ .filter(([, entryValue]) => typeof entryValue !== 'undefined')
60
+ .sort(([a], [b]) => a.localeCompare(b))
61
+ .map(
62
+ ([key, entryValue]) =>
63
+ `${JSON.stringify(key)}:${stableStringify(entryValue)}`,
64
+ );
65
+ return `{${entries.join(',')}}`;
66
+ }
67
+ return JSON.stringify(value) ?? 'null';
68
+ };
69
+
70
+ const sha256 = (text: string) =>
71
+ createHash('sha256').update(text).digest('hex');
72
+
73
+ type ZodToJSONSchema = (schema: unknown, options?: unknown) => unknown;
74
+
75
+ let cachedZodToJSONSchema: ZodToJSONSchema | null | undefined;
76
+
77
+ // FORK: the specifier is assembled at runtime so the bundler cannot see it.
78
+ // A literal require of the zod specifier here is externalized by rslib/rspack
79
+ // into a TOP-LEVEL static import of it in the esm-node output, which makes
80
+ // this OPTIONAL peer a hard runtime requirement: every consumer of
81
+ // this Node policy entry (and its BFF consumers) crashed with
82
+ // ERR_MODULE_NOT_FOUND: zod unless they happened to install zod.
83
+ // Guard: tests/bff-policy/optionalZodPeer.test.ts. Keep the lazy lookup.
84
+ const ZOD_SPECIFIER = ['z', 'o', 'd'].join('');
85
+
86
+ const resolveZodToJSONSchema = (): ZodToJSONSchema | null => {
87
+ if (typeof cachedZodToJSONSchema !== 'undefined') {
88
+ return cachedZodToJSONSchema;
89
+ }
90
+ try {
91
+ // zod is an optional peer dependency: schema serialization degrades to a
92
+ // route-identity hash when it is absent.
93
+ const load = createRequire(
94
+ typeof __filename === 'string' ? __filename : import.meta.url,
95
+ );
96
+ const zod = load(ZOD_SPECIFIER) as Record<string, unknown> & {
97
+ z?: Record<string, unknown>;
98
+ };
99
+ const candidate = zod?.toJSONSchema ?? zod?.z?.toJSONSchema;
100
+ cachedZodToJSONSchema =
101
+ typeof candidate === 'function' ? (candidate as ZodToJSONSchema) : null;
102
+ } catch {
103
+ cachedZodToJSONSchema = null;
104
+ }
105
+ return cachedZodToJSONSchema;
106
+ };
107
+
108
+ const INPUT_SCHEMA_METADATA_KEYS = [
109
+ 'DATA',
110
+ 'QUERY',
111
+ 'PARAMS',
112
+ 'HEADERS',
113
+ 'Files',
114
+ ] as const;
115
+
116
+ const serializeSchema = (schema: unknown): unknown => {
117
+ const toJSONSchema = resolveZodToJSONSchema();
118
+ if (toJSONSchema) {
119
+ try {
120
+ return toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });
121
+ } catch {
122
+ // fall through to the opaque marker below
123
+ }
124
+ }
125
+ // The schema cannot be serialized (non-zod schema, exotic zod type or zod
126
+ // not installed). Contribute a stable marker so the hash still reflects
127
+ // that *a* schema constraint exists on this slot.
128
+ return { __unserializableSchema: true };
129
+ };
130
+
131
+ /**
132
+ * Serializes the zod input schemas attached to an operator-decorated handler
133
+ * (`Data`/`Query`/`Params`/`Headers`/`Upload` metadata) into JSON-schema
134
+ * documents. Returns `undefined` for handlers without schema metadata
135
+ * (plain handlers, farrow schema-mode handlers).
136
+ */
137
+ export const serializeOperationSchemas = (
138
+ handler: ApiHandler | undefined,
139
+ ): Record<string, unknown> | undefined => {
140
+ if (typeof handler !== 'function') {
141
+ return undefined;
142
+ }
143
+ const serialized: Record<string, unknown> = {};
144
+ for (const metadataKey of INPUT_SCHEMA_METADATA_KEYS) {
145
+ let schema: unknown;
146
+ try {
147
+ schema = Reflect.getMetadata(metadataKey, handler);
148
+ } catch {
149
+ schema = undefined;
150
+ }
151
+ if (typeof schema === 'undefined' || schema === null) {
152
+ continue;
153
+ }
154
+ serialized[metadataKey] = serializeSchema(schema);
155
+ }
156
+ return Object.keys(serialized).length > 0 ? serialized : undefined;
157
+ };
158
+
159
+ export type OperationContractHashInput = OperationContractEntry & {
160
+ /** Serialized schema documents; omit for schema-less operations. */
161
+ schemas?: Record<string, unknown> | undefined;
162
+ };
163
+
164
+ /**
165
+ * Per-operation contract hash. The hash covers the operation identity
166
+ * (name, method, route, producer requestId) plus the serialized input
167
+ * schemas, so:
168
+ *
169
+ * - changing an input schema changes the hash of exactly that operation;
170
+ * - reordering routes or adding unrelated operations never rotates the hash
171
+ * of other operations (each operation is hashed independently).
172
+ */
173
+ export const createOperationContractHash = (
174
+ operation: OperationContractHashInput,
175
+ requestId: string,
176
+ ): string =>
177
+ sha256(
178
+ stableStringify({
179
+ httpMethod: String(operation.httpMethod || '').toUpperCase(),
180
+ name: operation.name,
181
+ requestId,
182
+ routePath: operation.routePath,
183
+ ...(operation.schemas ? { schemas: operation.schemas } : {}),
184
+ }),
185
+ );
186
+
187
+ export const createOperationEntries = (
188
+ handlers: Array<{
189
+ name: string;
190
+ httpMethod: string;
191
+ routePath: string;
192
+ }>,
193
+ ): OperationContractEntry[] =>
194
+ handlers
195
+ .map(item => ({
196
+ name: item.name,
197
+ httpMethod: String(item.httpMethod || '').toUpperCase(),
198
+ routePath: item.routePath,
199
+ }))
200
+ .sort((a, b) => {
201
+ const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
202
+ const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
203
+ return keyA.localeCompare(keyB);
204
+ });
205
+
206
+ /**
207
+ * Aggregate hash over a set of per-operation contract hashes. Used for the
208
+ * module-level `operationSchemaHash` manifest export; stable across route
209
+ * reordering because the per-operation hashes are sorted before hashing.
210
+ */
211
+ export const createOperationSchemaHash = (
212
+ operationEntries: Array<OperationContractEntry & { schemaHash?: string }>,
213
+ requestId: string,
214
+ ): string =>
215
+ sha256(
216
+ stableStringify({
217
+ operations: [...operationEntries]
218
+ .map(item => ({
219
+ hash:
220
+ item.schemaHash ??
221
+ createOperationContractHash(
222
+ {
223
+ name: item.name,
224
+ httpMethod: item.httpMethod,
225
+ routePath: item.routePath,
226
+ },
227
+ requestId,
228
+ ),
229
+ }))
230
+ .sort((a, b) => a.hash.localeCompare(b.hash)),
231
+ requestId,
232
+ }),
233
+ );
234
+
235
+ export type OperationContractSource = {
236
+ name: string;
237
+ httpMethod: string;
238
+ routePath: string;
239
+ filename?: string;
240
+ /**
241
+ * Optional handler function used to serialize schema metadata. Sources
242
+ * without a handler (e.g. reflected Effect HttpApi endpoints) hash the
243
+ * route identity only.
244
+ */
245
+ handler?: ApiHandler;
246
+ };
247
+
248
+ export const buildOperationContractMap = ({
249
+ handlers,
250
+ requestId,
251
+ operationVersion,
252
+ }: {
253
+ handlers: OperationContractSource[];
254
+ requestId?: string;
255
+ /**
256
+ * Producer contract version, usually `deriveOperationVersion(pkg.version)`.
257
+ * Defaults to {@link DEFAULT_OPERATION_VERSION}.
258
+ */
259
+ operationVersion?: number;
260
+ }): OperationContractMap => {
261
+ const normalizedRequestId =
262
+ typeof requestId === 'string' && requestId.trim().length > 0
263
+ ? requestId.trim()
264
+ : 'default';
265
+ const normalizedOperationVersion =
266
+ typeof operationVersion === 'number' && Number.isInteger(operationVersion)
267
+ ? operationVersion
268
+ : DEFAULT_OPERATION_VERSION;
269
+
270
+ const contracts: OperationContractMap = {};
271
+ handlers.forEach(item => {
272
+ const httpMethod = String(item.httpMethod || '').toUpperCase();
273
+ const schemaHash = createOperationContractHash(
274
+ {
275
+ name: item.name,
276
+ httpMethod,
277
+ routePath: item.routePath,
278
+ schemas: serializeOperationSchemas(item.handler),
279
+ },
280
+ normalizedRequestId,
281
+ );
282
+ const operationId = `${normalizedRequestId}:${item.name}`;
283
+ const contract: OperationContractDefinition = {
284
+ requestId: normalizedRequestId,
285
+ operationVersion: normalizedOperationVersion,
286
+ schemaHash,
287
+ method: httpMethod,
288
+ routePath: item.routePath,
289
+ operationId,
290
+ handlerName: item.name,
291
+ filename: item.filename,
292
+ };
293
+ contracts[`${httpMethod}:${item.routePath}`] = contract;
294
+ contracts[`operation:${operationId}`] = contract;
295
+ });
296
+
297
+ return contracts;
298
+ };
@@ -0,0 +1,88 @@
1
+ import type {
2
+ CrossProjectPolicyConfig,
3
+ NormalizedCrossProjectPolicy,
4
+ } from './crossProjectPolicy';
5
+ import {
6
+ buildOperationContractMap,
7
+ type OperationContractSource,
8
+ } from './operationContracts';
9
+
10
+ /**
11
+ * Runtime input collected by BFF server adapters (hono/effect/...) before
12
+ * the cross-project policy can be enforced.
13
+ *
14
+ * `crossProjectPolicy` accepts the raw `bff.crossProjectPolicy` user config —
15
+ * `BffCrossProjectPolicyUserConfig` is a structural subset of
16
+ * `CrossProjectPolicyConfig`, so no casts are required at the call site.
17
+ */
18
+ export interface ResolveCrossProjectPolicyInput {
19
+ crossProjectPolicy?: CrossProjectPolicyConfig;
20
+ /** Registered API handlers used to derive the operation-contract map. */
21
+ handlers: OperationContractSource[];
22
+ /** Logical producer ID (`bff.requestId`). */
23
+ requestId?: string;
24
+ /** Marker injected by generated cross-project SDK plugins. */
25
+ isCrossProjectServer?: boolean;
26
+ /**
27
+ * Producer contract version (usually derived from the producer
28
+ * package.json major via `deriveOperationVersion`).
29
+ */
30
+ operationVersion?: number;
31
+ }
32
+
33
+ /**
34
+ * Fully-defaulted policy returned by {@link resolveCrossProjectPolicy}.
35
+ */
36
+ export type ResolvedCrossProjectPolicy = NormalizedCrossProjectPolicy;
37
+
38
+ /**
39
+ * Normalizes the user-facing cross-project policy config into the evaluator
40
+ * input shared by every BFF server adapter:
41
+ *
42
+ * - returns `undefined` when neither a policy nor the cross-project server
43
+ * marker is present (policy middleware must not be installed);
44
+ * - applies the documented defaults for all `require*` switches;
45
+ * - merges generated operation contracts (derived from the registered
46
+ * handlers) over any user-provided `expectedOperationContracts`.
47
+ */
48
+ export const resolveCrossProjectPolicy = (
49
+ input: ResolveCrossProjectPolicyInput,
50
+ ): ResolvedCrossProjectPolicy | undefined => {
51
+ const {
52
+ crossProjectPolicy,
53
+ handlers,
54
+ requestId,
55
+ isCrossProjectServer,
56
+ operationVersion,
57
+ } = input;
58
+ if (!crossProjectPolicy && !isCrossProjectServer) {
59
+ return undefined;
60
+ }
61
+
62
+ const policy: CrossProjectPolicyConfig = crossProjectPolicy ?? {};
63
+ const effectiveRequestId =
64
+ typeof requestId === 'string' && requestId.trim().length > 0
65
+ ? requestId
66
+ : 'default';
67
+ const generatedContracts = buildOperationContractMap({
68
+ handlers,
69
+ requestId: effectiveRequestId,
70
+ operationVersion,
71
+ });
72
+
73
+ return {
74
+ ...policy,
75
+ enabled: policy.enabled ?? Boolean(isCrossProjectServer),
76
+ requireEnvelope: policy.requireEnvelope ?? true,
77
+ requireOperationContext: policy.requireOperationContext ?? true,
78
+ requireOperationContextDetails:
79
+ policy.requireOperationContextDetails ?? true,
80
+ requireOperationSchemaHash: policy.requireOperationSchemaHash ?? true,
81
+ requireOperationVersion: policy.requireOperationVersion ?? true,
82
+ allowUnknownOperations: policy.allowUnknownOperations ?? false,
83
+ expectedOperationContracts: {
84
+ ...(policy.expectedOperationContracts ?? {}),
85
+ ...generatedContracts,
86
+ },
87
+ };
88
+ };
@@ -8,16 +8,6 @@ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from './types';
8
8
 
9
9
  const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5_000;
10
10
 
11
- const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
12
- 'http',
13
- // historical aliases kept for config compatibility with the era when these
14
- // modules lived inside @modern-js/server-core.
15
- '@modern-js/server-core/http',
16
- '@modern-js/server-core/contract-gate-http-store',
17
- '@modern-js/server-runtime-extensions/http',
18
- '@modern-js/server-runtime-extensions/contract-gate-http-store',
19
- ]);
20
-
21
11
  const normalizeHttpStoreOptions = (
22
12
  options: Record<string, unknown> | undefined,
23
13
  ): ContractGateSnapshotHttpStoreOptions => {
@@ -149,7 +139,7 @@ export const tryResolveBuiltinSnapshotStore = (input: {
149
139
  stateStore: ContractGateSnapshotStoreUserConfig;
150
140
  }): ContractGateSnapshotStore | undefined => {
151
141
  const moduleName = input.stateStore.module.trim();
152
- if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) {
142
+ if (moduleName !== 'http') {
153
143
  return undefined;
154
144
  }
155
145
 
@@ -0,0 +1,21 @@
1
+ import { createSafeJsonFailureResponse } from '@modern-js/runtime-extensions/safe-failure';
2
+ import type { ServerPlugin } from '@modern-js/server-core';
3
+
4
+ /** Serialize unhandled BFF failures using the fork's public error contract. */
5
+ export const injectErrorResponsePlugin = (): ServerPlugin => ({
6
+ name: '@modern-js/safe-error-response',
7
+ setup(api) {
8
+ api.handleError(async (input, next) => {
9
+ const prefix = api.getServerConfig().bff?.prefix || '/api';
10
+ const prefixes = Array.isArray(prefix) ? prefix : [prefix];
11
+ if (prefixes.some(value => input.context.req.path.startsWith(value))) {
12
+ return {
13
+ ...input,
14
+ response: createSafeJsonFailureResponse(input.error),
15
+ };
16
+ }
17
+ next?.(input);
18
+ return input;
19
+ });
20
+ },
21
+ });
package/src/index.ts CHANGED
@@ -56,6 +56,10 @@ export {
56
56
  registerServerRuntimeDisposer,
57
57
  type ServerRuntimeHandle,
58
58
  } from './runtimeLifecycle';
59
+ export type {
60
+ UltramodernBffUserConfig,
61
+ UltramodernServerUserConfig,
62
+ } from './serverConfig';
59
63
  export {
60
64
  createOtlpTelemetryExporter,
61
65
  createRuntimeFallbackSignalRuntimeState,
@@ -0,0 +1,34 @@
1
+ import { setLoaderRouteIdResolver } from '@modern-js/plugin-data-loader/runtime';
2
+ import { resolveLocalisedLoaderRouteId } from '@modern-js/runtime-extensions/localised-loader-identity';
3
+ import {
4
+ getLoaderCtx,
5
+ type MiddlewareHandler,
6
+ type ServerPlugin,
7
+ } from '@modern-js/server-core';
8
+
9
+ export function injectLocalisedLoaderPlugin(): ServerPlugin {
10
+ return {
11
+ name: '@modern-js/localised-loader',
12
+ setup(api) {
13
+ const handler: MiddlewareHandler = async (context, next) => {
14
+ setLoaderRouteIdResolver(
15
+ getLoaderCtx(context),
16
+ (requestedRouteId, { routes, matchedRouteIds }) =>
17
+ resolveLocalisedLoaderRouteId(
18
+ routes,
19
+ requestedRouteId,
20
+ matchedRouteIds,
21
+ ),
22
+ );
23
+ await next();
24
+ };
25
+ api.onPrepare(() => {
26
+ api.getServerContext().middlewares.push({
27
+ name: 'localised-loader-route-id',
28
+ before: ['render'],
29
+ handler,
30
+ });
31
+ });
32
+ },
33
+ };
34
+ }
package/src/mfCache.ts CHANGED
@@ -81,12 +81,13 @@ export function resolveMfAssetCacheHeaders(
81
81
  * - `remoteEntry*.js` revalidates unless explicitly version-pinned via a
82
82
  * `mfv`/`v`/`version` query parameter, in which case it is immutable.
83
83
  *
84
- * Registered by @modern-js/prod-server next to the other fork plugins; the
85
- * middleware runs in the `pre` phase so it wraps the static-file middleware
86
- * that actually serves these assets.
84
+ * Composed with the other fork server plugins. The middleware runs in the
85
+ * `pre` phase so it wraps the static-file middleware serving these assets.
87
86
  */
88
87
  export const injectMfAssetCacheHeadersPlugin = (): ServerPlugin => ({
89
88
  name: '@modern-js/inject-mf-asset-cache-headers',
89
+ pre: ['@modern-js/inject-module-federation-css'],
90
+ post: ['@modern-js/plugin-inject-rsc-manifest'],
90
91
 
91
92
  setup(api) {
92
93
  api.onPrepare(() => {
@@ -29,14 +29,15 @@ 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
- * This plugin must be registered after `injectResourcePlugin()` (which sets
33
- * `serverManifest` on the request context). @modern-js/prod-server wires it
34
- * into its plugin assembly for both production and dev servers.
32
+ * Existing plugin ordering places this after the native resource plugin
33
+ * (which sets `serverManifest`) and before the native RSC manifest plugin.
35
34
  */
36
35
  export const injectModuleFederationCssPlugin = (
37
36
  options: ModuleFederationCssPluginOptions = {},
38
37
  ): ServerPlugin => ({
39
38
  name: '@modern-js/inject-module-federation-css',
39
+ pre: ['@modern-js/plugin-inject-resource'],
40
+ post: ['@modern-js/plugin-inject-rsc-manifest'],
40
41
 
41
42
  setup(api) {
42
43
  api.onPrepare(() => {
@@ -0,0 +1,32 @@
1
+ import type {} from '@modern-js/plugin/server';
2
+ import type {
3
+ BffRuntimeUserConfig,
4
+ BffRuntimeFramework as CanonicalBffRuntimeFramework,
5
+ ServerTelemetryConfigExtension,
6
+ } from '@modern-js/runtime-extensions/server-config';
7
+ import type { BffUserConfig, ServerUserConfig } from '@modern-js/server-core';
8
+
9
+ type BffConfigExtension = Omit<BffRuntimeUserConfig, 'runtimeFramework'>;
10
+
11
+ type ForkBffRuntimeRegistry = Record<
12
+ Exclude<CanonicalBffRuntimeFramework, 'hono'>,
13
+ true
14
+ >;
15
+
16
+ declare module '@modern-js/plugin/server' {
17
+ interface BffRuntimeRegistry extends ForkBffRuntimeRegistry {}
18
+ }
19
+
20
+ declare module '@modern-js/server-core' {
21
+ interface BffUserConfig extends BffConfigExtension {}
22
+ interface ServerUserConfig extends ServerTelemetryConfigExtension {}
23
+ }
24
+
25
+ export type UltramodernBffUserConfig = Omit<
26
+ BffUserConfig,
27
+ keyof BffRuntimeUserConfig
28
+ > &
29
+ BffRuntimeUserConfig;
30
+
31
+ export type UltramodernServerUserConfig = ServerUserConfig &
32
+ ServerTelemetryConfigExtension;
@@ -0,0 +1,38 @@
1
+ import './serverConfig';
2
+ import type { ServerPlugin } from '@modern-js/server-core';
3
+ import { injectErrorResponsePlugin } from './errorResponsePlugin';
4
+ import { injectLocalisedLoaderPlugin } from './localisedLoaderPlugin';
5
+ import { injectMfAssetCacheHeadersPlugin } from './mfCache';
6
+ import { injectModuleFederationCssPlugin } from './module-federation-css/plugin';
7
+ import { disposeServerRuntime } from './runtimeLifecycle';
8
+ import { injectStaticServingPlugin } from './static-serving/plugin';
9
+ import { injectTelemetryPlugin } from './telemetry/plugin';
10
+
11
+ /** Compose fork server policies through the native ServerPlugin extension. */
12
+ export const ultramodernServerPlugin = (): ServerPlugin => ({
13
+ name: '@modern-js/ultramodern-server',
14
+ usePlugins: [
15
+ injectLocalisedLoaderPlugin(),
16
+ injectErrorResponsePlugin(),
17
+ injectTelemetryPlugin(),
18
+ injectModuleFederationCssPlugin(),
19
+ injectMfAssetCacheHeadersPlugin(),
20
+ injectStaticServingPlugin(),
21
+ {
22
+ name: '@modern-js/server-runtime-lifecycle',
23
+ // Native disposal reverses registration: Effect resources close before
24
+ // the telemetry lane flushes their final events.
25
+ pre: ['@modern-js/inject-telemetry'],
26
+ setup(api) {
27
+ api.onDispose(() => {
28
+ const { serverBase } = api.getServerContext();
29
+ if (serverBase) {
30
+ return disposeServerRuntime(serverBase);
31
+ }
32
+ });
33
+ },
34
+ },
35
+ ],
36
+ });
37
+
38
+ export default ultramodernServerPlugin;
@@ -0,0 +1,16 @@
1
+ import type { ServerPlugin } from '@modern-js/server-core';
2
+ import { createStaticExtensionResponders } from './responders';
3
+
4
+ export function injectStaticServingPlugin(): ServerPlugin {
5
+ return {
6
+ name: '@modern-js/server-static-extensions',
7
+ post: ['@modern-js/plugin-server-static'],
8
+ setup(api) {
9
+ api.updateServerContext({
10
+ staticAssetResponders: createStaticExtensionResponders(),
11
+ });
12
+ },
13
+ };
14
+ }
15
+
16
+ export default injectStaticServingPlugin;