@ruyalab/webmonitor-nextjs 1.0.0 → 1.2.0

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.
@@ -79,6 +79,30 @@ function ensureKey() {
79
79
  return key;
80
80
  }
81
81
 
82
+ // Server-error tracking: Next.js loads instrumentation.(ts|js) from the project root or src/.
83
+ function writeInstrumentation() {
84
+ const router = findRouterDir();
85
+ const base = router && router.dir.startsWith('src/') ? 'src' : '.';
86
+ const ext = fs.existsSync(path.join(root, 'tsconfig.json')) ? 'ts' : 'js';
87
+ const existing = ['instrumentation.ts', 'instrumentation.js', 'src/instrumentation.ts', 'src/instrumentation.js']
88
+ .find((f) => fs.existsSync(path.join(root, f)));
89
+ const line = "export { register, onRequestError } from '@ruyalab/webmonitor-nextjs/instrumentation';";
90
+ if (existing) {
91
+ const text = fs.readFileSync(path.join(root, existing), 'utf8');
92
+ if (text.includes('@ruyalab/webmonitor-nextjs/instrumentation')) {
93
+ console.log(green(`✔ Server-error tracking already in ${existing}`));
94
+ } else {
95
+ console.log(yellow(`! ${existing} already exists. To track server errors, call Web Monitor's hooks from it:`));
96
+ console.log(" import { register as wmRegister, onRequestError as wmError } from '@ruyalab/webmonitor-nextjs/instrumentation';");
97
+ console.log(' // call wmRegister() in your register(), and wmError(error, request, context) in your onRequestError()');
98
+ }
99
+ return;
100
+ }
101
+ const file = path.join(base, `instrumentation.${ext}`);
102
+ fs.writeFileSync(path.join(root, file), `// Web Monitor: counts server errors so the dashboard can say which route is failing (Next.js 15+).\n${line}\n`);
103
+ console.log(green(`✔ Created ${file} (server-error tracking)`));
104
+ }
105
+
82
106
  if (command === 'init') {
83
107
  const pkgFile = path.join(root, 'package.json');
84
108
  if (!fs.existsSync(pkgFile)) fail('No package.json here. Run this in the root of your Next.js project.');
@@ -87,6 +111,7 @@ if (command === 'init') {
87
111
  console.log(yellow('! "next" is not in package.json — make sure you are in your Next.js project root.'));
88
112
  }
89
113
  writeRoute();
114
+ writeInstrumentation();
90
115
  const key = ensureKey();
91
116
  console.log(`
92
117
  Next steps
package/index.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  export declare const VERSION: string;
2
2
  export declare const ENDPOINTS: string[];
3
3
 
4
+ /** instrumentation.ts: export { register, onRequestError } from '@ruyalab/webmonitor-nextjs/instrumentation'; */
5
+ export declare function register(): void;
6
+ export declare function onRequestError(error: unknown, request: { path?: string; method?: string }, context?: { routePath?: string }): void;
7
+ export declare function getComponents(): { id: string; name: string; status: 'ok' | 'warning' | 'error' | 'unknown'; message: string; hint?: string }[];
8
+
4
9
  export declare function handleWebMonitorRequest(
5
10
  endpoint: string,
6
11
  request: { authorization?: string | null; origin: string; forwardedProto?: string | null },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruyalab/webmonitor-nextjs",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Connect a Next.js site to Web Monitor (webmonitor.ruyalab.com): uptime, performance, SEO and security checks.",
5
5
  "keywords": [
6
6
  "nextjs",
@@ -27,6 +27,10 @@
27
27
  "./pages-router": {
28
28
  "types": "./index.d.ts",
29
29
  "default": "./src/pages-router.js"
30
+ },
31
+ "./instrumentation": {
32
+ "types": "./index.d.ts",
33
+ "default": "./src/instrumentation.js"
30
34
  }
31
35
  },
32
36
  "bin": {
package/src/core.js CHANGED
@@ -3,10 +3,13 @@
3
3
  // is reported as null / "not_available", never guessed.
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
+ import v8 from 'node:v8';
6
7
  import path from 'node:path';
8
+ import { createRequire } from 'node:module';
7
9
  import { timingSafeEqual } from 'node:crypto';
10
+ import { errorStore } from './instrumentation.js';
8
11
 
9
- export const VERSION = '1.0.0';
12
+ export const VERSION = '1.2.0';
10
13
  export const ENDPOINTS = ['health', 'analytics', 'performance', 'seo', 'security', 'libraries', 'logs', 'recommendations'];
11
14
 
12
15
  const projectRoot = () => process.cwd();
@@ -21,6 +24,16 @@ function readJson(file) {
21
24
 
22
25
  const installedVersion = (name) => readJson(path.join(projectRoot(), 'node_modules', name, 'package.json'))?.version ?? null;
23
26
 
27
+ function nextVersion() {
28
+ const fromDisk = installedVersion('next');
29
+ if (fromDisk) return fromDisk;
30
+ try {
31
+ return createRequire(import.meta.url)('next/package.json').version || null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
24
37
  function safeEqual(a, b) {
25
38
  const left = Buffer.from(String(a));
26
39
  const right = Buffer.from(String(b));
@@ -29,6 +42,19 @@ function safeEqual(a, b) {
29
42
 
30
43
  const round = (value, digits = 2) => (value == null ? null : Number(value.toFixed(digits)));
31
44
 
45
+ // Node.js settings that decide whether some vulnerabilities apply (WebMonitor's Release Radar uses them to say
46
+ // "exposed" or "not exposed"). Flags only, never values of environment variables other than NODE_ENV.
47
+ export function securityConfig() {
48
+ const args = [...process.execArgv, ...String(process.env.NODE_OPTIONS || '').split(/\s+/)];
49
+ const env = String(process.env.NODE_ENV || '');
50
+ return {
51
+ 'node.permission_model': Boolean(process.permission) || args.some((a) => /^--(experimental-)?permission$/.test(a)),
52
+ 'node.inspector': args.some((a) => /^--inspect(-brk|-wait)?(=|$)/.test(a)),
53
+ 'node.experimental_flags': args.some((a) => /^--experimental-/.test(a)),
54
+ 'node.env': /^[\w.-]{1,20}$/.test(env) ? env : '',
55
+ };
56
+ }
57
+
32
58
  function systemMemoryPercent() {
33
59
  return round(((os.totalmem() - os.freemem()) / os.totalmem()) * 100);
34
60
  }
@@ -80,26 +106,80 @@ function diskStats() {
80
106
  }
81
107
  }
82
108
 
109
+ // ---- server errors (Next.js onRequestError hook) ---------------------------------------------
110
+ // Kept on globalThis: Next.js bundles instrumentation.ts and the API route separately, so a module-level
111
+ // variable would not be shared. Counts cover this server process (on serverless, the instance answering).
112
+
113
+ const component = (id, name, status, message, hint) => ({ id, name, status, message: String(message).slice(0, 200), ...(hint ? { hint } : {}) });
114
+
115
+ function errorsComponent() {
116
+ const store = errorStore();
117
+ if (!store.hooked && store.items.length === 0) {
118
+ return component('server_errors', 'Server errors', 'unknown', 'Not tracked yet.',
119
+ "Add instrumentation.ts with: export { register, onRequestError } from '@ruyalab/webmonitor-nextjs/instrumentation';");
120
+ }
121
+ const now = Date.now();
122
+ const recent = store.items.filter((e) => e.at >= now - 15 * 60_000);
123
+ const hour = store.items.filter((e) => e.at >= now - 60 * 60_000);
124
+ if (!hour.length) return component('server_errors', 'Server errors', 'ok', 'No server errors in the last hour.');
125
+ const last = hour[hour.length - 1];
126
+ // The route that failed most often in the last hour.
127
+ const byRoute = {};
128
+ for (const e of hour) byRoute[e.route || e.path] = (byRoute[e.route || e.path] || 0) + 1;
129
+ const [worst, worstCount] = Object.entries(byRoute).sort((a, b) => b[1] - a[1])[0];
130
+ const status = recent.length >= 5 ? 'error' : 'warning';
131
+ return component('server_errors', 'Server errors', status,
132
+ `${hour.length} server error${hour.length === 1 ? '' : 's'} in the last hour (${recent.length} in 15 min), most on ${worst} (${worstCount}). Latest: ${last.message}`,
133
+ (() => {
134
+ const lastOnWorst = [...hour].reverse().find((e) => (e.route || e.path) === worst);
135
+ return `Check the server logs for ${worst}${lastOnWorst?.digest ? ` (digest ${lastOnWorst.digest})` : ''}.`;
136
+ })());
137
+ }
138
+
139
+ function heapComponent() {
140
+ const h = v8.getHeapStatistics();
141
+ const pct = round((h.used_heap_size / h.heap_size_limit) * 100, 1);
142
+ return component('node_memory', 'Node.js memory', pct >= 95 ? 'error' : pct >= 85 ? 'warning' : 'ok',
143
+ `Heap ${pct}% of its ${Math.round(h.heap_size_limit / 1048576)} MB limit.`,
144
+ pct >= 85 ? 'Look for a memory leak (large caches, unclosed connections) or raise --max-old-space-size.' : null);
145
+ }
146
+
147
+ function diskComponent() {
148
+ const d = diskStats();
149
+ if (d.freePercent == null) return null;
150
+ return component('disk', 'Disk space', d.freePercent < 5 ? 'error' : d.freePercent < 15 ? 'warning' : 'ok',
151
+ `${d.freePercent}% free (${round(d.freeBytes / 1073741824, 1)} GB).`,
152
+ d.freePercent < 15 ? 'Free space: build caches (.next/cache), logs and old deployments.' : null);
153
+ }
154
+
155
+ export function getComponents() {
156
+ return [errorsComponent(), heapComponent(), diskComponent()].filter(Boolean);
157
+ }
158
+
83
159
  // ---- endpoints ------------------------------------------------------------------------------
84
160
 
85
161
  function getHealth() {
86
162
  const start = performance.now();
87
163
  const memory = systemMemoryPercent();
88
- const status = memory >= 95 ? 'warning' : 'healthy';
164
+ const components = getComponents();
165
+ const failing = components.find((c) => c.status === 'error') || components.find((c) => c.status === 'warning');
166
+ const status = failing || memory >= 95 ? 'warning' : 'healthy';
89
167
  return {
90
168
  status,
91
- message: status === 'healthy' ? 'Site is healthy' : 'Server memory usage is above 95%',
169
+ message: failing ? `${failing.name}: ${failing.message}` : memory >= 95 ? 'Server memory usage is above 95%' : 'Site is healthy',
92
170
  timestamp: new Date().toISOString(),
93
171
  response_time: round(performance.now() - start),
94
172
  node_version: process.version,
95
- nextjs_version: installedVersion('next'),
173
+ nextjs_version: nextVersion(),
96
174
  framework: 'Next.js',
97
175
  integration_version: VERSION,
176
+ security_config: securityConfig(),
98
177
  uptime_seconds: Math.round(os.uptime()),
99
178
  checks: {
100
179
  memory_usage: `${memory}%`,
101
180
  load_average: process.platform === 'win32' ? null : round(os.loadavg()[0]),
102
181
  },
182
+ components,
103
183
  };
104
184
  }
105
185
 
@@ -260,7 +340,7 @@ async function getSecurity(ctx) {
260
340
  total_plugins: null,
261
341
  outdated_plugins: null,
262
342
  node_version: process.version,
263
- nextjs_version: installedVersion('next'),
343
+ nextjs_version: nextVersion(),
264
344
  recommendations,
265
345
  };
266
346
  }
@@ -287,7 +367,7 @@ function getLibraries() {
287
367
  all_libraries: [...dependencies, ...devDependencies],
288
368
  outdated_count: null,
289
369
  node_version: process.version,
290
- nextjs_version: installedVersion('next'),
370
+ nextjs_version: nextVersion(),
291
371
  };
292
372
  }
293
373
 
package/src/index.js CHANGED
@@ -1,3 +1,4 @@
1
- export { handleWebMonitorRequest, ENDPOINTS, VERSION } from './core.js';
1
+ export { handleWebMonitorRequest, ENDPOINTS, VERSION, getComponents } from './core.js';
2
+ export { onRequestError, register } from './instrumentation.js';
2
3
  export { GET } from './app-router.js';
3
4
  export { default as pagesHandler } from './pages-router.js';
@@ -0,0 +1,27 @@
1
+ // Next.js instrumentation hooks. No Node.js imports: Next also loads instrumentation.ts in the edge runtime.
2
+ // In your project's instrumentation.ts:
3
+ // export { register, onRequestError } from '@ruyalab/webmonitor-nextjs/instrumentation';
4
+ // Errors are kept on globalThis because Next bundles instrumentation.ts and the API route separately.
5
+
6
+ const ERRORS_MAX = 200;
7
+
8
+ export const errorStore = () => (globalThis.__webmonitorErrors ??= { hooked: false, items: [] });
9
+
10
+ /** Called once when the server starts; marks error tracking as installed. */
11
+ export function register() {
12
+ errorStore().hooked = true;
13
+ }
14
+
15
+ /** Called by Next.js 15+ for every error thrown while handling a request. */
16
+ export function onRequestError(error, request, context) {
17
+ const store = errorStore();
18
+ store.hooked = true;
19
+ store.items.push({
20
+ at: Date.now(),
21
+ path: String(request?.path || '').split('?')[0].slice(0, 120),
22
+ route: context?.routePath ? String(context.routePath).slice(0, 120) : null,
23
+ message: String(error?.message || error || 'Error').slice(0, 160),
24
+ digest: error?.digest || null,
25
+ });
26
+ if (store.items.length > ERRORS_MAX) store.items.splice(0, store.items.length - ERRORS_MAX);
27
+ }