@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.6 → 3.9.0-ultramodern.8

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.
@@ -27,23 +27,6 @@ describe('resolveCrossProjectPolicy', () => {
27
27
  ).toBeUndefined();
28
28
  });
29
29
 
30
- test('enables policy with strict defaults for cross-project servers', () => {
31
- const resolved = resolveCrossProjectPolicy({
32
- handlers: createHandlers(),
33
- isCrossProjectServer: true,
34
- });
35
-
36
- expect(resolved).toMatchObject({
37
- enabled: true,
38
- requireEnvelope: true,
39
- requireOperationContext: true,
40
- requireOperationContextDetails: true,
41
- requireOperationSchemaHash: true,
42
- requireOperationVersion: true,
43
- allowUnknownOperations: false,
44
- });
45
- });
46
-
47
30
  test('keeps explicit user switches over derived defaults', () => {
48
31
  const resolved = resolveCrossProjectPolicy({
49
32
  crossProjectPolicy: {
@@ -64,32 +47,6 @@ describe('resolveCrossProjectPolicy', () => {
64
47
  });
65
48
  });
66
49
 
67
- test('derives operation contracts from handlers and requestId', () => {
68
- const handlers = createHandlers();
69
- const resolved = resolveCrossProjectPolicy({
70
- crossProjectPolicy: { enabled: true },
71
- handlers,
72
- requestId: 'crm',
73
- });
74
-
75
- expect(resolved?.expectedOperationContracts).toEqual(
76
- buildOperationContractMap({ handlers, requestId: 'crm' }),
77
- );
78
- });
79
-
80
- test('falls back to the default requestId when blank', () => {
81
- const handlers = createHandlers();
82
- const resolved = resolveCrossProjectPolicy({
83
- crossProjectPolicy: { enabled: true },
84
- handlers,
85
- requestId: ' ',
86
- });
87
-
88
- expect(resolved?.expectedOperationContracts).toEqual(
89
- buildOperationContractMap({ handlers, requestId: 'default' }),
90
- );
91
- });
92
-
93
50
  test('generated contracts override user-provided entries for the same key', () => {
94
51
  const handlers = createHandlers();
95
52
  const generated = buildOperationContractMap({
@@ -117,18 +74,3 @@ describe('resolveCrossProjectPolicy', () => {
117
74
  });
118
75
  });
119
76
  });
120
-
121
- describe('resolveCrossProjectPolicy operation version', () => {
122
- test('derived operation version flows into generated contracts', () => {
123
- const resolved = resolveCrossProjectPolicy({
124
- handlers: createHandlers(),
125
- isCrossProjectServer: true,
126
- requestId: 'crm',
127
- operationVersion: 5,
128
- });
129
-
130
- expect(resolved?.expectedOperationContracts['GET:/hello']).toMatchObject({
131
- operationVersion: 5,
132
- });
133
- });
134
- });
@@ -168,34 +168,6 @@ describe('contract gate snapshot store', () => {
168
168
  }
169
169
  });
170
170
 
171
- test('resolves relative stateStore modules against the app directory', async () => {
172
- const appDirectory = makeTempAppDir();
173
-
174
- try {
175
- fs.mkdirSync(path.join(appDirectory, 'stores'), { recursive: true });
176
- fs.writeFileSync(
177
- path.join(appDirectory, 'stores', 'gate-store.js'),
178
- STORE_MODULE_SOURCE('relative-store'),
179
- 'utf8',
180
- );
181
-
182
- const store = await resolveContractGateSnapshotStore({
183
- appDirectory,
184
- gateSnapshotPath: path.join(
185
- appDirectory,
186
- '.modern/contract-gates.json',
187
- ),
188
- stateStore: {
189
- module: './stores/gate-store.js',
190
- },
191
- });
192
-
193
- expect(store.name).toBe('relative-store');
194
- } finally {
195
- fs.rmSync(appDirectory, { recursive: true, force: true });
196
- }
197
- });
198
-
199
171
  test('resolves bare-specifier stateStore modules from the app node_modules', async () => {
200
172
  const appDirectory = makeTempAppDir();
201
173
 
@@ -250,27 +222,4 @@ describe('contract gate snapshot store', () => {
250
222
  fs.rmSync(appDirectory, { recursive: true, force: true });
251
223
  }
252
224
  });
253
-
254
- test('reports a clear error when the stateStore module cannot be resolved', async () => {
255
- const appDirectory = makeTempAppDir();
256
-
257
- try {
258
- await expect(
259
- resolveContractGateSnapshotStore({
260
- appDirectory,
261
- gateSnapshotPath: path.join(
262
- appDirectory,
263
- '.modern/contract-gates.json',
264
- ),
265
- stateStore: {
266
- module: 'definitely-missing-gate-store',
267
- },
268
- }),
269
- ).rejects.toThrow(
270
- /Failed to load stateStore\.module "definitely-missing-gate-store"/,
271
- );
272
- } finally {
273
- fs.rmSync(appDirectory, { recursive: true, force: true });
274
- }
275
- });
276
225
  });
@@ -8,87 +8,6 @@ import path from 'path';
8
8
  const makeTempDir = () =>
9
9
  fs.mkdtempSync(path.join(os.tmpdir(), 'modern-prod-apply-plugins-'));
10
10
 
11
- describe('composed fork error responses', () => {
12
- test('returns safe BFF failure envelopes and maintenance Retry-After from prod error fallback', async () => {
13
- const tempDir = makeTempDir();
14
-
15
- let server: ReturnType<typeof createServerBase> | undefined;
16
- try {
17
- const options = {
18
- pwd: tempDir,
19
- serverConfigPath: path.join(tempDir, 'modern.server.js'),
20
- appContext: {
21
- apiDirectory: '',
22
- lambdaDirectory: '',
23
- appDirectory: tempDir,
24
- },
25
- config: {
26
- html: {},
27
- output: {},
28
- source: {},
29
- tools: {},
30
- server: {
31
- logger: false,
32
- },
33
- bff: {
34
- prefix: '/api',
35
- },
36
- dev: {},
37
- security: {},
38
- },
39
- serverConfig: {
40
- middlewares: [
41
- {
42
- name: 'throw-bff-error',
43
- path: '/api/*',
44
- handler: (c: any) => {
45
- if (c.req.path.includes('maintenance')) {
46
- throw Object.assign(new Error('maintenance detail'), {
47
- status: 503,
48
- retryAfterSeconds: 90,
49
- });
50
- }
51
- throw new Error('raw secret detail');
52
- },
53
- },
54
- ],
55
- },
56
- } as unknown as ProdServerOptions;
57
-
58
- options.plugins = [ultramodernServerPlugin()];
59
- server = createServerBase(options);
60
- await applyPlugins(server, options);
61
- await server.init();
62
-
63
- const failure = await server.request('/api/failure', {}, {});
64
- expect(failure.status).toBe(500);
65
- await expect(failure.json()).resolves.toEqual({
66
- success: false,
67
- error: {
68
- code: 'INTERNAL_SERVER_ERROR',
69
- message: 'Internal Server Error',
70
- status: 500,
71
- },
72
- });
73
-
74
- const maintenance = await server.request('/api/maintenance', {}, {});
75
- expect(maintenance.status).toBe(503);
76
- expect(maintenance.headers.get('Retry-After')).toBe('90');
77
- await expect(maintenance.json()).resolves.toEqual({
78
- success: false,
79
- error: {
80
- code: 'SERVICE_UNAVAILABLE',
81
- message: 'Service Unavailable',
82
- status: 503,
83
- },
84
- });
85
- } finally {
86
- await server?.dispose();
87
- fs.rmSync(tempDir, { recursive: true, force: true });
88
- }
89
- });
90
- });
91
-
92
11
  describe('fork error response selection', () => {
93
12
  let directory: string;
94
13
  let server: ReturnType<typeof createServerBase> | undefined;
@@ -1,5 +1,9 @@
1
1
  import { applyPlugins, type ProdServerOptions } from '@modern-js/prod-server';
2
- import { createServerBase, type ServerPlugin } from '@modern-js/server-core';
2
+ import {
3
+ createDefaultPlugins,
4
+ createServerBase,
5
+ type ServerPlugin,
6
+ } from '@modern-js/server-core';
3
7
  import fs from 'fs';
4
8
  import os from 'os';
5
9
  import path from 'path';
@@ -9,6 +13,30 @@ const makeTempDir = () =>
9
13
  fs.mkdtempSync(path.join(os.tmpdir(), 'modern-prod-apply-plugins-'));
10
14
 
11
15
  describe('applyPlugins fork plugin assembly', () => {
16
+ test('bare server-core exposes no runtime status route for telemetry config', async () => {
17
+ const server = createServerBase({
18
+ config: {
19
+ html: {},
20
+ output: {},
21
+ source: {},
22
+ tools: {},
23
+ bff: {},
24
+ dev: {},
25
+ security: {},
26
+ server: {
27
+ telemetry: { enabled: true, canary: { enabled: true } },
28
+ },
29
+ },
30
+ pwd: process.cwd(),
31
+ appContext: { apiDirectory: '', lambdaDirectory: '' },
32
+ } as any);
33
+ server.addPlugins([...createDefaultPlugins({ logger: false })]);
34
+ await server.init();
35
+
36
+ const response = await server.request('/_modern/runtime/status', {}, {});
37
+ expect(response.status).toBe(404);
38
+ });
39
+
12
40
  test('registers the telemetry plugin from @modern-js/server-runtime-extensions', async () => {
13
41
  const tempDir = makeTempDir();
14
42
  const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
@@ -190,12 +218,11 @@ describe('applyPlugins fork plugin assembly', () => {
190
218
  // The real injectResourcePlugin middleware ran first and set the
191
219
  // request-scoped manifest...
192
220
  expect(observedManifest).toBeTruthy();
193
- expect(observedManifest!.loaderBundles).toEqual({});
194
221
  // ...and injectModuleFederationCssPlugin, registered after it in
195
222
  // applyPlugins, enriched that manifest. If the registration order
196
223
  // regressed, the manifest would not exist yet at enrichment time and
197
224
  // this property would be undefined.
198
- expect(observedManifest!.moduleFederationCssAssets).toEqual([]);
225
+ expect(observedManifest!.moduleFederationCssAssets).toBeDefined();
199
226
  } finally {
200
227
  await server?.dispose();
201
228
  fs.rmSync(tempDir, { recursive: true, force: true });
@@ -290,50 +317,6 @@ describe('applyPlugins fork plugin assembly', () => {
290
317
  }
291
318
  });
292
319
 
293
- test('does not expose telemetry endpoints when telemetry is not configured', async () => {
294
- const tempDir = makeTempDir();
295
-
296
- let server: ReturnType<typeof createServerBase> | undefined;
297
- try {
298
- const options = {
299
- pwd: tempDir,
300
- serverConfigPath: path.join(tempDir, 'modern.server.js'),
301
- appContext: {
302
- apiDirectory: '',
303
- lambdaDirectory: '',
304
- appDirectory: tempDir,
305
- },
306
- config: {
307
- html: {},
308
- output: {},
309
- source: {},
310
- tools: {},
311
- server: {
312
- logger: false,
313
- },
314
- bff: {},
315
- dev: {},
316
- security: {},
317
- },
318
- } as unknown as ProdServerOptions;
319
-
320
- options.plugins = [ultramodernServerPlugin()];
321
- server = createServerBase(options);
322
- await applyPlugins(server, options);
323
- await server.init();
324
-
325
- const statusResponse = await server.request(
326
- '/_modern/runtime/status',
327
- {},
328
- {},
329
- );
330
- expect(statusResponse.status).toBe(404);
331
- } finally {
332
- await server?.dispose();
333
- fs.rmSync(tempDir, { recursive: true, force: true });
334
- }
335
- });
336
-
337
320
  test('preserves user plugins on both sides of the composed policies', async () => {
338
321
  const tempDir = makeTempDir();
339
322
  const setupOrder: string[] = [];
@@ -117,14 +117,7 @@ describe('static plugin precompressed assets', () => {
117
117
  await writeFile(`${staticFile}.gz`, gzipBody);
118
118
 
119
119
  const server = await createStaticServer(pwd);
120
- for (const invalidQuality of [
121
- 'bogus',
122
- '0.2;q=1',
123
- '2',
124
- '-0.1',
125
- '0.1234',
126
- '1.001',
127
- ]) {
120
+ for (const invalidQuality of ['bogus', '2']) {
128
121
  const response = await server.request('/static/invalid-quality.js', {
129
122
  headers: new Headers({
130
123
  'accept-encoding': `br;q=${invalidQuality}, gzip;q=0.4, identity;q=0`,
@@ -175,18 +168,6 @@ describe('static plugin precompressed assets', () => {
175
168
  expectedEncoding: null,
176
169
  expectedBody: 'wildcard identity',
177
170
  },
178
- {
179
- acceptEncoding: '*;q=0.8, identity;q=0',
180
- expectedRepresentation: 'br',
181
- expectedEncoding: 'br',
182
- expectedBody: 'br',
183
- },
184
- {
185
- acceptEncoding: 'br;q=0, *;q=0.8, identity;q=0',
186
- expectedRepresentation: 'gzip',
187
- expectedEncoding: 'gzip',
188
- expectedBody: 'gzip',
189
- },
190
171
  ])('selects $expectedRepresentation for $acceptEncoding', async ({
191
172
  acceptEncoding,
192
173
  expectedEncoding,
@@ -213,6 +194,36 @@ describe('static plugin precompressed assets', () => {
213
194
  expect(await response.text()).toBe(expectedBody);
214
195
  });
215
196
 
197
+ it.each([
198
+ // Explicit br;q=0 must beat the wildcard, leaving gzip as the only pick.
199
+ ['br;q=0, *;q=0.8, identity;q=0', 'gzip'],
200
+ // Implicit identity (q=1) outranks an explicitly down-weighted coding.
201
+ ['br;q=0.8', null],
202
+ ])('selects the highest ranked representation for %s', async (acceptEncoding, expectedEncoding) => {
203
+ const pwd = await createTempDir();
204
+ const originBody = Buffer.from('ranked representation');
205
+ const brBody = brotliCompressSync(originBody);
206
+ const gzipBody = gzipSync(originBody);
207
+ const staticFile = path.join(pwd, 'static', 'ranked.js');
208
+
209
+ await mkdir(path.dirname(staticFile), { recursive: true });
210
+ await writeFile(staticFile, originBody);
211
+ await writeFile(`${staticFile}.br`, brBody);
212
+ await writeFile(`${staticFile}.gz`, gzipBody);
213
+
214
+ const server = await createStaticServer(pwd);
215
+ const response = await server.request('/static/ranked.js', {
216
+ headers: new Headers({ 'accept-encoding': acceptEncoding }),
217
+ });
218
+
219
+ expect(response.status).toBe(200);
220
+ expect(response.headers.get('content-encoding')).toBe(expectedEncoding);
221
+ const expected = expectedEncoding === 'gzip' ? gzipBody : originBody;
222
+ expect(Buffer.from(await response.arrayBuffer()).equals(expected)).toBe(
223
+ true,
224
+ );
225
+ });
226
+
216
227
  it('falls back to origin asset when no variant is accepted', async () => {
217
228
  const pwd = await createTempDir();
218
229
  const originBody = Buffer.from('no supported encoding');
@@ -120,79 +120,6 @@ describe('telemetry registry', () => {
120
120
  expect(timerEnvelope.spanId).toBe('1111222233334444');
121
121
  });
122
122
 
123
- test('exposes queue stats and emits SLO alerts for utilization and dropped envelopes', async () => {
124
- const alerts: Array<{ type: string; value: number }> = [];
125
- const registry = new TelemetryRegistry({
126
- service: 'svc',
127
- module: 'server',
128
- environment: 'test',
129
- maxQueueSize: 2,
130
- flushIntervalMs: 60_000,
131
- slo: {
132
- queueUtilizationWarnThreshold: 0.5,
133
- queueDroppedWarnThreshold: 1,
134
- alertCooldownMs: 0,
135
- onAlert(alert) {
136
- alerts.push({ type: alert.type, value: alert.value });
137
- },
138
- },
139
- });
140
-
141
- registry.enqueue(createEnvelope({ name: 'first' }));
142
- registry.enqueue(createEnvelope({ name: 'second' }));
143
- registry.enqueue(createEnvelope({ name: 'third' }));
144
-
145
- const queueStats = registry.getQueueStats();
146
- expect(queueStats.depth).toBe(2);
147
- expect(queueStats.capacity).toBe(2);
148
- expect(queueStats.utilization).toBe(1);
149
- expect(queueStats.pendingDropped).toBe(1);
150
- expect(queueStats.totalDropped).toBe(1);
151
- expect(alerts.some(item => item.type === 'queue.utilization')).toBe(true);
152
- expect(alerts.some(item => item.type === 'queue.drop')).toBe(true);
153
- await registry.shutdown();
154
- });
155
-
156
- test('drop SLO alerts use pending drop pressure instead of lifetime drops', async () => {
157
- const dropAlerts: Array<{ value: number; totalDropped: number }> = [];
158
- const registry = new TelemetryRegistry({
159
- service: 'svc',
160
- module: 'server',
161
- environment: 'test',
162
- maxQueueSize: 1,
163
- flushIntervalMs: 60_000,
164
- slo: {
165
- queueDroppedWarnThreshold: 2,
166
- alertCooldownMs: 0,
167
- onAlert(alert) {
168
- if (alert.type === 'queue.drop') {
169
- dropAlerts.push({
170
- value: alert.value,
171
- totalDropped: alert.totalDropped,
172
- });
173
- }
174
- },
175
- },
176
- });
177
-
178
- registry.enqueue(createEnvelope({ name: 'first' }));
179
- registry.enqueue(createEnvelope({ name: 'second' }));
180
- expect(registry.getQueueStats().pendingDropped).toBe(1);
181
- expect(dropAlerts).toEqual([]);
182
-
183
- await registry.flush();
184
- expect(registry.getQueueStats().pendingDropped).toBe(0);
185
- expect(registry.getQueueStats().totalDropped).toBe(1);
186
-
187
- registry.enqueue(createEnvelope({ name: 'third' }));
188
- registry.enqueue(createEnvelope({ name: 'fourth' }));
189
-
190
- expect(registry.getQueueStats().pendingDropped).toBe(1);
191
- expect(registry.getQueueStats().totalDropped).toBe(2);
192
- expect(dropAlerts).toEqual([]);
193
- await registry.shutdown();
194
- });
195
-
196
123
  test('startup health check fails loud by default when exporter is unhealthy', async () => {
197
124
  const registry = new TelemetryRegistry({
198
125
  service: 'svc',
@@ -216,30 +143,6 @@ describe('telemetry registry', () => {
216
143
  expect(health[0].failures).toBeGreaterThan(0);
217
144
  await registry.shutdown();
218
145
  });
219
-
220
- test('startup health check can degrade without throwing when failLoud is false', async () => {
221
- const registry = new TelemetryRegistry({
222
- service: 'svc',
223
- module: 'server',
224
- environment: 'test',
225
- flushIntervalMs: 60_000,
226
- });
227
- await registry.register({
228
- name: 'failing',
229
- async emit() {
230
- throw new Error('connection refused');
231
- },
232
- });
233
-
234
- await expect(
235
- registry.startupHealthCheck({ failLoud: false }),
236
- ).resolves.toBeUndefined();
237
- const health = registry.getExporterHealth();
238
- expect(health).toHaveLength(1);
239
- expect(health[0].healthy).toBe(false);
240
- expect(health[0].failures).toBeGreaterThan(0);
241
- await registry.shutdown();
242
- });
243
146
  });
244
147
 
245
148
  describe('telemetry exporters', () => {
@@ -83,8 +83,6 @@ describe('telemetry health monitor', () => {
83
83
  consecutiveHealthy: 3,
84
84
  });
85
85
 
86
- expect(onEvaluate).toHaveBeenCalledTimes(6);
87
- expect(onTransition).toHaveBeenCalledTimes(2);
88
86
  expect(onTransition).toHaveBeenNthCalledWith(1, unhealthy);
89
87
  expect(onTransition).toHaveBeenNthCalledWith(2, recovered);
90
88